rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
q = ''
|
def __init__(self, title=None, author=None, publisher=None, isbn=None, keywords=None, max_results=20): assert not(title is None and author is None and publisher is None \ and isbn is None and keywords is None) assert (max_results < 21)
|
|
q += isbn
|
q = isbn
|
def __init__(self, title=None, author=None, publisher=None, isbn=None, keywords=None, max_results=20): assert not(title is None and author is None and publisher is None \ and isbn is None and keywords is None) assert (max_results < 21)
|
if title is not None: q += title if author is not None: q += author if publisher is not None: q += publisher if keywords is not None: q += keywords
|
q = ' '.join([i for i in (title, author, publisher, keywords) \ if i is not None])
|
def __init__(self, title=None, author=None, publisher=None, isbn=None, keywords=None, max_results=20): assert not(title is None and author is None and publisher is None \ and isbn is None and keywords is None) assert (max_results < 21)
|
self.repub = re.compile(r'\s*.diteur\s*', re.I) self.reauteur = re.compile(r'\s*auteur.*', re.I) self.reautclean = re.compile(r'\s*\(.*\)\s*')
|
self.repub = re.compile(u'\s*.diteur\s*', re.I) self.reauteur = re.compile(u'\s*auteur.*', re.I) self.reautclean = re.compile(u'\s*\(.*\)\s*')
|
def __init__(self): self.repub = re.compile(r'\s*.diteur\s*', re.I) self.reauteur = re.compile(r'\s*auteur.*', re.I) self.reautclean = re.compile(r'\s*\(.*\)\s*')
|
return title.replace('\n', '')
|
return unicode(title.replace('\n', ''))
|
def get_title(self, entry): title = deepcopy(entry.find("div[@id='book-info']")) title.remove(title.find("dl[@title='Informations sur le livre']")) title = ' '.join([i.text_content() for i in title.iterchildren()]) return title.replace('\n', '')
|
authortext.append(elt.text_content())
|
authortext.append(unicode(elt.text_content()))
|
def get_authors(self, entry): author = entry.find("div[@id='book-info']/dl[@title='Informations sur le livre']") authortext = [] for x in author.getiterator('dt'): if self.reauteur.match(x.text): elt = x.getnext() i = 0 while elt.tag <> 'dt' and i < 20: authortext.append(elt.text_content()) elt = elt.getnext() i += 1 break if len(authortext) == 1: authortext = [self.reautclean.sub('', authortext[0])] return authortext
|
return 'RESUME:\n' + entry.xpath("//p[@id='book-description']")[0].text
|
return 'RESUME:\n' + unicode(entry.xpath("//p[@id='book-description']")[0].text)
|
def get_description(self, entry, verbose): try: return 'RESUME:\n' + entry.xpath("//p[@id='book-description']")[0].text except: report(verbose) return None
|
return publitext
|
return unicode(publitext).strip()
|
def get_publisher(self, entry): publisher = entry.find("div[@id='book-info']/dl[@title='Informations sur le livre']") publitext = None for x in publisher.getiterator('dt'): if self.repub.match(x.text): publitext = x.getnext().text_content() break return publitext
|
if not len(d):
|
if len(d) == 0:
|
def get_date(self, entry, verbose): date = entry.find("div[@id='book-info']/dl[@title='Informations sur le livre']") for x in date.getiterator('dt'): if x.text == 'Date de parution': d = x.getnext().text_content() break if not len(d): return None try: default = utcnow().replace(day=15) d = replace_monthsfr(d) d = parse_date(d, assume_utc=True, default=default) except: report(verbose) d = None return d
|
break return isbntext
|
isbntext = isbntext.replace('-', '') break return unicode(isbntext)
|
def get_ISBN(self, entry): isbn = entry.find("div[@id='book-info']/dl[@title='Informations sur le livre']") isbntext = None for x in isbn.getiterator('dt'): if x.text == 'ISBN': isbntext = x.getnext().text_content() if not check_isbn(isbntext): return None break return isbntext
|
return langtext
|
return unicode(langtext).strip()
|
def get_language(self, entry): language = entry.find("div[@id='book-info']/dl[@title='Informations sur le livre']") langtext = None for x in language.getiterator('dt'): if x.text == 'Langue': langtext = x.getnext().text_content() break return langtext
|
verbose=False, max_results=5, keywords=None):
|
max_results=5, verbose=False, keywords=None):
|
def search(title=None, author=None, publisher=None, isbn=None, verbose=False, max_results=5, keywords=None): br = browser() entries = Query(title=title, author=author, isbn=isbn, publisher=publisher, keywords=keywords, max_results=max_results)(br, verbose) if entries is None: return #List of entry ans = ResultList() if len(entries) > 1: ans.populate(entries, br, verbose) else: ans.populate_single(entries[0], verbose) return ans
|
if entries is None:
|
if entries is None or len(entries) == 0:
|
def search(title=None, author=None, publisher=None, isbn=None, verbose=False, max_results=5, keywords=None): br = browser() entries = Query(title=title, author=author, isbn=isbn, publisher=publisher, keywords=keywords, max_results=max_results)(br, verbose) if entries is None: return #List of entry ans = ResultList() if len(entries) > 1: ans.populate(entries, br, verbose) else: ans.populate_single(entries[0], verbose) return ans
|
container = soup.find('container')
|
container = soup.find(name=re.compile(r'container$', re.I))
|
def __init__(self, stream=None): if not stream: return soup = BeautifulStoneSoup(stream.read()) container = soup.find('container') if not container: raise OCFException("<container/> element missing") if container.get('version', None) != '1.0': raise EPubException("unsupported version of OCF") rootfiles = container.find('rootfiles') if not rootfiles: raise EPubException("<rootfiles/> element missing") for rootfile in rootfiles.findAll('rootfile'): try: self[rootfile['media-type']] = rootfile['full-path'] except KeyError: raise EPubException("<rootfile/> element malformed")
|
raise OCFException("<container/> element missing")
|
raise OCFException("<container> element missing")
|
def __init__(self, stream=None): if not stream: return soup = BeautifulStoneSoup(stream.read()) container = soup.find('container') if not container: raise OCFException("<container/> element missing") if container.get('version', None) != '1.0': raise EPubException("unsupported version of OCF") rootfiles = container.find('rootfiles') if not rootfiles: raise EPubException("<rootfiles/> element missing") for rootfile in rootfiles.findAll('rootfile'): try: self[rootfile['media-type']] = rootfile['full-path'] except KeyError: raise EPubException("<rootfile/> element malformed")
|
rootfiles = container.find('rootfiles')
|
rootfiles = container.find(re.compile(r'rootfiles$', re.I))
|
def __init__(self, stream=None): if not stream: return soup = BeautifulStoneSoup(stream.read()) container = soup.find('container') if not container: raise OCFException("<container/> element missing") if container.get('version', None) != '1.0': raise EPubException("unsupported version of OCF") rootfiles = container.find('rootfiles') if not rootfiles: raise EPubException("<rootfiles/> element missing") for rootfile in rootfiles.findAll('rootfile'): try: self[rootfile['media-type']] = rootfile['full-path'] except KeyError: raise EPubException("<rootfile/> element malformed")
|
for rootfile in rootfiles.findAll('rootfile'):
|
for rootfile in rootfiles.findAll(re.compile(r'rootfile$', re.I)):
|
def __init__(self, stream=None): if not stream: return soup = BeautifulStoneSoup(stream.read()) container = soup.find('container') if not container: raise OCFException("<container/> element missing") if container.get('version', None) != '1.0': raise EPubException("unsupported version of OCF") rootfiles = container.find('rootfiles') if not rootfiles: raise EPubException("<rootfiles/> element missing") for rootfile in rootfiles.findAll('rootfile'): try: self[rootfile['media-type']] = rootfile['full-path'] except KeyError: raise EPubException("<rootfile/> element malformed")
|
if self.get_extra(key):
|
if self.get_extra(key) is not None:
|
def format_field_extended(self, key, series_with_index=True): from calibre.ebooks.metadata import authors_to_string ''' returns the tuple (field_name, formatted_value) '''
|
cursor = QTextCursor(self.preview.document()) extsel = QTextEdit.ExtraSelection() extsel.cursor = cursor extsel.format.setBackground(QBrush(Qt.yellow))
|
def do_test(self): selections = [] if self.regex_valid(): text = qstring_to_unicode(self.preview.toPlainText()) regex = qstring_to_unicode(self.regex.text())
|
|
cursor = QTextCursor(self.preview.document()) cursor.setPosition(match.start(), QTextCursor.MoveAnchor) cursor.setPosition(match.end(), QTextCursor.KeepAnchor) sel = QTextEdit.ExtraSelection() sel.cursor = cursor sel.format.setBackground(QBrush(Qt.yellow)) selections.append(sel)
|
es = QTextEdit.ExtraSelection(extsel) es.cursor.setPosition(match.start(), QTextCursor.MoveAnchor) es.cursor.setPosition(match.end(), QTextCursor.KeepAnchor) selections.append(es)
|
def do_test(self): selections = [] if self.regex_valid(): text = qstring_to_unicode(self.preview.toPlainText()) regex = qstring_to_unicode(self.regex.text())
|
chars = list(range(8)) + [0x0B, 0x0E, 0x0F] + list(range(0x10, 0x19)) illegal_chars = re.compile(u'|'.join(map(unichr, chars))) txt = illegal_chars.sub('', txt)
|
def convert_basic(txt, title='', epub_split_size_kb=0): # Strip whitespace from the beginning and end of the line. Also replace # all line breaks with \n. txt = '\n'.join([line.strip() for line in txt.splitlines()]) # Condense redundant spaces txt = re.sub('[ ]{2,}', ' ', txt) # Remove blank lines from the beginning and end of the document. txt = re.sub('^\s+(?=.)', '', txt) txt = re.sub('(?<=.)\s+$', '', txt) # Remove excessive line breaks. txt = re.sub('\n{3,}', '\n\n', txt) #Takes care if there is no point to split if epub_split_size_kb > 0: length_byte = len(txt.encode('utf-8')) #Calculating the average chunk value for easy splitting as EPUB (+2 as a safe margin) chunk_size = long(length_byte / (int(length_byte / (epub_split_size_kb * 1024) ) + 2 )) #if there are chunks with a superior size then go and break if (len(filter(lambda x: len(x.encode('utf-8')) > chunk_size, txt.split('\n\n')))) : txt = u'\n\n'.join([split_string_separator(line, chunk_size) for line in txt.split('\n\n')]) lines = [] # Split into paragraphs based on having a blank line between text. for line in txt.split('\n\n'): if line.strip(): lines.append('<p>%s</p>' % prepare_string_for_xml(line.replace('\n', ' '))) return HTML_TEMPLATE % (title, '\n'.join(lines))
|
|
length_byte = len(txt.encode('utf-8'))
|
if isinstance(txt, unicode): txt = txt.encode('utf-8') length_byte = len(txt)
|
def convert_basic(txt, title='', epub_split_size_kb=0): # Strip whitespace from the beginning and end of the line. Also replace # all line breaks with \n. txt = '\n'.join([line.strip() for line in txt.splitlines()]) # Condense redundant spaces txt = re.sub('[ ]{2,}', ' ', txt) # Remove blank lines from the beginning and end of the document. txt = re.sub('^\s+(?=.)', '', txt) txt = re.sub('(?<=.)\s+$', '', txt) # Remove excessive line breaks. txt = re.sub('\n{3,}', '\n\n', txt) #Takes care if there is no point to split if epub_split_size_kb > 0: length_byte = len(txt.encode('utf-8')) #Calculating the average chunk value for easy splitting as EPUB (+2 as a safe margin) chunk_size = long(length_byte / (int(length_byte / (epub_split_size_kb * 1024) ) + 2 )) #if there are chunks with a superior size then go and break if (len(filter(lambda x: len(x.encode('utf-8')) > chunk_size, txt.split('\n\n')))) : txt = u'\n\n'.join([split_string_separator(line, chunk_size) for line in txt.split('\n\n')]) lines = [] # Split into paragraphs based on having a blank line between text. for line in txt.split('\n\n'): if line.strip(): lines.append('<p>%s</p>' % prepare_string_for_xml(line.replace('\n', ' '))) return HTML_TEMPLATE % (title, '\n'.join(lines))
|
if (len(filter(lambda x: len(x.encode('utf-8')) > chunk_size, txt.split('\n\n')))) : txt = u'\n\n'.join([split_string_separator(line, chunk_size) for line in txt.split('\n\n')])
|
if (len(filter(lambda x: len(x) > chunk_size, txt.split('\n\n')))) : txt = '\n\n'.join([split_string_separator(line, chunk_size) for line in txt.split('\n\n')]) if isbytestring(txt): txt = txt.decode('utf-8')
|
def convert_basic(txt, title='', epub_split_size_kb=0): # Strip whitespace from the beginning and end of the line. Also replace # all line breaks with \n. txt = '\n'.join([line.strip() for line in txt.splitlines()]) # Condense redundant spaces txt = re.sub('[ ]{2,}', ' ', txt) # Remove blank lines from the beginning and end of the document. txt = re.sub('^\s+(?=.)', '', txt) txt = re.sub('(?<=.)\s+$', '', txt) # Remove excessive line breaks. txt = re.sub('\n{3,}', '\n\n', txt) #Takes care if there is no point to split if epub_split_size_kb > 0: length_byte = len(txt.encode('utf-8')) #Calculating the average chunk value for easy splitting as EPUB (+2 as a safe margin) chunk_size = long(length_byte / (int(length_byte / (epub_split_size_kb * 1024) ) + 2 )) #if there are chunks with a superior size then go and break if (len(filter(lambda x: len(x.encode('utf-8')) > chunk_size, txt.split('\n\n')))) : txt = u'\n\n'.join([split_string_separator(line, chunk_size) for line in txt.split('\n\n')]) lines = [] # Split into paragraphs based on having a blank line between text. for line in txt.split('\n\n'): if line.strip(): lines.append('<p>%s</p>' % prepare_string_for_xml(line.replace('\n', ' '))) return HTML_TEMPLATE % (title, '\n'.join(lines))
|
lines.append('<p>%s</p>' % prepare_string_for_xml(line.replace('\n', ' ')))
|
lines.append(u'<p>%s</p>' % prepare_string_for_xml(line.replace('\n', ' ')))
|
def convert_basic(txt, title='', epub_split_size_kb=0): # Strip whitespace from the beginning and end of the line. Also replace # all line breaks with \n. txt = '\n'.join([line.strip() for line in txt.splitlines()]) # Condense redundant spaces txt = re.sub('[ ]{2,}', ' ', txt) # Remove blank lines from the beginning and end of the document. txt = re.sub('^\s+(?=.)', '', txt) txt = re.sub('(?<=.)\s+$', '', txt) # Remove excessive line breaks. txt = re.sub('\n{3,}', '\n\n', txt) #Takes care if there is no point to split if epub_split_size_kb > 0: length_byte = len(txt.encode('utf-8')) #Calculating the average chunk value for easy splitting as EPUB (+2 as a safe margin) chunk_size = long(length_byte / (int(length_byte / (epub_split_size_kb * 1024) ) + 2 )) #if there are chunks with a superior size then go and break if (len(filter(lambda x: len(x.encode('utf-8')) > chunk_size, txt.split('\n\n')))) : txt = u'\n\n'.join([split_string_separator(line, chunk_size) for line in txt.split('\n\n')]) lines = [] # Split into paragraphs based on having a blank line between text. for line in txt.split('\n\n'): if line.strip(): lines.append('<p>%s</p>' % prepare_string_for_xml(line.replace('\n', ' '))) return HTML_TEMPLATE % (title, '\n'.join(lines))
|
return HTML_TEMPLATE % (title, '\n'.join(lines))
|
return HTML_TEMPLATE % (title, u'\n'.join(lines))
|
def convert_basic(txt, title='', epub_split_size_kb=0): # Strip whitespace from the beginning and end of the line. Also replace # all line breaks with \n. txt = '\n'.join([line.strip() for line in txt.splitlines()]) # Condense redundant spaces txt = re.sub('[ ]{2,}', ' ', txt) # Remove blank lines from the beginning and end of the document. txt = re.sub('^\s+(?=.)', '', txt) txt = re.sub('(?<=.)\s+$', '', txt) # Remove excessive line breaks. txt = re.sub('\n{3,}', '\n\n', txt) #Takes care if there is no point to split if epub_split_size_kb > 0: length_byte = len(txt.encode('utf-8')) #Calculating the average chunk value for easy splitting as EPUB (+2 as a safe margin) chunk_size = long(length_byte / (int(length_byte / (epub_split_size_kb * 1024) ) + 2 )) #if there are chunks with a superior size then go and break if (len(filter(lambda x: len(x.encode('utf-8')) > chunk_size, txt.split('\n\n')))) : txt = u'\n\n'.join([split_string_separator(line, chunk_size) for line in txt.split('\n\n')]) lines = [] # Split into paragraphs based on having a blank line between text. for line in txt.split('\n\n'): if line.strip(): lines.append('<p>%s</p>' % prepare_string_for_xml(line.replace('\n', ' '))) return HTML_TEMPLATE % (title, '\n'.join(lines))
|
txt = re.sub(u'(?<=.)\n(?=.)', u'\n\n', txt)
|
txt = re.sub(u'(?<=.)\n(?=.)', '\n\n', txt)
|
def separate_paragraphs_single_line(txt): txt = txt.replace('\r\n', '\n') txt = txt.replace('\r', '\n') txt = re.sub(u'(?<=.)\n(?=.)', u'\n\n', txt) return txt
|
txt = re.sub('(?miu)^(\t+|[ ]{2,})(?=.)', '\n\t', txt)
|
txt = re.sub(u'(?miu)^(\t+|[ ]{2,})(?=.)', '\n\t', txt)
|
def separate_paragraphs_print_formatted(txt): txt = re.sub('(?miu)^(\t+|[ ]{2,})(?=.)', '\n\t', txt) return txt
|
self.addItems(QStringList(list(set(config[opt_name]))))
|
items = [] for item in config[opt_name]: if item not in items: items.append(item) self.addItems(QStringList(items))
|
def initialize(self, opt_name, colorize=False, help_text=_('Search')): self.as_you_type = config['search_as_you_type'] self.opt_name = opt_name self.addItems(QStringList(list(set(config[opt_name])))) try: self.line_edit.setPlaceholderText(help_text) except: # Using Qt < 4.7 pass self.colorize = colorize self.clear()
|
config[self.opt_name] = [unicode(self.itemText(i)) for i in
|
history = [unicode(self.itemText(i)) for i in
|
def _do_search(self, store_in_history=True): text = unicode(self.currentText()).strip() if not text: return self.clear() self.search.emit(text)
|
print "this is a pdf" chapter_line_open = "<(?P<outer>p)[^>]*>(\s*<[ibu][^>]*>)?\s*" chapter_line_close = "\s*(</[ibu][^>]*>\s*)?</(?P=outer)>" title_line_open = "<(?P<outer2>p)[^>]*>\s*" title_line_close = "\s*</(?P=outer2)>"
|
chapter_line_open = "<(?P<outer>p)[^>]*>(\s*<[ibu][^>]*>)?\s*" chapter_line_close = "\s*(</[ibu][^>]*>\s*)?</(?P=outer)>" title_line_open = "<(?P<outer2>p)[^>]*>\s*" title_line_close = "\s*</(?P=outer2)>"
|
def markup_chapters(self, html, wordcount, blanks_between_paragraphs): # Typical chapters are between 2000 and 7000 words, use the larger number to decide the # minimum of chapters to search for self.min_chapters = 1 if wordcount > 7000: self.min_chapters = wordcount / 7000 print "minimum chapters required are: "+str(self.min_chapters) heading = re.compile('<h[1-3][^>]*>', re.IGNORECASE) self.html_preprocess_sections = len(heading.findall(html)) self.log("found " + unicode(self.html_preprocess_sections) + " pre-existing headings")
|
if isinstance(xbounds, basestring): xbounds = self._get_or_create_datasource(xbounds).get_data() if xbounds is None: xs = arange(array_data.shape[1]) elif isinstance(xbounds, tuple): xs = linspace(xbounds[0], xbounds[1], array_data.shape[1]) elif isinstance(xbounds, ndarray): if len(xbounds.shape) == 1 and len(xbounds) == array_data.shape[1]: xs = linspace(xbounds[0], xbounds[-1], array_data.shape[1]) elif xbounds.shape == array_data.shape: xs = xbounds[0,:] else: raise ValueError("xbounds shape not commensurate with data") else: raise ValueError("xbounds must be None, a tuple, an array, or a PlotData name") if isinstance(ybounds, basestring): ybounds = self._get_or_create_datasource(ybounds).get_data() if ybounds is None: ys = arange(array_data.shape[0]) elif isinstance(ybounds, tuple): ys = linspace(ybounds[0], ybounds[1], array_data.shape[0]) elif isinstance(ybounds, ndarray): if len(ybounds.shape) == 1 and len(ybounds) == array_data.shape[0]: ys = linspace(ybounds[0], ybounds[-1], array_data.shape[0]) elif ybounds.shape == array_data.shape: ys = ybounds[:,0] else: raise ValueError("ybounds shape not commensurate with data") else: raise ValueError("ybounds must be None, a tuple, an array, or a PlotData name") index = GridDataSource(xs, ys, sort_order=('ascending', 'ascending')) self.range2d.add(index) mapper = GridMapper(range=self.range2d, stretch_data_x=self.x_mapper.stretch_data, stretch_data_y=self.y_mapper.stretch_data) plot = cls(index=index, value=value, index_mapper=mapper, orientation=self.orientation, origin=origin, **kwargs) if hide_grids: self.x_grid.visible = False self.y_grid.visible = False self.add(plot) self.plots[name] = [plot] return self.plots[name]
|
return self._create_2d_plot(cls, name, origin, xbounds, ybounds, value, hide_grids, **kwargs)
|
def img_plot(self, data, name=None, colormap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds image plots to this Plot object.
|
xs = arange(array_data.shape[1])
|
xs = arange(num_x_ticks)
|
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
|
xs = linspace(xbounds[0], xbounds[1], array_data.shape[1])
|
xs = linspace(xbounds[0], xbounds[1], num_x_ticks)
|
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
|
if len(xbounds.shape) == 1 and len(xbounds) == array_data.shape[1]: xs = linspace(xbounds[0], xbounds[-1], array_data.shape[1])
|
if len(xbounds.shape) == 1 and len(xbounds) == num_x_ticks: xs = linspace(xbounds[0], xbounds[-1], num_x_ticks) elif len(xbounds.shape) == 1 and len(xbounds) == num_x_ticks-1: raise ValueError("The xbounds array of an image plot needs to have 1 more element that its corresponding data shape, because it represents the locations of pixel boundaries.")
|
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
|
xs = linspace(xbounds[0,0],xbounds[0,-1],array_data.shape[1])
|
xs = xbounds[0,:]
|
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
|
ys = arange(array_data.shape[0])
|
ys = arange(num_y_ticks)
|
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
|
ys = linspace(ybounds[0], ybounds[1], array_data.shape[0])
|
ys = linspace(ybounds[0], ybounds[1], num_y_ticks)
|
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
|
if len(ybounds.shape) == 1 and len(ybounds) == array_data.shape[0]: ys = linspace(ybounds[0], ybounds[-1], array_data.shape[0])
|
if len(ybounds.shape) == 1 and len(ybounds) == num_y_ticks: ys = linspace(ybounds[0], ybounds[-1], num_y_ticks) elif len(ybounds.shape) == 1 and len(ybounds) == num_y_ticks-1: raise ValueError("The ybounds array of an image plot needs to have 1 more element that its corresponding data shape, because it represents the locations of pixel boundaries.")
|
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
|
ys = linspace(ybounds[0,0],ybounds[-1,0],array_data.shape[0])
|
ys = ybounds[:,0]
|
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
|
value=value,
|
value=value_ds,
|
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
|
class PlotFrame(DemoFrame): def _create_window(self): self.controller = TimerController() container = _create_plot_component(self.controller) self.Bind(wx.EVT_CLOSE, self.onClose) timerId = wx.NewId() self.timer = wx.Timer(self, timerId) self.Bind(wx.EVT_TIMER, self.controller.onTimer, id=timerId) self.timer.Start(20.0, wx.TIMER_CONTINUOUS) return Window(self, -1, component=container) def onClose(self, event): self.timer.Stop() event.Skip()
|
from enthought.etsconfig.api import ETSConfig if ETSConfig.enable_toolkit == "wx": import wx class PlotFrame(DemoFrame): def _create_window(self): self.controller = TimerController() container = _create_plot_component(self.controller) self.Bind(wx.EVT_CLOSE, self.onClose) timerId = wx.NewId() self.timer = wx.Timer(self, timerId) self.Bind(wx.EVT_TIMER, self.controller.onTimer, id=timerId) self.timer.Start(20.0, wx.TIMER_CONTINUOUS) return Window(self, -1, component=container) def onClose(self, event): self.timer.Stop() event.Skip() elif ETSConfig.enable_toolkit == "qt4": from PyQt4 import QtGui, QtCore class PlotFrame(DemoFrame): def _create_window(self): self.controller = TimerController() container = _create_plot_component(self.controller) self.timer = QtCore.QTimer() self.timer.timeout.connect(self.controller.onTimer) self.timer.start(20) return Window(self, -1, component=container) def closeEvent(self, event): if getattr(self, "timer", None): self.timer.stop() return super(PlotFrame, self).closeEvent(event)
|
def configure_traits(self, *args, **kws): # Start up the timer! We should do this only when the demo actually # starts and not when the demo object is created. self.timer = Timer(20, self.controller.onTimer) return super(Demo, self).configure_traits(*args, **kws)
|
_stream = None
|
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0.0, float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(NUM_SAMPLES/2) obj.spectrum_data.set_data('amplitude', empty_amplitude) obj.spectrum_plot = Plot(obj.spectrum_data) obj.spectrum_plot.plot(("frequency", "amplitude"), name="Spectrum", color="red") obj.spectrum_plot.padding = 50 obj.spectrum_plot.title = "Spectrum" spec_range = obj.spectrum_plot.plots.values()[0][0].value_mapper.range spec_range.low = 0.0 spec_range.high = 5.0 obj.spectrum_plot.index_axis.title = 'Frequency (hz)' obj.spectrum_plot.value_axis.title = 'Amplitude' # Time Series plot times = linspace(0.0, float(NUM_SAMPLES)/SAMPLING_RATE, num=NUM_SAMPLES) obj.time_data = ArrayPlotData(time=times) empty_amplitude = zeros(NUM_SAMPLES) obj.time_data.set_data('amplitude', empty_amplitude) obj.time_plot = Plot(obj.time_data) obj.time_plot.plot(("time", "amplitude"), name="Time", color="blue") obj.time_plot.padding = 50 obj.time_plot.title = "Time" obj.time_plot.index_axis.title = 'Time (seconds)' obj.time_plot.value_axis.title = 'Amplitude' time_range = obj.time_plot.plots.values()[0][0].value_mapper.range time_range.low = -0.2 time_range.high = 0.2 # Spectrogram plot spectrogram_data = zeros(( NUM_SAMPLES/2, SPECTROGRAM_LENGTH)) obj.spectrogram_plotdata = ArrayPlotData() obj.spectrogram_plotdata.set_data('imagedata', spectrogram_data) spectrogram_plot = Plot(obj.spectrogram_plotdata) max_time = float(SPECTROGRAM_LENGTH * NUM_SAMPLES) / SAMPLING_RATE max_freq = float(SAMPLING_RATE / 2) spectrogram_plot.img_plot('imagedata', name='Spectrogram', xbounds=(0, max_time), ybounds=(0, max_freq), colormap=jet, ) range_obj = spectrogram_plot.plots['Spectrogram'][0].value_mapper.range range_obj.high = 5 range_obj.low = 0.0 spectrogram_plot.title = 'Spectrogram' obj.spectrogram_plot = spectrogram_plot container = HPlotContainer() container.add(obj.spectrum_plot) container.add(obj.time_plot) container.add(spectrogram_plot) return container
|
|
pa = pyaudio.PyAudio() stream = pa.open(format=pyaudio.paInt16, channels=1, rate=SAMPLING_RATE,
|
global _stream if _stream is None: pa = pyaudio.PyAudio() _stream = pa.open(format=pyaudio.paInt16, channels=1, rate=SAMPLING_RATE,
|
def get_audio_data(): pa = pyaudio.PyAudio() stream = pa.open(format=pyaudio.paInt16, channels=1, rate=SAMPLING_RATE, input=True, frames_per_buffer=NUM_SAMPLES) audio_data = fromstring(stream.read(NUM_SAMPLES), dtype=short) stream.close() normalized_data = audio_data / 32768.0 return (abs(fft(normalized_data))[:NUM_SAMPLES/2], normalized_data)
|
audio_data = fromstring(stream.read(NUM_SAMPLES), dtype=short) stream.close()
|
audio_data = fromstring(_stream.read(NUM_SAMPLES), dtype=short)
|
def get_audio_data(): pa = pyaudio.PyAudio() stream = pa.open(format=pyaudio.paInt16, channels=1, rate=SAMPLING_RATE, input=True, frames_per_buffer=NUM_SAMPLES) audio_data = fromstring(stream.read(NUM_SAMPLES), dtype=short) stream.close() normalized_data = audio_data / 32768.0 return (abs(fft(normalized_data))[:NUM_SAMPLES/2], normalized_data)
|
demo_main(PlotFrame, size=size, title=title)
|
try: demo_main(PlotFrame, size=size, title=title) finally: if _stream is not None: _stream.close()
|
def closeEvent(self, event): # stop the timer if getattr(self, "timer", None): self.timer.stop() return super(PlotFrame, self).closeEvent(event)
|
@on_trait_change("_xrange.updated,_yrange.updated") def _subranges_updated(self): self.updated = True
|
def _sources_changed(self, old, new): for source in old: source.on_trait_change(self.refresh, "data_changed", remove=True) for source in new: source.on_trait_change(self.refresh, "data_changed") # the _xdata and _ydata of the sources may be created anew on every # access, so we can't just add/delete from _xrange and _yrange sources # based on object identity. So recreate lists each time: self._xrange.sources = [s._xdata for s in self.sources] self._yrange.sources = [s._ydata for s in self.sources] self.refresh()
|
|
plot.img_plot("imagedata", xbounds=x, ybounds=y, colormap=jet)
|
plot.img_plot("imagedata", colormap=jet)
|
def __init__(self): # Create the data and the PlotData object. For a 2D plot, we need to # take the row of X points and Y points and create a grid from them # using meshgrid(). x = linspace(0, 10, 50) y = linspace(0, 5, 50) xgrid, ygrid = meshgrid(x, y) z = exp(-(xgrid*xgrid + ygrid*ygrid) / 100) plotdata = ArrayPlotData(imagedata = z) # Create a Plot and associate it with the PlotData plot = Plot(plotdata) # Create a line plot in the Plot plot.img_plot("imagedata", xbounds=x, ybounds=y, colormap=jet) self.plot = plot
|
gc.save_state() gc.clip_to_rect(self.x, self.y, self.width, self.height)
|
def _draw_plot(self, gc, view_bounds=None, mode="normal"): self._gather_points() if len(self._cached_data_pts) == 0: return index = self.index_mapper.map_screen(self._cached_data_pts[0]) vals = [] for v in self._cached_data_pts[1:]: if v is None: vals.append(None) else: vals.append(self.value_mapper.map_screen(v)) gc.save_state() gc.clip_to_rect(self.x, self.y, self.width, self.height)
|
|
if len(index) == 0: return elif len(index) == 1:
|
if len(index) == 1:
|
def _draw_plot(self, gc, view_bounds=None, mode="normal"): self._gather_points() if len(self._cached_data_pts) == 0: return index = self.index_mapper.map_screen(self._cached_data_pts[0]) vals = [] for v in self._cached_data_pts[1:]: if v is None: vals.append(None) else: vals.append(self.value_mapper.map_screen(v)) gc.save_state() gc.clip_to_rect(self.x, self.y, self.width, self.height)
|
self._render(gc, left, right, *vals) gc.restore_state()
|
with gc: gc.clip_to_rect(self.x, self.y, self.width, self.height) self._render(gc, left, right, *vals)
|
def _draw_plot(self, gc, view_bounds=None, mode="normal"): self._gather_points() if len(self._cached_data_pts) == 0: return index = self.index_mapper.map_screen(self._cached_data_pts[0]) vals = [] for v in self._cached_data_pts[1:]: if v is None: vals.append(None) else: vals.append(self.value_mapper.map_screen(v)) gc.save_state() gc.clip_to_rect(self.x, self.y, self.width, self.height)
|
x_axis = Instance(PlotAxis)
|
x_axis = Instance(AbstractOverlay)
|
def set_grid(self, attr_name, new): """ Setter function used by GridProperty. """ if (attr_name,self.orientation) in [("index_grid","v"), ("value_grid","h")]: self.y_grid = new else: self.y_grid = new
|
y_axis = Instance(PlotAxis)
|
y_axis = Instance(AbstractOverlay)
|
def set_grid(self, attr_name, new): """ Setter function used by GridProperty. """ if (attr_name,self.orientation) in [("index_grid","v"), ("value_grid","h")]: self.y_grid = new else: self.y_grid = new
|
if self.selection_mode == "single":
|
if self.selection_mode == "single" or not modifier_down:
|
def normal_left_down(self, event): """ Handles the left mouse button being pressed when the tool is in the 'normal' state. If selecting is enabled and the cursor is within **threshold** of a data point, the method calls the subclass's _select" or _deselect methods to perform the appropriate action, given the current selection_mode. """ if self.selection_mode != "off": already_selected, clicked = self._get_selection_state(event) modifier_down = self.multiselect_modifier.match(event) token = self._get_selection_token(event)
|
gc.save_state() gc.clip_to_rect(self.x, self.y, self.width, self.height) try:
|
with gc: gc.clip_to_rect(self.x, self.y, self.width, self.height)
|
def _render(self, gc, pts): gc.save_state() gc.clip_to_rect(self.x, self.y, self.width, self.height) try: if not self.index: gc.restore_state() return name = self.selection_metadata_name md = self.index.metadata if name in md and md[name] is not None and len(md[name]) > 0: # FIXME: when will we ever encounter multiple masks in the list? sel_mask = md[name][0] sel_pts = np.compress(sel_mask, pts, axis=0) unsel_pts = np.compress(~sel_mask, pts, axis=0) color = list(self.color_) color[3] *= self.unselected_alpha outline_color = list(self.outline_color_) outline_color[3] *= self.unselected_alpha if unsel_pts.size > 0: self.render_markers_func(gc, unsel_pts, self.marker, self.marker_size, tuple(color), self.unselected_line_width, tuple(outline_color), self.custom_symbol) if sel_pts.size > 0: self.render_markers_func(gc, sel_pts, self.marker, self.marker_size, self.selected_color_, self.line_width, self.outline_color_, self.custom_symbol) else: self.render_markers_func(gc, pts, self.marker, self.marker_size, self.color_, self.line_width, self.outline_color_, self.custom_symbol) finally: gc.restore_state()
|
gc.restore_state()
|
def _render(self, gc, pts): gc.save_state() gc.clip_to_rect(self.x, self.y, self.width, self.height) try: if not self.index: gc.restore_state() return name = self.selection_metadata_name md = self.index.metadata if name in md and md[name] is not None and len(md[name]) > 0: # FIXME: when will we ever encounter multiple masks in the list? sel_mask = md[name][0] sel_pts = np.compress(sel_mask, pts, axis=0) unsel_pts = np.compress(~sel_mask, pts, axis=0) color = list(self.color_) color[3] *= self.unselected_alpha outline_color = list(self.outline_color_) outline_color[3] *= self.unselected_alpha if unsel_pts.size > 0: self.render_markers_func(gc, unsel_pts, self.marker, self.marker_size, tuple(color), self.unselected_line_width, tuple(outline_color), self.custom_symbol) if sel_pts.size > 0: self.render_markers_func(gc, sel_pts, self.marker, self.marker_size, self.selected_color_, self.line_width, self.outline_color_, self.custom_symbol) else: self.render_markers_func(gc, pts, self.marker, self.marker_size, self.color_, self.line_width, self.outline_color_, self.custom_symbol) finally: gc.restore_state()
|
|
finally: gc.restore_state()
|
def _render(self, gc, pts): gc.save_state() gc.clip_to_rect(self.x, self.y, self.width, self.height) try: if not self.index: gc.restore_state() return name = self.selection_metadata_name md = self.index.metadata if name in md and md[name] is not None and len(md[name]) > 0: # FIXME: when will we ever encounter multiple masks in the list? sel_mask = md[name][0] sel_pts = np.compress(sel_mask, pts, axis=0) unsel_pts = np.compress(~sel_mask, pts, axis=0) color = list(self.color_) color[3] *= self.unselected_alpha outline_color = list(self.outline_color_) outline_color[3] *= self.unselected_alpha if unsel_pts.size > 0: self.render_markers_func(gc, unsel_pts, self.marker, self.marker_size, tuple(color), self.unselected_line_width, tuple(outline_color), self.custom_symbol) if sel_pts.size > 0: self.render_markers_func(gc, sel_pts, self.marker, self.marker_size, self.selected_color_, self.line_width, self.outline_color_, self.custom_symbol) else: self.render_markers_func(gc, pts, self.marker, self.marker_size, self.color_, self.line_width, self.outline_color_, self.custom_symbol) finally: gc.restore_state()
|
|
try: self.model = model = BrainModel() cmap = bone except SystemExit: sys.exit() except: print "Unable to load BrainModel, using generated data cube." self.model = model = Model() cmap = jet
|
self.model = model = Model() cmap = jet
|
def _create_window(self): # Create the model try: self.model = model = BrainModel() cmap = bone except SystemExit: sys.exit() except: print "Unable to load BrainModel, using generated data cube." self.model = model = Model() cmap = jet self._update_model(cmap)
|
imgplot = centerplot.img_plot("xy", xbounds=model.xs, ybounds=model.ys, colormap=cmap)[0]
|
imgplot = centerplot.img_plot("xy", xbounds=(model.xs[0], model.xs[-1]), ybounds=(model.ys[0], model.ys[-1]), colormap=cmap)[0]
|
def _create_window(self): # Create the model try: self.model = model = BrainModel() cmap = bone except SystemExit: sys.exit() except: print "Unable to load BrainModel, using generated data cube." self.model = model = Model() cmap = jet self._update_model(cmap)
|
imgplot = rightplot.img_plot("yz", xbounds=model.zs, ybounds=model.ys, colormap=cmap)[0]
|
imgplot = rightplot.img_plot("yz", xbounds=(model.zs[0], model.zs[-1]), ybounds=(model.ys[0], model.ys[-1]), colormap=cmap)[0]
|
def _create_window(self): # Create the model try: self.model = model = BrainModel() cmap = bone except SystemExit: sys.exit() except: print "Unable to load BrainModel, using generated data cube." self.model = model = Model() cmap = jet self._update_model(cmap)
|
imgplot = bottomplot.img_plot("xz", xbounds=model.xs, ybounds=model.zs, colormap=cmap)[0]
|
imgplot = bottomplot.img_plot("xz", xbounds=(model.xs[0], model.xs[-1]), ybounds=(model.zs[0], model.zs[-1]), colormap=cmap)[0]
|
def _create_window(self): # Create the model try: self.model = model = BrainModel() cmap = bone except SystemExit: sys.exit() except: print "Unable to load BrainModel, using generated data cube." self.model = model = Model() cmap = jet self._update_model(cmap)
|
if not RectZoomTool in existing_tools: cont.overlays.append(RectZoomTool(cont, drag_button="right"))
|
if not ZoomTool in existing_tools: cont.overlays.append(ZoomTool(cont, tool_mode="box", always_on=True, drag_button="right"))
|
def _do_plot_boilerplate(kwargs, image=False): """ Used by various plotting functions. Checks/handles hold state, returns a Plot object for the plotting function to use. """ if kwargs.has_key("hold"): hold(kwargs["hold"]) del kwargs["hold"] # Check for an active window; if none, open one. if len(session.windows) == 0: if image: win = session.new_window(is_image=True) activate(win) else: figure() cont = session.active_window.get_container() if not cont: cont = Plot(session.data) session.active_window.set_container(cont) existing_tools = [type(t) for t in (cont.tools + cont.overlays)] if not PanTool in existing_tools: cont.tools.append(PanTool(cont)) if not RectZoomTool in existing_tools: cont.overlays.append(RectZoomTool(cont, drag_button="right")) if not session.hold: cont.delplot(*cont.plots.keys()) return cont
|
self.set(**postponed)
|
def __init__(self, *args, **kw): super(BarPlot, self).__init__(*args, **kw) # update colors to use the correct alpha channel self.line_color_ = self.line_color_[0:3] + (self.alpha,) self.fill_color_ = self.fill_color_[0:3] + (self.alpha,)
|
|
def map_index(self, screen_pt, threshold=2.0, outside_returns_none=True, \
|
def map_index(self, screen_pt, threshold=2.0, outside_returns_none=True,
|
def map_index(self, screen_pt, threshold=2.0, outside_returns_none=True, \ index_only=False): """ Maps a screen space point to an index into the plot's index array(s). Implements the AbstractPlotRenderer interface. """ data_pt = self.map_data(screen_pt) if ((data_pt < self.index_mapper.range.low) or \ (data_pt > self.index_mapper.range.high)) and outside_returns_none: return None half = threshold / 2.0 index_data = self.index.get_data() value_data = self.value.get_data()
|
half = threshold / 2.0
|
def map_index(self, screen_pt, threshold=2.0, outside_returns_none=True, \ index_only=False): """ Maps a screen space point to an index into the plot's index array(s). Implements the AbstractPlotRenderer interface. """ data_pt = self.map_data(screen_pt) if ((data_pt < self.index_mapper.range.low) or \ (data_pt > self.index_mapper.range.high)) and outside_returns_none: return None half = threshold / 2.0 index_data = self.index.get_data() value_data = self.value.get_data()
|
|
x = numpy.linspace(-5,5,100) y = numpy.linspace(-5,5,100)
|
xy_range = (-5, 5) x = numpy.linspace(xy_range[0], xy_range[1] ,100) y = numpy.linspace(xy_range[0], xy_range[1] ,100)
|
def __init__(self): #The delegates views don't work unless we caller the superclass __init__ super(CursorTest, self).__init__() container = HPlotContainer(padding=0, spacing=20) self.plot = container #a subcontainer for the first plot. #I'm not sure why this is required. Without it, the layout doesn't work right. subcontainer = OverlayPlotContainer(padding=40) container.add(subcontainer) #make some data index = numpy.linspace(-10,10,512) value = numpy.sin(index) #create a LinePlot instance and add it to the subcontainer line = create_line_plot([index, value], add_grid=True, add_axis=True, index_sort='ascending', orientation = 'h') subcontainer.add(line) #here's our first cursor. csr = CursorTool(line, drag_button="left", color='blue') self.cursor1 = csr #and set it's initial position (in data-space units) csr.current_position = 0.0, 0.0 #this is a rendered component so it goes in the overlays list line.overlays.append(csr) #some other standard tools line.tools.append(PanTool(line, drag_button="right")) line.overlays.append(ZoomTool(line)) #make some 2D data for a colourmap plot x = numpy.linspace(-5,5,100) y = numpy.linspace(-5,5,100) X,Y = numpy.meshgrid(x, y) Z = numpy.sin(X)*numpy.arctan2(Y,X) #easiest way to get a CMapImagePlot is to use the Plot class ds = ArrayPlotData() ds.set_data('img', Z) img = Plot(ds, padding=40) cmapImgPlot = img.img_plot("img", xbounds = x, ybounds = y, colormap = jet)[0] container.add(img) #now make another cursor csr2 = CursorTool(cmapImgPlot, drag_button='left', color='white', line_width=2.0 ) self.cursor2 = csr2 csr2.current_position = 1.0, 1.5 cmapImgPlot.overlays.append(csr2) #add some standard tools. Note, I'm assigning the PanTool to the #right mouse-button to avoid conflicting with the cursors cmapImgPlot.tools.append(PanTool(cmapImgPlot, drag_button="right")) cmapImgPlot.overlays.append(ZoomTool(cmapImgPlot))
|
xbounds = x, ybounds = y,
|
xbounds = xy_range, ybounds = xy_range,
|
def __init__(self): #The delegates views don't work unless we caller the superclass __init__ super(CursorTest, self).__init__() container = HPlotContainer(padding=0, spacing=20) self.plot = container #a subcontainer for the first plot. #I'm not sure why this is required. Without it, the layout doesn't work right. subcontainer = OverlayPlotContainer(padding=40) container.add(subcontainer) #make some data index = numpy.linspace(-10,10,512) value = numpy.sin(index) #create a LinePlot instance and add it to the subcontainer line = create_line_plot([index, value], add_grid=True, add_axis=True, index_sort='ascending', orientation = 'h') subcontainer.add(line) #here's our first cursor. csr = CursorTool(line, drag_button="left", color='blue') self.cursor1 = csr #and set it's initial position (in data-space units) csr.current_position = 0.0, 0.0 #this is a rendered component so it goes in the overlays list line.overlays.append(csr) #some other standard tools line.tools.append(PanTool(line, drag_button="right")) line.overlays.append(ZoomTool(line)) #make some 2D data for a colourmap plot x = numpy.linspace(-5,5,100) y = numpy.linspace(-5,5,100) X,Y = numpy.meshgrid(x, y) Z = numpy.sin(X)*numpy.arctan2(Y,X) #easiest way to get a CMapImagePlot is to use the Plot class ds = ArrayPlotData() ds.set_data('img', Z) img = Plot(ds, padding=40) cmapImgPlot = img.img_plot("img", xbounds = x, ybounds = y, colormap = jet)[0] container.add(img) #now make another cursor csr2 = CursorTool(cmapImgPlot, drag_button='left', color='white', line_width=2.0 ) self.cursor2 = csr2 csr2.current_position = 1.0, 1.5 cmapImgPlot.overlays.append(csr2) #add some standard tools. Note, I'm assigning the PanTool to the #right mouse-button to avoid conflicting with the cursors cmapImgPlot.tools.append(PanTool(cmapImgPlot, drag_button="right")) cmapImgPlot.overlays.append(ZoomTool(cmapImgPlot))
|
logger.warning("No datasource for plot")
|
def _render(self, gc, points): # If there is nothing to render, render nothing if len(points) == 0: logger.warning("No datasource for plot") return if self.fill_direction == 'down': ox, oy = self.map_screen([[0,0]])[0] else: ox, oy = self.map_screen([[self.x_mapper.range.high, self.y_mapper.range.high]])[0] gc.save_state() try: gc.clip_to_rect(self.x, self.y, self.width, self.height) # If the fill color is not transparent, then draw the fill polygon first if self.face_color_[-1] != 0 and self.face_color_[:3] != (0,0,0): gc.set_fill_color(self.face_color_) gc.begin_path() startx, starty = points[0] if self.orientation == "h": gc.move_to(startx, oy) gc.line_to(startx, starty) else: gc.move_to(ox, starty) gc.line_to(startx, starty) gc.lines(points) endx, endy = points[-1] if self.orientation == "h": gc.line_to(endx, oy) gc.line_to(startx, oy) else: gc.line_to(ox, endy) gc.line_to(ox, starty) gc.close_path() gc.fill_path() # If the line color is not transparent, or tha same color # as the filled area: if self.edge_color_[-1] != 0 and self.edge_color_ != self.face_color_: gc.set_stroke_color(self.edge_color_) gc.set_line_width(self.edge_width) gc.set_line_dash(self.edge_style_) gc.begin_path() gc.move_to(*points[0]) gc.lines(points) gc.stroke_path() finally: gc.restore_state()
|
|
if self.face_color_[-1] != 0 and self.face_color_[:3] != (0,0,0): gc.set_fill_color(self.face_color_)
|
face_col = self.face_color_ if not (len(face_col) == 4 and face_col[-1] == 0): gc.set_fill_color(face_col)
|
def _render(self, gc, points): # If there is nothing to render, render nothing if len(points) == 0: logger.warning("No datasource for plot") return if self.fill_direction == 'down': ox, oy = self.map_screen([[0,0]])[0] else: ox, oy = self.map_screen([[self.x_mapper.range.high, self.y_mapper.range.high]])[0] gc.save_state() try: gc.clip_to_rect(self.x, self.y, self.width, self.height) # If the fill color is not transparent, then draw the fill polygon first if self.face_color_[-1] != 0 and self.face_color_[:3] != (0,0,0): gc.set_fill_color(self.face_color_) gc.begin_path() startx, starty = points[0] if self.orientation == "h": gc.move_to(startx, oy) gc.line_to(startx, starty) else: gc.move_to(ox, starty) gc.line_to(startx, starty) gc.lines(points) endx, endy = points[-1] if self.orientation == "h": gc.line_to(endx, oy) gc.line_to(startx, oy) else: gc.line_to(ox, endy) gc.line_to(ox, starty) gc.close_path() gc.fill_path() # If the line color is not transparent, or tha same color # as the filled area: if self.edge_color_[-1] != 0 and self.edge_color_ != self.face_color_: gc.set_stroke_color(self.edge_color_) gc.set_line_width(self.edge_width) gc.set_line_dash(self.edge_style_) gc.begin_path() gc.move_to(*points[0]) gc.lines(points) gc.stroke_path() finally: gc.restore_state()
|
if self.edge_color_[-1] != 0 and self.edge_color_ != self.face_color_: gc.set_stroke_color(self.edge_color_)
|
edge_col = self.edge_color_ if (not (len(edge_col) == 4 and edge_col[-1] == 0)) and edge_col != face_col: gc.set_stroke_color(edge_col)
|
def _render(self, gc, points): # If there is nothing to render, render nothing if len(points) == 0: logger.warning("No datasource for plot") return if self.fill_direction == 'down': ox, oy = self.map_screen([[0,0]])[0] else: ox, oy = self.map_screen([[self.x_mapper.range.high, self.y_mapper.range.high]])[0] gc.save_state() try: gc.clip_to_rect(self.x, self.y, self.width, self.height) # If the fill color is not transparent, then draw the fill polygon first if self.face_color_[-1] != 0 and self.face_color_[:3] != (0,0,0): gc.set_fill_color(self.face_color_) gc.begin_path() startx, starty = points[0] if self.orientation == "h": gc.move_to(startx, oy) gc.line_to(startx, starty) else: gc.move_to(ox, starty) gc.line_to(startx, starty) gc.lines(points) endx, endy = points[-1] if self.orientation == "h": gc.line_to(endx, oy) gc.line_to(startx, oy) else: gc.line_to(ox, endy) gc.line_to(ox, starty) gc.close_path() gc.fill_path() # If the line color is not transparent, or tha same color # as the filled area: if self.edge_color_[-1] != 0 and self.edge_color_ != self.face_color_: gc.set_stroke_color(self.edge_color_) gc.set_line_width(self.edge_width) gc.set_line_dash(self.edge_style_) gc.begin_path() gc.move_to(*points[0]) gc.lines(points) gc.stroke_path() finally: gc.restore_state()
|
tick_indices = [] for tick in tick_list: for i, pos in enumerate(self.positions): if allclose(pos, tick): tick_indices.append(i) break
|
pos_index = [] pos = [] pos_min = None pos_max = None for i, position in enumerate(self.positions): if datalow <= position <= datahigh: pos_max = max(position, pos_max) if pos_max is not None else position pos_min = min(position, pos_min) if pos_min is not None else position pos_index.append(i) pos.append(position) if len(pos_index) == 0: self._tick_positions = [] self._tick_label_positions = [] self._tick_label_list = [] return
|
def _compute_tick_positions(self, gc, component=None): """ Calculates the positions for the tick marks. Overrides PlotAxis. """ if (self.mapper is None): self._reset_cache() self._cache_valid = True return datalow = self.mapper.range.low datahigh = self.mapper.range.high screenhigh = self.mapper.high_pos screenlow = self.mapper.low_pos if (datalow == datahigh) or (screenlow == screenhigh) or \ (datalow in [inf, -inf]) or (datahigh in [inf, -inf]): self._reset_cache() self._cache_valid = True return
|
tick_positions = take(self.positions, tick_indices) self._tick_label_list = take(self.labels, tick_indices)
|
tick_indices = unique1d(searchsorted(pos, tick_list)) tick_indices = tick_indices[tick_indices < len(pos)] tick_positions = take(pos, tick_indices) self._tick_label_list = take(self.labels, take(pos_index, tick_indices))
|
def _compute_tick_positions(self, gc, component=None): """ Calculates the positions for the tick marks. Overrides PlotAxis. """ if (self.mapper is None): self._reset_cache() self._cache_valid = True return datalow = self.mapper.range.low datahigh = self.mapper.range.high screenhigh = self.mapper.high_pos screenlow = self.mapper.low_pos if (datalow == datahigh) or (screenlow == screenhigh) or \ (datalow in [inf, -inf]) or (datahigh in [inf, -inf]): self._reset_cache() self._cache_valid = True return
|
mapped_label_positions = [((self.mapper.map_screen(pos)-screenlow) / \ (screenhigh-screenlow)) for pos in tick_positions] self._tick_positions = [self._axis_vector*tickpos + self._origin_point \ for tickpos in mapped_label_positions] self._tick_label_positions = self._tick_positions
|
if self.small_haxis_style: mapped_label_positions = [((self.mapper.map_screen(pos)-screenlow) / \ (screenhigh-screenlow)) for pos in tick_positions] self._tick_positions = [self._axis_vector*tickpos + self._origin_point \ for tickpos in mapped_label_positions] self._tick_label_positions = self._tick_positions else: mapped_label_positions = [((self.mapper.map_screen(pos)-screenlow) / \ (screenhigh-screenlow)) for pos in tick_positions] self._tick_positions = [self._axis_vector*tickpos + self._origin_point \ for tickpos in mapped_label_positions] self._tick_label_positions = self._tick_positions
|
def _compute_tick_positions(self, gc, component=None): """ Calculates the positions for the tick marks. Overrides PlotAxis. """ if (self.mapper is None): self._reset_cache() self._cache_valid = True return datalow = self.mapper.range.low datahigh = self.mapper.range.high screenhigh = self.mapper.high_pos screenlow = self.mapper.low_pos if (datalow == datahigh) or (screenlow == screenhigh) or \ (datalow in [inf, -inf]) or (datahigh in [inf, -inf]): self._reset_cache() self._cache_valid = True return
|
render(gc, selected_points)
|
render(gc, selected_points, self.orientation)
|
def _render(self, gc, points, selected_points=None): if len(points) == 0: return
|
render(gc, points)
|
render(gc, points, self.orientation)
|
def _render(self, gc, points, selected_points=None): if len(points) == 0: return
|
def _render_normal(self, gc, points):
|
@classmethod def _render_normal(cls, gc, points, orientation):
|
def _render_normal(self, gc, points): for ary in points: if len(ary) > 0: gc.begin_path() gc.lines(ary) gc.stroke_path() return
|
def _render_hold(self, gc, points):
|
@classmethod def _render_hold(cls, gc, points, orientation):
|
def _render_hold(self, gc, points): for starts in points: x,y = starts.T ends = transpose(array( (x[1:], y[:-1]) )) gc.begin_path() gc.line_set(starts[:-1], ends) gc.stroke_path() return
|
ends = transpose(array( (x[1:], y[:-1]) ))
|
if orientation == "h": ends = transpose(array( (x[1:], y[:-1]) )) else: ends = transpose(array( (x[:-1], y[1:]) ))
|
def _render_hold(self, gc, points): for starts in points: x,y = starts.T ends = transpose(array( (x[1:], y[:-1]) )) gc.begin_path() gc.line_set(starts[:-1], ends) gc.stroke_path() return
|
def _render_connected_hold(self, gc, points):
|
@classmethod def _render_connected_hold(cls, gc, points, orientation):
|
def _render_connected_hold(self, gc, points): for starts in points: x,y = starts.T ends = transpose(array( (x[1:], y[:-1]) )) gc.begin_path() gc.line_set(starts[:-1], ends) gc.line_set(ends, starts[1:]) gc.stroke_path() return
|
ends = transpose(array( (x[1:], y[:-1]) ))
|
if orientation == "h": ends = transpose(array( (x[1:], y[:-1]) )) else: ends = transpose(array( (x[:-1], y[1:]) ))
|
def _render_connected_hold(self, gc, points): for starts in points: x,y = starts.T ends = transpose(array( (x[1:], y[:-1]) )) gc.begin_path() gc.line_set(starts[:-1], ends) gc.line_set(ends, starts[1:]) gc.stroke_path() return
|
frequencies = linspace(0., float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2)
|
frequencies = linspace(0.0, float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2)
|
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0., float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(NUM_SAMPLES/2) obj.spectrum_data.set_data('amplitude', empty_amplitude) obj.spectrum_plot = Plot(obj.spectrum_data) obj.spectrum_plot.plot(("frequency", "amplitude"), name="Spectrum", color="red") obj.spectrum_plot.padding = 50 obj.spectrum_plot.title = "Spectrum" spec_range = obj.spectrum_plot.plots.values()[0][0].value_mapper.range spec_range.low = 0.0 spec_range.high = 5.0 obj.spectrum_plot.index_axis.title = 'Frequency (hz)' obj.spectrum_plot.value_axis.title = 'Amplitude' # Time Series plot times = linspace(0., float(NUM_SAMPLES)/SAMPLING_RATE, num=NUM_SAMPLES) obj.time_data = ArrayPlotData(time=times) empty_amplitude = zeros(NUM_SAMPLES) obj.time_data.set_data('amplitude', empty_amplitude) obj.time_plot = Plot(obj.time_data) obj.time_plot.plot(("time", "amplitude"), name="Time", color="blue") obj.time_plot.padding = 50 obj.time_plot.title = "Time" obj.time_plot.index_axis.title = 'Time (seconds)' obj.time_plot.value_axis.title = 'Amplitude' time_range = obj.time_plot.plots.values()[0][0].value_mapper.range time_range.low = -0.2 time_range.high = 0.2 # Spectrogram plot spectrogram_data = zeros(( NUM_SAMPLES/2, SPECTROGRAM_LENGTH)) obj.spectrogram_plotdata = ArrayPlotData() obj.spectrogram_plotdata.set_data('imagedata', spectrogram_data) spectrogram_plot = Plot(obj.spectrogram_plotdata) spectrogram_time = linspace( 0.0, float(SPECTROGRAM_LENGTH*NUM_SAMPLES)/float(SAMPLING_RATE), num=SPECTROGRAM_LENGTH) spectrogram_freq = linspace(0.0, float(SAMPLING_RATE/2), num=NUM_SAMPLES/2) spectrogram_plot.img_plot('imagedata', name='Spectrogram', xbounds=spectrogram_time, ybounds=spectrogram_freq, colormap=jet, ) range_obj = spectrogram_plot.plots['Spectrogram'][0].value_mapper.range range_obj.high = 5 range_obj.low = 0.0 spectrogram_plot.title = 'Spectrogram' obj.spectrogram_plot = spectrogram_plot container = HPlotContainer() container.add(obj.spectrum_plot) container.add(obj.time_plot) container.add(spectrogram_plot) return container
|
times = linspace(0., float(NUM_SAMPLES)/SAMPLING_RATE, num=NUM_SAMPLES)
|
times = linspace(0.0, float(NUM_SAMPLES)/SAMPLING_RATE, num=NUM_SAMPLES)
|
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0., float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(NUM_SAMPLES/2) obj.spectrum_data.set_data('amplitude', empty_amplitude) obj.spectrum_plot = Plot(obj.spectrum_data) obj.spectrum_plot.plot(("frequency", "amplitude"), name="Spectrum", color="red") obj.spectrum_plot.padding = 50 obj.spectrum_plot.title = "Spectrum" spec_range = obj.spectrum_plot.plots.values()[0][0].value_mapper.range spec_range.low = 0.0 spec_range.high = 5.0 obj.spectrum_plot.index_axis.title = 'Frequency (hz)' obj.spectrum_plot.value_axis.title = 'Amplitude' # Time Series plot times = linspace(0., float(NUM_SAMPLES)/SAMPLING_RATE, num=NUM_SAMPLES) obj.time_data = ArrayPlotData(time=times) empty_amplitude = zeros(NUM_SAMPLES) obj.time_data.set_data('amplitude', empty_amplitude) obj.time_plot = Plot(obj.time_data) obj.time_plot.plot(("time", "amplitude"), name="Time", color="blue") obj.time_plot.padding = 50 obj.time_plot.title = "Time" obj.time_plot.index_axis.title = 'Time (seconds)' obj.time_plot.value_axis.title = 'Amplitude' time_range = obj.time_plot.plots.values()[0][0].value_mapper.range time_range.low = -0.2 time_range.high = 0.2 # Spectrogram plot spectrogram_data = zeros(( NUM_SAMPLES/2, SPECTROGRAM_LENGTH)) obj.spectrogram_plotdata = ArrayPlotData() obj.spectrogram_plotdata.set_data('imagedata', spectrogram_data) spectrogram_plot = Plot(obj.spectrogram_plotdata) spectrogram_time = linspace( 0.0, float(SPECTROGRAM_LENGTH*NUM_SAMPLES)/float(SAMPLING_RATE), num=SPECTROGRAM_LENGTH) spectrogram_freq = linspace(0.0, float(SAMPLING_RATE/2), num=NUM_SAMPLES/2) spectrogram_plot.img_plot('imagedata', name='Spectrogram', xbounds=spectrogram_time, ybounds=spectrogram_freq, colormap=jet, ) range_obj = spectrogram_plot.plots['Spectrogram'][0].value_mapper.range range_obj.high = 5 range_obj.low = 0.0 spectrogram_plot.title = 'Spectrogram' obj.spectrogram_plot = spectrogram_plot container = HPlotContainer() container.add(obj.spectrum_plot) container.add(obj.time_plot) container.add(spectrogram_plot) return container
|
spectrogram_time = linspace( 0.0, float(SPECTROGRAM_LENGTH*NUM_SAMPLES)/float(SAMPLING_RATE), num=SPECTROGRAM_LENGTH) spectrogram_freq = linspace(0.0, float(SAMPLING_RATE/2), num=NUM_SAMPLES/2)
|
max_time = float(SPECTROGRAM_LENGTH * NUM_SAMPLES) / SAMPLING_RATE max_freq = float(SAMPLING_RATE / 2)
|
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0., float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(NUM_SAMPLES/2) obj.spectrum_data.set_data('amplitude', empty_amplitude) obj.spectrum_plot = Plot(obj.spectrum_data) obj.spectrum_plot.plot(("frequency", "amplitude"), name="Spectrum", color="red") obj.spectrum_plot.padding = 50 obj.spectrum_plot.title = "Spectrum" spec_range = obj.spectrum_plot.plots.values()[0][0].value_mapper.range spec_range.low = 0.0 spec_range.high = 5.0 obj.spectrum_plot.index_axis.title = 'Frequency (hz)' obj.spectrum_plot.value_axis.title = 'Amplitude' # Time Series plot times = linspace(0., float(NUM_SAMPLES)/SAMPLING_RATE, num=NUM_SAMPLES) obj.time_data = ArrayPlotData(time=times) empty_amplitude = zeros(NUM_SAMPLES) obj.time_data.set_data('amplitude', empty_amplitude) obj.time_plot = Plot(obj.time_data) obj.time_plot.plot(("time", "amplitude"), name="Time", color="blue") obj.time_plot.padding = 50 obj.time_plot.title = "Time" obj.time_plot.index_axis.title = 'Time (seconds)' obj.time_plot.value_axis.title = 'Amplitude' time_range = obj.time_plot.plots.values()[0][0].value_mapper.range time_range.low = -0.2 time_range.high = 0.2 # Spectrogram plot spectrogram_data = zeros(( NUM_SAMPLES/2, SPECTROGRAM_LENGTH)) obj.spectrogram_plotdata = ArrayPlotData() obj.spectrogram_plotdata.set_data('imagedata', spectrogram_data) spectrogram_plot = Plot(obj.spectrogram_plotdata) spectrogram_time = linspace( 0.0, float(SPECTROGRAM_LENGTH*NUM_SAMPLES)/float(SAMPLING_RATE), num=SPECTROGRAM_LENGTH) spectrogram_freq = linspace(0.0, float(SAMPLING_RATE/2), num=NUM_SAMPLES/2) spectrogram_plot.img_plot('imagedata', name='Spectrogram', xbounds=spectrogram_time, ybounds=spectrogram_freq, colormap=jet, ) range_obj = spectrogram_plot.plots['Spectrogram'][0].value_mapper.range range_obj.high = 5 range_obj.low = 0.0 spectrogram_plot.title = 'Spectrogram' obj.spectrogram_plot = spectrogram_plot container = HPlotContainer() container.add(obj.spectrum_plot) container.add(obj.time_plot) container.add(spectrogram_plot) return container
|
xbounds=spectrogram_time, ybounds=spectrogram_freq,
|
xbounds=(0, max_time), ybounds=(0, max_freq),
|
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0., float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(NUM_SAMPLES/2) obj.spectrum_data.set_data('amplitude', empty_amplitude) obj.spectrum_plot = Plot(obj.spectrum_data) obj.spectrum_plot.plot(("frequency", "amplitude"), name="Spectrum", color="red") obj.spectrum_plot.padding = 50 obj.spectrum_plot.title = "Spectrum" spec_range = obj.spectrum_plot.plots.values()[0][0].value_mapper.range spec_range.low = 0.0 spec_range.high = 5.0 obj.spectrum_plot.index_axis.title = 'Frequency (hz)' obj.spectrum_plot.value_axis.title = 'Amplitude' # Time Series plot times = linspace(0., float(NUM_SAMPLES)/SAMPLING_RATE, num=NUM_SAMPLES) obj.time_data = ArrayPlotData(time=times) empty_amplitude = zeros(NUM_SAMPLES) obj.time_data.set_data('amplitude', empty_amplitude) obj.time_plot = Plot(obj.time_data) obj.time_plot.plot(("time", "amplitude"), name="Time", color="blue") obj.time_plot.padding = 50 obj.time_plot.title = "Time" obj.time_plot.index_axis.title = 'Time (seconds)' obj.time_plot.value_axis.title = 'Amplitude' time_range = obj.time_plot.plots.values()[0][0].value_mapper.range time_range.low = -0.2 time_range.high = 0.2 # Spectrogram plot spectrogram_data = zeros(( NUM_SAMPLES/2, SPECTROGRAM_LENGTH)) obj.spectrogram_plotdata = ArrayPlotData() obj.spectrogram_plotdata.set_data('imagedata', spectrogram_data) spectrogram_plot = Plot(obj.spectrogram_plotdata) spectrogram_time = linspace( 0.0, float(SPECTROGRAM_LENGTH*NUM_SAMPLES)/float(SAMPLING_RATE), num=SPECTROGRAM_LENGTH) spectrogram_freq = linspace(0.0, float(SAMPLING_RATE/2), num=NUM_SAMPLES/2) spectrogram_plot.img_plot('imagedata', name='Spectrogram', xbounds=spectrogram_time, ybounds=spectrogram_freq, colormap=jet, ) range_obj = spectrogram_plot.plots['Spectrogram'][0].value_mapper.range range_obj.high = 5 range_obj.low = 0.0 spectrogram_plot.title = 'Spectrogram' obj.spectrogram_plot = spectrogram_plot container = HPlotContainer() container.add(obj.spectrum_plot) container.add(obj.time_plot) container.add(spectrogram_plot) return container
|
_stream = None
|
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0., float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(NUM_SAMPLES/2) obj.spectrum_data.set_data('amplitude', empty_amplitude) obj.spectrum_plot = Plot(obj.spectrum_data) obj.spectrum_plot.plot(("frequency", "amplitude"), name="Spectrum", color="red") obj.spectrum_plot.padding = 50 obj.spectrum_plot.title = "Spectrum" spec_range = obj.spectrum_plot.plots.values()[0][0].value_mapper.range spec_range.low = 0.0 spec_range.high = 5.0 obj.spectrum_plot.index_axis.title = 'Frequency (hz)' obj.spectrum_plot.value_axis.title = 'Amplitude' # Time Series plot times = linspace(0., float(NUM_SAMPLES)/SAMPLING_RATE, num=NUM_SAMPLES) obj.time_data = ArrayPlotData(time=times) empty_amplitude = zeros(NUM_SAMPLES) obj.time_data.set_data('amplitude', empty_amplitude) obj.time_plot = Plot(obj.time_data) obj.time_plot.plot(("time", "amplitude"), name="Time", color="blue") obj.time_plot.padding = 50 obj.time_plot.title = "Time" obj.time_plot.index_axis.title = 'Time (seconds)' obj.time_plot.value_axis.title = 'Amplitude' time_range = obj.time_plot.plots.values()[0][0].value_mapper.range time_range.low = -0.2 time_range.high = 0.2 # Spectrogram plot spectrogram_data = zeros(( NUM_SAMPLES/2, SPECTROGRAM_LENGTH)) obj.spectrogram_plotdata = ArrayPlotData() obj.spectrogram_plotdata.set_data('imagedata', spectrogram_data) spectrogram_plot = Plot(obj.spectrogram_plotdata) spectrogram_time = linspace( 0.0, float(SPECTROGRAM_LENGTH*NUM_SAMPLES)/float(SAMPLING_RATE), num=SPECTROGRAM_LENGTH) spectrogram_freq = linspace(0.0, float(SAMPLING_RATE/2), num=NUM_SAMPLES/2) spectrogram_plot.img_plot('imagedata', name='Spectrogram', xbounds=spectrogram_time, ybounds=spectrogram_freq, colormap=jet, ) range_obj = spectrogram_plot.plots['Spectrogram'][0].value_mapper.range range_obj.high = 5 range_obj.low = 0.0 spectrogram_plot.title = 'Spectrogram' obj.spectrogram_plot = spectrogram_plot container = HPlotContainer() container.add(obj.spectrum_plot) container.add(obj.time_plot) container.add(spectrogram_plot) return container
|
|
global _stream if _stream is None: pa = pyaudio.PyAudio() _stream = pa.open(format=pyaudio.paInt16, channels=1, rate=SAMPLING_RATE, input=True, frames_per_buffer=NUM_SAMPLES) audio_data = fromstring(_stream.read(NUM_SAMPLES), dtype=short)
|
pa = pyaudio.PyAudio() stream = pa.open(format=pyaudio.paInt16, channels=1, rate=SAMPLING_RATE, input=True, frames_per_buffer=NUM_SAMPLES) audio_data = fromstring(stream.read(NUM_SAMPLES), dtype=short) stream.close()
|
def get_audio_data(): global _stream if _stream is None: # The audio stream is opened the first time this function gets called. # The stream is always closed (if it was opened) in a try finally # block at the end of this file, pa = pyaudio.PyAudio() _stream = pa.open(format=pyaudio.paInt16, channels=1, rate=SAMPLING_RATE, input=True, frames_per_buffer=NUM_SAMPLES) audio_data = fromstring(_stream.read(NUM_SAMPLES), dtype=short) normalized_data = audio_data / 32768.0 return (abs(fft(normalized_data))[:NUM_SAMPLES/2], normalized_data)
|
try: demo_main(PlotFrame, size=size, title=title) finally: if _stream is not None: _stream.close()
|
demo_main(PlotFrame, size=size, title=title)
|
def onClose(self, event): #sys.exit() self.timer.Stop() event.Skip()
|
if len(coordinates) < 2: return 1.0 dy = coordinates[1] - coordinates[0]
|
if len(coordinates) > 1: dy = coordinates[1] - coordinates[0] else: dy = 1.0
|
def _get_amplitude_scale(self): """ If the amplitude is set to this value, the largest trace deviation from is base y coordinates will be equal to the y coordinate spacing. """ # Note: Like the rest of the current code, this ignores the `scale` attribute.
|
amp_scale = 0.5 * dy / max_abs
|
if max_abs == 0: amp_scale = 0.5 * dy else: amp_scale = 0.5 * dy / max_abs
|
def _get_amplitude_scale(self): """ If the amplitude is set to this value, the largest trace deviation from is base y coordinates will be equal to the y coordinate spacing. """ # Note: Like the rest of the current code, this ignores the `scale` attribute.
|
tmax = varray.max() tmin = varray.min() if tmax < self.value_range.low or tmin > self.value_range.high:
|
ylow, yhigh = varray.min(), varray.max() if ylow > self.value_range.high or yhigh < self.value_range.low:
|
def _gather_points(self): """ Collects the data points that are within the bounds of the plot and caches them. """
|
self.clip_to_rect(0, 0, trans_width, trans_height)
|
self.clip_to_rect(0, 0, width, height)
|
def render_component(self, component, container_coords=False, halign="center", valign="top"): """ Erases the current contents of the graphics context and renders the given component at the maximum possible scaling while preserving aspect ratio. Parameters ---------- component : Component The component to be rendered. container_coords : Boolean Whether to use coordinates of the component's container halign : "center", "left", "right" Determines the position of the component if it is narrower than the graphics context area (after scaling) valign : "center", "top", "bottom" Determiens the position of the component if it is shorter than the graphics context area (after scaling) Description ----------- If *container_coords* is False, then the (0,0) coordinate of this graphics context corresponds to the lower-left corner of the component's **outer_bounds**. If *container_coords* is True, then the method draws the component as it appears inside its container, i.e., it treats (0,0) of the graphics context as the lower-left corner of the container's outer bounds. """ x, y = component.outer_position if container_coords: width, height = component.container.bounds else: x = -x y = -y width, height = component.outer_bounds
|
component.draw(self, view_bounds=(0, 0, trans_width, trans_height))
|
component.draw(self, view_bounds=(0, 0, width, height))
|
def render_component(self, component, container_coords=False, halign="center", valign="top"): """ Erases the current contents of the graphics context and renders the given component at the maximum possible scaling while preserving aspect ratio. Parameters ---------- component : Component The component to be rendered. container_coords : Boolean Whether to use coordinates of the component's container halign : "center", "left", "right" Determines the position of the component if it is narrower than the graphics context area (after scaling) valign : "center", "top", "bottom" Determiens the position of the component if it is shorter than the graphics context area (after scaling) Description ----------- If *container_coords* is False, then the (0,0) coordinate of this graphics context corresponds to the lower-left corner of the component's **outer_bounds**. If *container_coords* is True, then the method draws the component as it appears inside its container, i.e., it treats (0,0) of the graphics context as the lower-left corner of the container's outer bounds. """ x, y = component.outer_position if container_coords: width, height = component.container.bounds else: x = -x y = -y width, height = component.outer_bounds
|
_trace_data = Property(Array, depends_on=['index', 'value', 'yindex', 'amplitude', 'scale', 'offset'])
|
_trace_data = Property(Array, depends_on=['index', 'index.data_changed', 'value', 'value.data_changed', 'yindex', 'yindex.data_changed', 'amplitude', 'scale', 'offset'])
|
def time_ms(t): s = "%5.1f ms" % (t * 1000) return s
|
zoom_to_mouse = Bool(True)
|
zoom_to_mouse = Bool(False)
|
def revert(self, zoom_tool): if isinstance(zoom_tool.component.index_mapper, GridMapper): index_mapper = zoom_tool.component.index_mapper._xmapper value_mapper = zoom_tool.component.index_mapper._ymapper else: index_mapper = zoom_tool.component.index_mapper value_mapper = zoom_tool.component.value_mapper zoom_tool._zoom_in_mapper(index_mapper, self.prev[0]/self.next[0]) zoom_tool._zoom_in_mapper(value_mapper, self.prev[1]/self.next[1])
|
gc.draw_marker_at_points(screen_pts, 3, DOT_MARKER)
|
if hasattr(gc, 'draw_marker_at_points'): gc.draw_marker_at_points(screen_pts, 3, DOT_MARKER) else: gc.save_state() for sx,sy in screen_pts: gc.translate_ctm(sx, sy) gc.begin_path() self.marker.add_to_path(gc, 3) gc.draw_path(self.marker.draw_mode) gc.translate_ctm(-sx, -sy) gc.restore_state()
|
def overlay(self, component, gc, view_bounds=None, mode='normal'): x_range = self._get_selection_index_screen_range() y_range = self._get_selection_value_screen_range() if len(x_range) == 0: return x1, x2 = x_range y1, y2 = y_range
|
rotation=self.tick_label_rotate_angle, *tl_bounds) + \
|
rotation=0, *tl_bounds) + \
|
def _draw_labels(self, gc): """ Draws the tick labels for the axis. """ for i in range(len(self._tick_label_positions)): #We want a more sophisticated scheme than just 2 decimals all the time ticklabel = self.ticklabel_cache[i] tl_bounds = self._tick_label_bounding_boxes[i]
|
if self.fixed_preferred_size == "":
|
if self.fixed_preferred_size is not None:
|
def get_preferred_size(self, components=None): """ Returns the size (width,height) that is preferred for this component.
|
hostname = os.uname()[1]
|
hostname = socket.gethostname()
|
def get_hostname(): hostname = os.uname()[1] # Convert the machine's hostname into alphanumeric characters, suitable for python module names # Note: We don't want to use \W because it also matches underscores. # The string segment "._." would end up as "___" instead of "_". hostname = re.sub('[^a-zA-Z0-9]+', '_', hostname) return hostname
|
def cache_trace(dst, trace=None): if isinstance(dst, types.StringTypes): dst = unpack(b'!i', socket.inet_aton(dst))[0]
|
def cache_object(key, value=None, ext=None): if ext: key = '{0}__{1}'.format(ext, key) key, key_hr = buffer(pickle.dumps(key, -1)), key
|
def cache_trace(dst, trace=None): if isinstance(dst, types.StringTypes): dst = unpack(b'!i', socket.inet_aton(dst))[0] cur = geoip_db.cursor() if trace is None: cur.execute('SELECT trace, ts FROM trace_cache WHERE dst = ?', (dst,)) # exit() try: trace, ts = next(cur) except StopIteration: raise KeyError if ts < time() - optz.trace_cache_obsoletion: raise KeyError(ts) return pickle.loads(bytes(trace)) else: log.debug('Caching trace to {0}'.format(dst)) cur.execute( 'INSERT OR REPLACE' ' INTO trace_cache (dst, trace, ts) VALUES (?, ?, ?)', (dst, buffer(pickle.dumps(trace, -1)), int(time())) ) # GC global _cache_gc_counter try: _cache_gc_counter() except StopIteration: cur.execute('SELECT COUNT(*) FROM trace_cache') log.debug('GC - trace_cache oversaturation: {0}'.format(clean_count)) clean_count = next(cur)[0] - optz.trace_cache_max_size if clean_count > 0: cur.execute( 'DELETE FROM trace_cache' ' ORDER BY ts LIMIT ?', (clean_count,) ) _cache_gc_counter.reset() except TypeError: _cache_gc_counter = countdown(optz.trace_cache_max_size / 10, 'trace_cache') geoip_db.commit() return trace
|
if trace is None: cur.execute('SELECT trace, ts FROM trace_cache WHERE dst = ?', (dst,)) try: trace, ts = next(cur)
|
if value is None: cur.execute('SELECT value, ts FROM object_cache WHERE key = ?', (key,)) try: value, ts = next(cur)
|
def cache_trace(dst, trace=None): if isinstance(dst, types.StringTypes): dst = unpack(b'!i', socket.inet_aton(dst))[0] cur = geoip_db.cursor() if trace is None: cur.execute('SELECT trace, ts FROM trace_cache WHERE dst = ?', (dst,)) # exit() try: trace, ts = next(cur) except StopIteration: raise KeyError if ts < time() - optz.trace_cache_obsoletion: raise KeyError(ts) return pickle.loads(bytes(trace)) else: log.debug('Caching trace to {0}'.format(dst)) cur.execute( 'INSERT OR REPLACE' ' INTO trace_cache (dst, trace, ts) VALUES (?, ?, ?)', (dst, buffer(pickle.dumps(trace, -1)), int(time())) ) # GC global _cache_gc_counter try: _cache_gc_counter() except StopIteration: cur.execute('SELECT COUNT(*) FROM trace_cache') log.debug('GC - trace_cache oversaturation: {0}'.format(clean_count)) clean_count = next(cur)[0] - optz.trace_cache_max_size if clean_count > 0: cur.execute( 'DELETE FROM trace_cache' ' ORDER BY ts LIMIT ?', (clean_count,) ) _cache_gc_counter.reset() except TypeError: _cache_gc_counter = countdown(optz.trace_cache_max_size / 10, 'trace_cache') geoip_db.commit() return trace
|
if ts < time() - optz.trace_cache_obsoletion: raise KeyError(ts) return pickle.loads(bytes(trace))
|
if ts < time() - optz.cache_obsoletion: raise KeyError(ts) return pickle.loads(bytes(value))
|
def cache_trace(dst, trace=None): if isinstance(dst, types.StringTypes): dst = unpack(b'!i', socket.inet_aton(dst))[0] cur = geoip_db.cursor() if trace is None: cur.execute('SELECT trace, ts FROM trace_cache WHERE dst = ?', (dst,)) # exit() try: trace, ts = next(cur) except StopIteration: raise KeyError if ts < time() - optz.trace_cache_obsoletion: raise KeyError(ts) return pickle.loads(bytes(trace)) else: log.debug('Caching trace to {0}'.format(dst)) cur.execute( 'INSERT OR REPLACE' ' INTO trace_cache (dst, trace, ts) VALUES (?, ?, ?)', (dst, buffer(pickle.dumps(trace, -1)), int(time())) ) # GC global _cache_gc_counter try: _cache_gc_counter() except StopIteration: cur.execute('SELECT COUNT(*) FROM trace_cache') log.debug('GC - trace_cache oversaturation: {0}'.format(clean_count)) clean_count = next(cur)[0] - optz.trace_cache_max_size if clean_count > 0: cur.execute( 'DELETE FROM trace_cache' ' ORDER BY ts LIMIT ?', (clean_count,) ) _cache_gc_counter.reset() except TypeError: _cache_gc_counter = countdown(optz.trace_cache_max_size / 10, 'trace_cache') geoip_db.commit() return trace
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.