rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
attributes = None | attributes = {'guid': list_record['id']} | def save(self, old_record, list_record, detail_record): kwargs = self.unique_fields(list_record) |
attributes = {'rating': rating} | attributes['rating'] = rating | def save(self, old_record, list_record, detail_record): kwargs = self.unique_fields(list_record) |
kwargs.update(dict(description=content, location=location, )) if old_record: self.update_existing(old_record, kwargs, attributes) else: self.create_newsitem(attributes=attributes, **kwargs) | kwargs['description'] = content | def save(self, old_record, list_record, detail_record): kwargs = self.unique_fields(list_record) |
def unique_fields(self, list_record): import datetime date = datetime.date(*list_record['updated_parsed'][:3]) summary_detail = list_record['summary_detail']['value'] addr = address_re.search(summary_detail) if addr: addr = addr.group(1) location_name = ', '.join([part.strip() for part in addr.split(',')]) else: location_name = u'' | kwargs['location'] = location | def unique_fields(self, list_record): # not necessarily primary key, but for this script's purposes # these are the fields that in combination uniquely idenfity # an article. import datetime date = datetime.date(*list_record['updated_parsed'][:3]) summary_detail = list_record['summary_detail']['value'] addr = address_re.search(summary_detail) if addr: addr = addr.group(1) location_name = ', '.join([part.strip() for part in addr.split(',')]) else: location_name = u'' |
return dict(item_date=date, location_name=location_name, title=list_record['title'], ) | self.create_or_update(old_record, attributes, **kwargs) | def unique_fields(self, list_record): # not necessarily primary key, but for this script's purposes # these are the fields that in combination uniquely idenfity # an article. import datetime date = datetime.date(*list_record['updated_parsed'][:3]) summary_detail = list_record['summary_detail']['value'] addr = address_re.search(summary_detail) if addr: addr = addr.group(1) location_name = ', '.join([part.strip() for part in addr.split(',')]) else: location_name = u'' |
self.assertRaises(AssertionError, make_pid, b) | self.assertRaises(TypeError, make_pid, b) | def test_make_pid__block__not_enough_args(self): b = self._makeBlock() self.assertRaises(AssertionError, make_pid, b) |
def existing_record(self, record): return None | def existing_record(self, list_record): pk_fields = self.pk_fields(list_record) qs = NewsItem.objects.filter(schema__id=self.schema.id, **pk_fields) try: return qs[0] except IndexError: return None | def existing_record(self, record): # TODO return None |
title = list_record['title'] location = Point((float(list_record['geo_lat']), float(list_record['geo_long']))) | return dict(item_date=date, title=u'SeeClickFix: ' + list_record['title'], ) | def save(self, old_record, list_record, detail_record): summary_detail = list_record['summary_detail']['value'] content = list_record['summary'] # remove address and rating from content, i guess. content = content.replace(summary_detail, '') import re address_re = re.compile(r'Address: (.*?)<br />') addr = address_re.search(summary_detail) if addr: addr = addr.group(1) location_name = ', '.join([part.strip() for part in addr.split(',')]) else: location_name = u'' import datetime date = datetime.date(*list_record['updated_parsed'][:3]) title = list_record['title'] location = Point((float(list_record['geo_lat']), float(list_record['geo_long']))) |
if (location.x, location.y) == (0,0, 0.0): print "skipping %r as it has bad location 0,0" % title return self.create_newsitem( attributes=None, title=u'SeeClickFix: ' + title, description=list_record['summary_detail']['value'], item_date=date, location_name=location_name, location=location, ) | def save(self, old_record, list_record, detail_record): summary_detail = list_record['summary_detail']['value'] content = list_record['summary'] # remove address and rating from content, i guess. content = content.replace(summary_detail, '') import re address_re = re.compile(r'Address: (.*?)<br />') addr = address_re.search(summary_detail) if addr: addr = addr.group(1) location_name = ', '.join([part.strip() for part in addr.split(',')]) else: location_name = u'' import datetime date = datetime.date(*list_record['updated_parsed'][:3]) title = list_record['title'] location = Point((float(list_record['geo_lat']), float(list_record['geo_long']))) |
|
from ebdata.retrieval import log_debug | def save(self, old_record, list_record, detail_record): summary_detail = list_record['summary_detail']['value'] content = list_record['summary'] # remove address and rating from content, i guess. content = content.replace(summary_detail, '') import re address_re = re.compile(r'Address: (.*?)<br />') addr = address_re.search(summary_detail) if addr: addr = addr.group(1) location_name = ', '.join([part.strip() for part in addr.split(',')]) else: location_name = u'' import datetime date = datetime.date(*list_record['updated_parsed'][:3]) title = list_record['title'] location = Point((float(list_record['geo_lat']), float(list_record['geo_long']))) |
|
return '/%s/by-date/%s/%s/%s/' % (self.schema.slug, self.item_date.year, self.item_date.month, self.item_date.day) | year = self.item_date.year month = self.item_date.month day = self.item_date.day slug = self.schema.slug return '/%(slug)s/by-date/%(year)s-%(month)s-%(day)s,%(year)s-%(month)s-%(day)s/' % locals() | def item_date_url(self): return '/%s/by-date/%s/%s/%s/' % (self.schema.slug, self.item_date.year, self.item_date.month, self.item_date.day) |
return tree.body.text.strip() | if tree.body.text: return tree.body.text.strip() else: return u'' | def preprocess_to_string(*args, **kw): """ like make_tree_and_preprocess() but returns a string. """ tree = make_tree_and_preprocess(*args, **kw) return tree.body.text.strip() |
return u'User %s: %u' % (self.user_id, self.name()) | return u'User %d: %s' % (self.user_id, self.name()) | def __unicode__(self): return u'User %s: %u' % (self.user_id, self.name()) |
print len(geo_entries) | def geo_example(request): import feedparser from ebdata.nlp.addresses import parse_addresses from ebpub.geocoder.base import AddressGeocoder feed_url = 'http://www.bpdnews.com/index.xml' feed = feedparser.parse(feed_url) geocoder = AddressGeocoder() geo_entries = [] for entry in feed.entries: addresses = parse_addresses(entry.description) point = None while not point: for address in addresses: try: location = geocoder.geocode(address[0]) point = location['point'] break except Exception: pass if not point: point = -1 if point and point is not -1: entry['point'] = point geo_entries.append(entry) print len(geo_entries) return render_to_response('db/geo_example.html', {'entries': geo_entries }) |
|
max_per_page = 200 max_pages = 10 | max_per_page = 500 max_pages = 4 | def list_pages(self): # Fetch the feed, paginating if necessary. # See API docs at # http://help.seeclickfix.com/faqs/api/listing-issues max_per_page = 200 max_pages = 10 |
import pprint for info in SeeClickFixNewsFeedScraper().raw_data(): pprint.pprint(info['detail']) | SeeClickFixNewsFeedScraper().display_data() | def save(self, old_record, list_record, detail_record): attributes = detail_record.pop('attributes', None) self.create_or_update(old_record, attributes, **detail_record) |
def get_unique_fields(list_record): | class SeeClickFixNewsFeedScraper(RssListDetailScraper, NewsItemListDetailScraper): """ For all of these methods, see docstrings in ebdata.retrieval.scrapers.list_detail.ListDetailScraper """ | def get_unique_fields(list_record): # not necessarily primary key, but for this script's purposes # these are the fields that in combination uniquely identify # an article. # TODO: 'id' is all we need for uniqueness, but what i'm doing # here is really cleaning? date = datetime.date(*list_record['updated_parsed'][:3]) summary_detail = list_record['summary_detail']['value'] addr = address_re.search(summary_detail) if addr: addr = addr.group(1) location_name = ', '.join([part.strip() for part in addr.split(',')]) else: location_name = u'' return dict(id=list_record['id'], item_date=date, location_name=location_name, title=list_record['title'], ) |
date = datetime.date(*list_record['updated_parsed'][:3]) summary_detail = list_record['summary_detail']['value'] addr = address_re.search(summary_detail) if addr: addr = addr.group(1) location_name = ', '.join([part.strip() for part in addr.split(',')]) else: location_name = u'' return dict(id=list_record['id'], item_date=date, location_name=location_name, title=list_record['title'], ) class SeeClickFixNewsFeedScraper(RssListDetailScraper, NewsItemListDetailScraper): | def get_unique_fields(list_record): # not necessarily primary key, but for this script's purposes # these are the fields that in combination uniquely identify # an article. # TODO: 'id' is all we need for uniqueness, but what i'm doing # here is really cleaning? date = datetime.date(*list_record['updated_parsed'][:3]) summary_detail = list_record['summary_detail']['value'] addr = address_re.search(summary_detail) if addr: addr = addr.group(1) location_name = ', '.join([part.strip() for part in addr.split(',')]) else: location_name = u'' return dict(id=list_record['id'], item_date=date, location_name=location_name, title=list_record['title'], ) |
|
has_detail = False | has_detail = True | def get_unique_fields(list_record): # not necessarily primary key, but for this script's purposes # these are the fields that in combination uniquely identify # an article. # TODO: 'id' is all we need for uniqueness, but what i'm doing # here is really cleaning? date = datetime.date(*list_record['updated_parsed'][:3]) summary_detail = list_record['summary_detail']['value'] addr = address_re.search(summary_detail) if addr: addr = addr.group(1) location_name = ', '.join([part.strip() for part in addr.split(',')]) else: location_name = u'' return dict(id=list_record['id'], item_date=date, location_name=location_name, title=list_record['title'], ) |
max_per_page = 1000 | max_per_page = 200 | def list_pages(self): # See API docs at # http://help.seeclickfix.com/faqs/api/listing-issues # paginate if necessary. max_per_page = 1000 max_pages = 10 # First, figure out how long it's been since the last scrape; # seeclickfix has a 'start' option in hours. # We'll discard microseconds and round up. # The idea is not to be precise, but to get everything we haven't # seen yet and not much that we have seen. delta = datetime.datetime.now() - self.last_updated_time() hours_ago = math.ceil((delta.seconds / 3600.0) + (delta.days * 24)) for page in range(1, max_pages + 1): url = LIST_URL + '&start=%d&page=%d&num_results=%d' % ( hours_ago, page, max_per_page) yield self.get_html(url) |
url = LIST_URL + '&start=%d&page=%d&num_results=%d' % ( | feed_url = FEED_URL + '&start=%d&page=%d&num_results=%d' % ( | def list_pages(self): # See API docs at # http://help.seeclickfix.com/faqs/api/listing-issues # paginate if necessary. max_per_page = 1000 max_pages = 10 # First, figure out how long it's been since the last scrape; # seeclickfix has a 'start' option in hours. # We'll discard microseconds and round up. # The idea is not to be precise, but to get everything we haven't # seen yet and not much that we have seen. delta = datetime.datetime.now() - self.last_updated_time() hours_ago = math.ceil((delta.seconds / 3600.0) + (delta.days * 24)) for page in range(1, max_pages + 1): url = LIST_URL + '&start=%d&page=%d&num_results=%d' % ( hours_ago, page, max_per_page) yield self.get_html(url) |
yield self.get_html(url) | yield self.fetch_data(feed_url) | def list_pages(self): # See API docs at # http://help.seeclickfix.com/faqs/api/listing-issues # paginate if necessary. max_per_page = 1000 max_pages = 10 # First, figure out how long it's been since the last scrape; # seeclickfix has a 'start' option in hours. # We'll discard microseconds and round up. # The idea is not to be precise, but to get everything we haven't # seen yet and not much that we have seen. delta = datetime.datetime.now() - self.last_updated_time() hours_ago = math.ceil((delta.seconds / 3600.0) + (delta.days * 24)) for page in range(1, max_pages + 1): url = LIST_URL + '&start=%d&page=%d&num_results=%d' % ( hours_ago, page, max_per_page) yield self.get_html(url) |
def existing_record(self, list_record): qs = NewsItem.objects.filter(schema__id=self.schema.id) qs = qs.by_attribute(self.schema_fields['guid'], list_record['id']) | def existing_record(self, cleaned_list_record): url = cleaned_list_record['id'].replace('https:', 'http:') qs = NewsItem.objects.filter(schema__id=self.schema.id, url=url) | def existing_record(self, list_record): qs = NewsItem.objects.filter(schema__id=self.schema.id) qs = qs.by_attribute(self.schema_fields['guid'], list_record['id']) try: return qs[0] except IndexError: return None |
if old_record is not None: self.logger.info("Stopping, we've already seen %s" % old_record) raise StopScraping() | def save(self, old_record, list_record, detail_record): if old_record is not None: self.logger.info("Stopping, we've already seen %s" % old_record) raise StopScraping() |
|
kwargs = get_unique_fields(list_record) location = self.get_location(list_record) if (location.x, location.y) == (0,0, 0.0): self.logger.warn("skipping %r as it has bad location 0,0" % list_record['title']) return summary_detail = list_record['summary_detail']['value'] content = list_record['summary'] content = address_re.sub('', content) rating = rating_re.search(content) attributes = {'guid': list_record['id']} if rating: rating = int(rating.group(1)) attributes['rating'] = rating content = rating_re.sub('', content) content = preprocess_to_string(content, drop_tags=('p', 'br', 'b',)) kwargs['description'] = content kwargs['location'] = location self.create_or_update(old_record, attributes, **kwargs) | attributes = detail_record.pop('attributes', None) self.create_or_update(old_record, attributes, **detail_record) | def save(self, old_record, list_record, detail_record): if old_record is not None: self.logger.info("Stopping, we've already seen %s" % old_record) raise StopScraping() |
from ebdata.retrieval import log_debug SeeClickFixNewsFeedScraper().update() | TESTING = True if TESTING: from ebdata.retrieval import log_debug import pprint for info in SeeClickFixNewsFeedScraper().raw_data(): pprint.pprint(info['detail']) else: SeeClickFixNewsFeedScraper().update() | def save(self, old_record, list_record, detail_record): if old_record is not None: self.logger.info("Stopping, we've already seen %s" % old_record) raise StopScraping() |
time = datetime.utcnow() - timedelta(minutes = 30) | time = datetime.utcnow() | def testBoatWindVersusWeather(self): settings = Settings() weather = Weather() weather.load(settings) wind = Wind(weather) |
off_track_angle = normalize_angle_pipi(track[0] - heading) | off_track_angle = normalize_angle_pipi(heading - track[0]) | def handle_tacking_and_gybing(self, heading, bearing): wind = self.boat.condition.wind wind_angle = normalize_angle_pipi(wind[0] - heading) track, waypoint = self.router.get_active_segment() |
+ 60 * math.cos(0.8 * off_track_angle) ^ 2 | + 60 * math.pow(math.cos(0.8 * off_track_angle), 2) | def handle_tacking_and_gybing(self, heading, bearing): wind = self.boat.condition.wind wind_angle = normalize_angle_pipi(wind[0] - heading) track, waypoint = self.router.get_active_segment() |
allowed_off_track = waypoint.range + off_track_mult * math.sqrt(bearing[1]) | allowed_off_track = off_track_mult * math.sqrt(bearing[1]) | def handle_tacking_and_gybing(self, heading, bearing): wind = self.boat.condition.wind wind_angle = normalize_angle_pipi(wind[0] - heading) track, waypoint = self.router.get_active_segment() |
cs = math.cos(track[0] - bearing[0]) | cos_approach_angle = math.cos(track[0] - bearing[0]) | def handle_tacking_and_gybing(self, heading, bearing): wind = self.boat.condition.wind wind_angle = normalize_angle_pipi(wind[0] - heading) track, waypoint = self.router.get_active_segment() |
if abs(off_track) > allowed_off_track or cs < 0.72: | if abs(off_track) > allowed_off_track or cos_approach_angle < 0.72: | def handle_tacking_and_gybing(self, heading, bearing): wind = self.boat.condition.wind wind_angle = normalize_angle_pipi(wind[0] - heading) track, waypoint = self.router.get_active_segment() |
track_angle = normalize_angle_pipi(heading - track[0]) if (off_track > 0) == (track_angle > 0): | off_bearing_angle = normalize_angle_pipi(heading - bearing[0]) if (off_track > 0) == (off_bearing_angle > 0): | def handle_tacking_and_gybing(self, heading, bearing): wind = self.boat.condition.wind wind_angle = normalize_angle_pipi(wind[0] - heading) track, waypoint = self.router.get_active_segment() |
track_angle = normalize_angle_pipi(heading - track[0]) | off_bearing_angle = normalize_angle_pipi(heading - bearing[0]) | def prevent_beaching(self, heading, look_ahead = None): if look_ahead == None: look_ahead = 250 # We'll construct a future course line... boat_position = self.boat.position # ... project it ahead... sail_vector = PolarVector(heading, look_ahead) future_position = boat_position + sail_vector sail_line = (self.boat.position, sail_vector, future_position) # Check if the projected line hits land... if self.map.hit(sail_line): # ... and if so, tack or gybe away from it wind = self.boat.condition.wind wind_angle = normalize_angle_pipi(wind[0] - heading) self.__log("Tacked/gybed to avoid hitting land") return True, normalize_angle_2pi(heading + 2 * wind_angle) |
if (off_track > 0) == (track_angle > 0): | if (off_track > 0) == (off_bearing_angle > 0): | def prevent_beaching(self, heading, look_ahead = None): if look_ahead == None: look_ahead = 250 # We'll construct a future course line... boat_position = self.boat.position # ... project it ahead... sail_vector = PolarVector(heading, look_ahead) future_position = boat_position + sail_vector sail_line = (self.boat.position, sail_vector, future_position) # Check if the projected line hits land... if self.map.hit(sail_line): # ... and if so, tack or gybe away from it wind = self.boat.condition.wind wind_angle = normalize_angle_pipi(wind[0] - heading) self.__log("Tacked/gybed to avoid hitting land") return True, normalize_angle_2pi(heading + 2 * wind_angle) |
elif elem.tag == '{'+dcterms+'}license' | elif elem.tag == '{'+dcterms+'}license': | def readmeta(item,meta): for elem in meta: if elem.tag.find(dc): if elem.tag == '{'+dc+'}date': try: item.info.date = datetime.strptime(elem.text,"%Y-%m-%dT%H:%M:%S.%f") except ValueError, e: if str(e) == "'f' is a bad directive in format '%Y-%m-%dT%H:%M:%S.%f'": # Python 2.5 item.info.date = datetime.strptime(elem.text.split('.')[0],"%Y-%m-%dT%H:%M:%S") else: remain = str(e)[26:] if remain == 'Z': item.info.date = datetime.strptime(elem.text[:-len(remain)],"%Y-%m-%dT%H:%M:%S.%f") else: date = datetime.strptime(elem.text[:-len(remain)],"%Y-%m-%dT%H:%M:%S.%f") delta = remain.split(':') item.info.date = date - timedelta(hours=int(delta[0]),minutes=int(delta[1])) elif elem.tag == '{'+dc+'}type': if elem.attrib['{'+rdf+'}resource'] != 'http://purl.org/dc/dcmitype/Dataset': raise FileFormatError elif elem.tag == '{'+dc+'}format': if elem.text != 'application/swatchbook': raise FileFormatError elif '{'+xml+'}lang' in elem.attrib: exec("item.info."+elem.tag[(len(dc)+2):]+"_l10n[elem.attrib['{'+xml+'}lang']] = xmlunescape(elem.text)") else: exec("item.info."+elem.tag[(len(dc)+2):]+" = xmlunescape(elem.text)") elif elem.tag == '{'+dcterms+'}license' item.info.license = xmlunescape(elem.attrib['{'+rdf+'}resource']) |
xml = '<?xml version="1.0" encoding="UTF-8"?>\n<SwatchBook version="0.7"\n xmlns:dc="http://purl.org/dc/elements/1.1/"\n xmlns:cc="http://creativecommons.org/ns | xml = '<?xml version="1.0" encoding="UTF-8"?>\n<SwatchBook version="0.7"\n xmlns:dc="'+dc+'"\n xmlns:cc="'+cc+'"\n xmlns:rdf="'+rdf+'">\n' | def write(swatchbook): xml = '<?xml version="1.0" encoding="UTF-8"?>\n<SwatchBook version="0.7"\n xmlns:dc="http://purl.org/dc/elements/1.1/"\n xmlns:cc="http://creativecommons.org/ns#"\n xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n' xml += sbz.writemeta(swatchbook.info) xml += ' <swatches>\n' for id in swatchbook.swatches: if isinstance(swatchbook.swatches[id], Color): swatch = swatchbook.swatches[id] xml += ' <color' if 'spot' in swatch.usage: xml += ' spot="1"' xml += '>\n' xml += sbz.writemeta(swatch.info,2) for value in swatch.values: xml += ' <values model="'+value[0]+'"' if value[1]: xml += ' space="'+value[1]+'"' xml += '>'+' '.join(str(round(x,16)) for x in swatch.values[value])+'</values>\n' for extra in swatch.extra: xml += ' <extra type="'+xmlescape(extra)+'">' if swatch.extra[extra]: xml += xmlescape(unicode(swatch.extra[extra])) xml += '</extra>\n' xml += ' </color>\n' xml += ' </swatches>\n' if len(swatchbook.book.items) > 0: xml += ' <book' for display in swatchbook.book.display: if swatchbook.book.display[display]: xml += ' '+display+'="'+str(swatchbook.book.display[display])+'"' xml += '>\n' xml += unicode(sbz.writem(swatchbook.book.items),'utf-8') xml += ' </book>\n' xml += '</SwatchBook>\n' tf = open(tempfile.mkstemp()[1],"w+b") zip = ZipFile(tf,'w',ZIP_DEFLATED) zip.writestr('swatchbook.xml',xml.encode('utf-8')) for profile in swatchbook.profiles: zip.write(swatchbook.profiles[profile].uri,'profiles/'+profile) zip.close() tf.seek(0) return tf.read() |
if lang == 0: xml += ' <info type="'+info+'">'+xmlescape(book.info[info][0])+'</info>\n' else: xml += ' <info type="'+info+'" lang="'+lang+'">'+xmlescape(book.info[info][lang])+'</info>\n' | if book.info[info][lang]: if lang == 0: xml += ' <info type="'+info+'">'+xmlescape(book.info[info][0])+'</info>\n' else: xml += ' <info type="'+info+'" lang="'+lang+'">'+xmlescape(book.info[info][lang])+'</info>\n' | def write(book): xml = '<?xml version="1.0" encoding="UTF-8"?>\n<SwatchBook version="0.2">\n' for info in book.info: if isinstance(book.info[info],dict): for lang in book.info[info]: if lang == 0: xml += ' <info type="'+info+'">'+xmlescape(book.info[info][0])+'</info>\n' else: xml += ' <info type="'+info+'" lang="'+lang+'">'+xmlescape(book.info[info][lang])+'</info>\n' else: xml += ' <info type="'+info+'">'+xmlescape(book.info[info])+'</info>\n' for display in book.display: xml += ' <display type="'+display+'">'+str(book.display[display])+'</display>\n' xml += unicode(sbz.writem(book.items,0),'utf-8') xml += '</SwatchBook>\n' tf = open(tempfile.mkstemp()[1],"w+b") zip = ZipFile(tf,'w',ZIP_DEFLATED) zip.writestr('swatchbook.xml',xml.encode('utf-8')) for profile in book.profiles: #TODO: check if exists zip.write(book.profiles[profile].uri,'profiles/'+profile) zip.close() tf.seek(0) return tf.read() |
xml += ' <info type="'+info+'">'+xmlescape(book.info[info])+'</info>\n' | if book.info[info]: xml += ' <info type="'+info+'">'+xmlescape(book.info[info])+'</info>\n' | def write(book): xml = '<?xml version="1.0" encoding="UTF-8"?>\n<SwatchBook version="0.2">\n' for info in book.info: if isinstance(book.info[info],dict): for lang in book.info[info]: if lang == 0: xml += ' <info type="'+info+'">'+xmlescape(book.info[info][0])+'</info>\n' else: xml += ' <info type="'+info+'" lang="'+lang+'">'+xmlescape(book.info[info][lang])+'</info>\n' else: xml += ' <info type="'+info+'">'+xmlescape(book.info[info])+'</info>\n' for display in book.display: xml += ' <display type="'+display+'">'+str(book.display[display])+'</display>\n' xml += unicode(sbz.writem(book.items,0),'utf-8') xml += '</SwatchBook>\n' tf = open(tempfile.mkstemp()[1],"w+b") zip = ZipFile(tf,'w',ZIP_DEFLATED) zip.writestr('swatchbook.xml',xml.encode('utf-8')) for profile in book.profiles: #TODO: check if exists zip.write(book.profiles[profile].uri,'profiles/'+profile) zip.close() tf.seek(0) return tf.read() |
xml += ' <display type="'+display+'">'+str(book.display[display])+'</display>\n' | if book.display[display]: xml += ' <display type="'+display+'">'+str(book.display[display])+'</display>\n' | def write(book): xml = '<?xml version="1.0" encoding="UTF-8"?>\n<SwatchBook version="0.2">\n' for info in book.info: if isinstance(book.info[info],dict): for lang in book.info[info]: if lang == 0: xml += ' <info type="'+info+'">'+xmlescape(book.info[info][0])+'</info>\n' else: xml += ' <info type="'+info+'" lang="'+lang+'">'+xmlescape(book.info[info][lang])+'</info>\n' else: xml += ' <info type="'+info+'">'+xmlescape(book.info[info])+'</info>\n' for display in book.display: xml += ' <display type="'+display+'">'+str(book.display[display])+'</display>\n' xml += unicode(sbz.writem(book.items,0),'utf-8') xml += '</SwatchBook>\n' tf = open(tempfile.mkstemp()[1],"w+b") zip = ZipFile(tf,'w',ZIP_DEFLATED) zip.writestr('swatchbook.xml',xml.encode('utf-8')) for profile in book.profiles: #TODO: check if exists zip.write(book.profiles[profile].uri,'profiles/'+profile) zip.close() tf.seek(0) return tf.read() |
elif elem.tag.find(cc): exec("item.info."+elem.tag[(len(cc)+2):]+" = xmlunescape(elem.text)") | elif elem.tag == '{'+dcterms+'}license' item.info.license = xmlunescape(elem.attrib['{'+rdf+'}resource']) | def readmeta(item,meta): for elem in meta: if elem.tag.find(dc): if elem.tag == '{'+dc+'}date': try: item.info.date = datetime.strptime(elem.text,"%Y-%m-%dT%H:%M:%S.%f") except ValueError, e: if str(e) == "'f' is a bad directive in format '%Y-%m-%dT%H:%M:%S.%f'": # Python 2.5 item.info.date = datetime.strptime(elem.text.split('.')[0],"%Y-%m-%dT%H:%M:%S") else: remain = str(e)[26:] if remain == 'Z': item.info.date = datetime.strptime(elem.text[:-len(remain)],"%Y-%m-%dT%H:%M:%S.%f") else: date = datetime.strptime(elem.text[:-len(remain)],"%Y-%m-%dT%H:%M:%S.%f") delta = remain.split(':') item.info.date = date - timedelta(hours=int(delta[0]),minutes=int(delta[1])) elif elem.tag == '{'+dc+'}type': if elem.attrib['{'+rdf+'}resource'] != 'http://purl.org/dc/dcmitype/Dataset': raise FileFormatError elif elem.tag == '{'+dc+'}format': if elem.text != 'application/swatchbook': raise FileFormatError elif '{'+xml+'}lang' in elem.attrib: exec("item.info."+elem.tag[(len(dc)+2):]+"_l10n[elem.attrib['{'+xml+'}lang']] = xmlunescape(elem.text)") else: exec("item.info."+elem.tag[(len(dc)+2):]+" = xmlunescape(elem.text)") elif elem.tag.find(cc): exec("item.info."+elem.tag[(len(cc)+2):]+" = xmlunescape(elem.text)") |
xml = '<?xml version="1.0" encoding="UTF-8"?>\n<SwatchBook version="0.7"\n xmlns:dc="'+dc+'"\n xmlns:cc="'+cc+'"\n xmlns:rdf="'+rdf+'">\n' | xml = '<?xml version="1.0" encoding="UTF-8"?>\n<SwatchBook version="0.7"\n xmlns:dc="'+dc+'"\n xmlns:dcterms="'+dcterms+'"\n xmlns:rdf="'+rdf+'">\n' | def write(swatchbook): xml = '<?xml version="1.0" encoding="UTF-8"?>\n<SwatchBook version="0.7"\n xmlns:dc="'+dc+'"\n xmlns:cc="'+cc+'"\n xmlns:rdf="'+rdf+'">\n' xml += sbz.writemeta(swatchbook.info) xml += ' <swatches>\n' for id in swatchbook.swatches: if isinstance(swatchbook.swatches[id], Color): swatch = swatchbook.swatches[id] xml += ' <color' if 'spot' in swatch.usage: xml += ' spot="1"' xml += '>\n' xml += sbz.writemeta(swatch.info,2) for value in swatch.values: xml += ' <values model="'+value[0]+'"' if value[1]: xml += ' space="'+value[1]+'"' xml += '>'+' '.join(str(round(x,16)) for x in swatch.values[value])+'</values>\n' for extra in swatch.extra: xml += ' <extra type="'+xmlescape(extra)+'">' if swatch.extra[extra]: xml += xmlescape(unicode(swatch.extra[extra])) xml += '</extra>\n' xml += ' </color>\n' xml += ' </swatches>\n' if len(swatchbook.book.items) > 0: xml += ' <book' for display in swatchbook.book.display: if swatchbook.book.display[display]: xml += ' '+display+'="'+str(swatchbook.book.display[display])+'"' xml += '>\n' xml += unicode(sbz.writem(swatchbook.book.items),'utf-8') xml += ' </book>\n' xml += '</SwatchBook>\n' tf = open(tempfile.mkstemp()[1],"w+b") zip = ZipFile(tf,'w',ZIP_DEFLATED) zip.writestr('swatchbook.xml',xml.encode('utf-8')) for profile in swatchbook.profiles: zip.write(swatchbook.profiles[profile].uri,'profiles/'+profile) zip.close() tf.seek(0) return tf.read() |
xml += ' '*(offset+2)+'<cc:license rdf:resource="'+xmlescape(meta.license)+'" />\n' | xml += ' '*(offset+2)+'<dcterms:license rdf:resource="'+xmlescape(meta.license)+'" />\n' | def writemeta(meta,offset=0): xml = u'' if offset == 0: xml += ' <dc:format>application/swatchbook</dc:format>\n <dc:type rdf:resource="http://purl.org/dc/dcmitype/Dataset" />\n' if meta.date: xml += ' '*(offset+2)+'<dc:date>'+meta.date.isoformat()+'Z</dc:date>\n' for dc in meta.dc: info = eval('meta.'+dc) if len(info) > 0: xml += ' '*(offset+2)+'<dc:'+dc+'>'+xmlescape(info)+'</dc:'+dc+'>\n' if meta.dc[dc][0]: info_l10n = eval('meta.'+dc+'_l10n') for lang in info_l10n: xml += ' '*(offset+2)+'<dc:'+dc+' xml:lang="'+lang+'">'+xmlescape(info_l10n[lang])+'</dc:'+dc+'>\n' if meta.license > '': xml += ' '*(offset+2)+'<cc:license rdf:resource="'+xmlescape(meta.license)+'" />\n' if xml > u'': return ' '*(offset+1)+'<metadata>\n'+xml+' '*(offset+1)+'</metadata>\n' else: return u'' |
if sys.getfilesystemencoding() == 'UTF-8' and isinstance(file,unicode): filename = os.path.splitext(os.path.basename(file))[0] else: filename = os.path.splitext(os.path.basename(file))[0].decode(sys.getfilesystemencoding()) | if sys.platform == 'win32': encoding = "UTF-8" else: encoding = sys.getfilesystemencoding() if encoding == 'UTF-8' and isinstance(file,unicode): filename = os.path.splitext(os.path.basename(file))[0] else: filename = os.path.splitext(os.path.basename(file))[0].decode(encoding) | def read(self,file,codec): import swatchbook.codecs as codecs if self.test(file,codec): eval('codecs.'+self.test(file,codec)).read(self,file) if sys.getfilesystemencoding() == 'UTF-8' and isinstance(file,unicode): filename = os.path.splitext(os.path.basename(file))[0] else: filename = os.path.splitext(os.path.basename(file))[0].decode(sys.getfilesystemencoding()) if 'name' not in self.info: self.info['name'] = {0: filename.replace('_',' ')} else: raise FileFormatError,file+': unsupported file' |
cprt = self.info['tags']['cprt'] self.info['cprt'] = self.readfield(file,cprt[1],cprt[0]) desc = self.info['tags']['desc'] self.info['desc'] = self.readfield(file,desc[1],desc[0]) | try: cprt = self.info['tags']['cprt'] self.info['cprt'] = self.readfield(file,cprt[1],cprt[0]) desc = self.info['tags']['desc'] self.info['desc'] = self.readfield(file,desc[1],desc[0]) except KeyError: raise BadICCprofile, "That file misses one mandatory tag" | def __init__(self,uri): if os.path.getsize(uri) < 128: raise BadICCprofile, "That file doesn't seem to be an ICC color profile" else: file = open(uri,'rb') self.uri = uri file.seek(0) size,cmm = struct.unpack('>L 4s',file.read(8)) # Profile size if os.path.getsize(uri) != size: raise BadICCprofile, "That file doesn't have the expected size" if not (all(c in string.ascii_letters+' '+string.digits for c in cmm) or cmm == '\x00\x00\x00\x00'): raise BadICCprofile, "That file doesn't seem to be an ICC color profile" else: file.seek(8) version = struct.unpack('>B 1s 2s',file.read(4)) # Profile version number version1 = version[1].encode('hex') self.info = {} self.info['version'] = (version[0],eval('0x'+version1[0]),eval('0x'+version1[1])) self.info['class'] = struct.unpack('4s',file.read(4))[0] # Profile/Device Class self.info['space'] = struct.unpack('4s',file.read(4))[0] # Color space of data self.info['pcs'] = struct.unpack('4s',file.read(4))[0] # Profile Connection Space file.seek(128) tags = struct.unpack('>L',file.read(4))[0] self.info['tags'] = {} for i in range(tags): tag = struct.unpack('>4s 2L',file.read(12)) self.info['tags'][tag[0]] = (tag[1],tag[2]) |
sbz.sitem.extra[xmlunescape(elem.attrib['type'])] = xmlunescape(elem.text) | sitem.extra[xmlunescape(elem.attrib['type'])] = xmlunescape(elem.text) | def readmaterial(material,swatchbook): if material.tag == 'color': sitem = Color(swatchbook) if 'usage' in material.attrib: sitem.usage = material.attrib['usage'].split(',') for elem in material: if elem.tag == 'values': values = map(eval,elem.text.split()) if 'space' in elem.attrib: sitem.values[(elem.attrib['model'],unicode(elem.attrib['space']))] = values else: sitem.values[(elem.attrib['model'],False)] = values elif elem.tag == 'metadata': sbz.readmeta(sitem,elem) elif elem.tag == 'extra': sbz.sitem.extra[xmlunescape(elem.attrib['type'])] = xmlunescape(elem.text) if sitem.info.identifier > '': id = sitem.info.identifier else: raise FileFormatError swatchbook.materials[id] = sitem |
version='0.7', | version='0.7.1', | def run(self): for lang in os.listdir('build/locale/'): lang_dir = os.path.join('share', 'locale', lang, 'LC_MESSAGES') lang_file = os.path.join('build', 'locale', lang, 'LC_MESSAGES', 'swatchbooker.mo') self.data_files.append( (lang_dir, [lang_file]) ) _install_data.run(self) |
scripts=['data/swatchbooker', 'data/sbconvertor','data/sbconvert'], | def run(self): for lang in os.listdir('build/locale/'): lang_dir = os.path.join('share', 'locale', lang, 'LC_MESSAGES') lang_file = os.path.join('build', 'locale', lang, 'LC_MESSAGES', 'swatchbooker.mo') self.data_files.append( (lang_dir, [lang_file]) ) _install_data.run(self) |
|
('lib/swatchbooker', ['src/swatchbooker.pyw', 'src/sbconvertor.pyw','src/sbconvert.py'])], | ('lib/swatchbooker', ['src/swatchbooker.pyw', 'src/sbconvertor.pyw','src/sbconvert.py','src/sbcommon.py']), ('bin',['data/swatchbooker', 'data/sbconvertor','data/sbconvert'])], | def run(self): for lang in os.listdir('build/locale/'): lang_dir = os.path.join('share', 'locale', lang, 'LC_MESSAGES') lang_file = os.path.join('build', 'locale', lang, 'LC_MESSAGES', 'swatchbooker.mo') self.data_files.append( (lang_dir, [lang_file]) ) _install_data.run(self) |
elif elem.tag == '{'+dcterms+'}license': item.info.license = xmlunescape(elem.attrib['{'+rdf+'}resource']) | def readmeta(item,meta): for elem in meta: if elem.tag.find(dc): if elem.tag == '{'+dc+'}date': try: item.info.date = datetime.strptime(elem.text,"%Y-%m-%dT%H:%M:%S.%f") except ValueError, e: if str(e) == "'f' is a bad directive in format '%Y-%m-%dT%H:%M:%S.%f'": # Python 2.5 item.info.date = datetime.strptime(elem.text.split('.')[0],"%Y-%m-%dT%H:%M:%S") else: remain = str(e)[26:] if remain == 'Z': item.info.date = datetime.strptime(elem.text[:-len(remain)],"%Y-%m-%dT%H:%M:%S.%f") else: date = datetime.strptime(elem.text[:-len(remain)],"%Y-%m-%dT%H:%M:%S.%f") delta = remain.split(':') item.info.date = date - timedelta(hours=int(delta[0]),minutes=int(delta[1])) elif elem.tag == '{'+dc+'}type': if elem.attrib['{'+rdf+'}resource'] != 'http://purl.org/dc/dcmitype/Dataset': raise FileFormatError elif elem.tag == '{'+dc+'}format': if elem.text != 'application/swatchbook': raise FileFormatError elif '{'+xml+'}lang' in elem.attrib: exec("item.info."+elem.tag[(len(dc)+2):]+"_l10n[elem.attrib['{'+xml+'}lang']] = xmlunescape(elem.text)") else: exec("item.info."+elem.tag[(len(dc)+2):]+" = xmlunescape(elem.text)") elif elem.tag == '{'+dcterms+'}license': item.info.license = xmlunescape(elem.attrib['{'+rdf+'}resource']) |
|
posX = rootNode.size.x-50 posY = rootNode.size.y-50 | posX = rootNode.size.x * 3/4 posY = rootNode.size.y-40 | def __init__(self): rootNode = Player.getRootNode() posX = rootNode.size.x-50 posY = rootNode.size.y-50 self.__layer = Player.createNode(''' <words id="displayEmu" x="%(posX)i" y="%(posY)i" fontsize="20" opacity="1" alignment="right" color="DDDDDD" text="Multitouch emulation active" sensitive="False" /> ''' % {'posX':posX, 'posY':posY} ) rootNode.appendChild(self.__layer) self.__container = Player.createNode('div', {}) self.__p1 = Player.createNode('circle', {'r': 10, 'fillcolor':'ff0000', 'fillopacity':0, 'opacity':0, 'sensitive':False}) self.__p2 = Player.createNode('circle', {'r': 10, 'fillcolor':'ff0000', 'fillopacity':0, 'opacity':0, 'sensitive':False}) |
<words id="displayEmu" x="%(posX)i" y="%(posY)i" fontsize="20" opacity="1" alignment="right" | <words id="displayEmu" x="%(posX)i" y="%(posY)i" fontsize="20" opacity="1" | def __init__(self): rootNode = Player.getRootNode() posX = rootNode.size.x-50 posY = rootNode.size.y-50 self.__layer = Player.createNode(''' <words id="displayEmu" x="%(posX)i" y="%(posY)i" fontsize="20" opacity="1" alignment="right" color="DDDDDD" text="Multitouch emulation active" sensitive="False" /> ''' % {'posX':posX, 'posY':posY} ) rootNode.appendChild(self.__layer) self.__container = Player.createNode('div', {}) self.__p1 = Player.createNode('circle', {'r': 10, 'fillcolor':'ff0000', 'fillopacity':0, 'opacity':0, 'sensitive':False}) self.__p2 = Player.createNode('circle', {'r': 10, 'fillcolor':'ff0000', 'fillopacity':0, 'opacity':0, 'sensitive':False}) |
if self.pos1 != (-1,-1) and self.pos2 != (-1,-1): Player.getTestHelper().fakeTouchEvent(self.__getLeftID(), avg.CURSORUP, self.EventMode, self.pos1, self.pos1, Point2D(0,0)) Player.getTestHelper().fakeTouchEvent(self.__getRightID(), avg.CURSORUP, self.EventMode, self.pos2, self.pos2, Point2D(0,0)) | Player.getTestHelper().fakeTouchEvent(self.__getLeftID(), avg.CURSORUP, self.EventMode, self.pos1, self.pos1, Point2D(0,0)) Player.getTestHelper().fakeTouchEvent(self.__getRightID(), avg.CURSORUP, self.EventMode, self.pos2, self.pos2, Point2D(0,0)) | def delete(self): """ after turning off the emulater the function unlinks all nodes of the emulator. so it be garanted that the application is working as before again. events will be cleared with two UP events. """ rootNode = Player.getRootNode() rootNode.setEventHandler(avg.CURSORMOTION, avg.MOUSE, None) rootNode.setEventHandler(avg.CURSORDOWN, avg.MOUSE, None) rootNode.setEventHandler(avg.CURSORUP, avg.MOUSE, None) self.__layer.unlink() self.__container.unlink() self.__p1.unlink() self.__p2.unlink() self.__p1 = self.__p2 = None self.__container = self.__node2root = self.__layer = None if self.pos1 != (-1,-1) and self.pos2 != (-1,-1): Player.getTestHelper().fakeTouchEvent(self.__getLeftID(), avg.CURSORUP, self.EventMode, self.pos1, self.pos1, Point2D(0,0)) Player.getTestHelper().fakeTouchEvent(self.__getRightID(), avg.CURSORUP, self.EventMode, self.pos2, self.pos2, Point2D(0,0)) |
def __clampPos(self, pos): if pos[0] < 0: pos[0] = 0 if pos[1] < 0: pos[1] = 0 if pos[0] > Player.getRootNode().size[0]-1: pos[0] = Player.getRootNode().size[0]-1 if pos[1] > Player.getRootNode().size[1]-1: pos[1] = Player.getRootNode().size[0]-1 return pos | def __getRightID(self): self.idpos2 = int(self.ID.y) return self.idpos2 |
|
self.pos1 = (-1,-1) self.mouseDown1 = (-1,-1) if self.multiActive: | if self.multiActive: self.pos2 = self.__clampPos(self.pos2) | def __onMouseButtonUp(self, e): #one or two fake UP events will be created (multitouch active or not). #SOURCE depending on EventMode. self.__eraseDraw() if e.button == 1: self.mouseState = 'Up' Player.getTestHelper().fakeTouchEvent(self.__getLeftID(), avg.CURSORUP, self.EventMode, self.pos1, self.pos1, e.speed) self.pos1 = (-1,-1) self.mouseDown1 = (-1,-1) |
self.pos2 = (-1,-1) self.mouseDown2 = (-1,-1) | def __onMouseButtonUp(self, e): #one or two fake UP events will be created (multitouch active or not). #SOURCE depending on EventMode. self.__eraseDraw() if e.button == 1: self.mouseState = 'Up' Player.getTestHelper().fakeTouchEvent(self.__getLeftID(), avg.CURSORUP, self.EventMode, self.pos1, self.pos1, e.speed) self.pos1 = (-1,-1) self.mouseDown1 = (-1,-1) |
|
self.start(None, (startAnim, | self.start(None, (startFireForgetAnim, lambda: self.assert_(avg.getNumRunningAnims() == 2), None, startAnim, | def deleteAnim(): self.anim = None |
startAnim, deleteAnim, lambda: self.assert_(avg.getNumRunningAnims() == 0), | startAnim | def deleteAnim(): self.anim = None |
lambda: self.assert_(self.mouseDownCalled and self.mainMouseDownCalled), | def noCaptureEvent(): self.mouseDownCalled = False self.mainMouseDownCalled = False self.img.releaseEventCapture() |
|
not(self.divMouseOverCalled) and | self.divMouseOverCalled and | def killNodeUnderCursor(): Parent = img1.getParent() Parent.removeChild(Parent.indexOf(img1)) |
not(self.divMouseOutCalled) and | self.divMouseOutCalled and | def killNodeUnderCursor(): Parent = img1.getParent() Parent.removeChild(Parent.indexOf(img1)) |
return self.__hasBitState(Button.STATE_DOWN) | return bool(self.__hasBitState(Button.STATE_DOWN)) | def isChecked(self): return self.__hasBitState(Button.STATE_DOWN) |
self.__customClickHandler(event) | def __releaseHandlerTemplateMethod(self, event): numberOfCapturedCursors = self.__getNumberOfCapturedCursors() numberOfOverCursors = len(self.__overCursorIds) if self.__isCursorCaptured(event.cursorid): self.__releaseCapturedCursor(event.cursorid) |
|
def testVideoEOFWhithZeroOpacity(self): def onEOF(): Player.stop() def onNoEOF(): self.assert_(False) self.loadEmptyScene() videoNode = libavg.VideoNode(href = "../video/testfiles/mpeg1-48x48.mpg") videoNode.opacity = 0 Player.get().getRootNode().appendChild(videoNode) videoNode.play() videoNode.setEOFCallback(onEOF) Player.setTimeout(10000, onNoEOF) Player.play() | def onNoEOF(): self.assert_(False) |
|
self.assertException(Player.screenshot()) | self.assertException(Player.screenshot) | def checkCanvasScreenshot(): bmp = offscreenCanvas.screenshot() self.compareBitmapToFile(bmp, "testOffscreenScreenshot", False) |
avg.RectNode(parent=root, pos=(48,0), size=(32, 128), fillopacity=1, fillcolor="808080") | avg.RectNode(parent=root, pos=(48,0), size=(32, 120), strokewidth=2, fillopacity=1, fillcolor="808080") | def createBaseCanvas(): return Player.loadCanvasString(""" <canvas id="testcanvas" width="64" height="64"> <image x="0" y="0" href="rgb24alpha-64x64.png"/> </canvas> """) |
sys.path += ['..'] | sys.path.insert(0, '..') | def setSymlink(src, dest): if not os.path.exists(dest): os.symlink(src, dest) elif not os.path.islink(dest): raise RuntimeError( '%s exists as a file/directory. Please remove it to perform tests' % dest) |
<canvas id="testcanvas" width="160" height="120"> <image href="freidrehen.jpg"/> <image id="blend" x="0" y="0" opacity="0.6" href="rgb24-65x65.png"/> <image x="0" y="48" opacity="0.6" href="rgb24-65x65.png" blendmode="add"/> <image x="48" y="0" opacity="1" href="rgb24-65x65.png" blendmode="min"/> <image x="48" y="48" opacity="1" href="rgb24-65x65.png" blendmode="max"/> | <canvas id="testcanvas" width="64" height="64"> <image x="0" y="0" href="rgb24alpha-64x64.png"/> | def createBaseCanvas(): return Player.loadCanvasString(""" <canvas id="testcanvas" width="160" height="120"> <image href="freidrehen.jpg"/> <image id="blend" x="0" y="0" opacity="0.6" href="rgb24-65x65.png"/> <image x="0" y="48" opacity="0.6" href="rgb24-65x65.png" blendmode="add"/> <image x="48" y="0" opacity="1" href="rgb24-65x65.png" blendmode="min"/> <image x="48" y="48" opacity="1" href="rgb24-65x65.png" blendmode="max"/> </canvas> """) |
avg.ImageNode(parent=Player.getRootNode(), href="freidrehen.jpg") | def createBaseCanvas(): return Player.loadCanvasString(""" <canvas id="testcanvas" width="160" height="120"> <image href="freidrehen.jpg"/> <image id="blend" x="0" y="0" opacity="0.6" href="rgb24-65x65.png"/> <image x="0" y="48" opacity="0.6" href="rgb24-65x65.png" blendmode="add"/> <image x="48" y="0" opacity="1" href="rgb24-65x65.png" blendmode="min"/> <image x="48" y="48" opacity="1" href="rgb24-65x65.png" blendmode="max"/> </canvas> """) |
|
node = avg.ImageNode(parent=Player.getRootNode(), href="canvas:testcanvas") | root = Player.getRootNode() avg.RectNode(parent=root, pos=(48,0), size=(32, 128), fillopacity=1, fillcolor="808080") avg.ImageNode(parent=root, href="canvas:testcanvas") avg.ImageNode(parent=root, pos=(0,64), href="canvas:testcanvas", opacity=0.6) avg.ImageNode(parent=root, pos=(64,0), href="canvas:testcanvas", blendmode="add") avg.ImageNode(parent=root, pos=(64,64), href="canvas:testcanvas", opacity=0.6, blendmode="add") | def createBaseCanvas(): return Player.loadCanvasString(""" <canvas id="testcanvas" width="160" height="120"> <image href="freidrehen.jpg"/> <image id="blend" x="0" y="0" opacity="0.6" href="rgb24-65x65.png"/> <image x="0" y="48" opacity="0.6" href="rgb24-65x65.png" blendmode="add"/> <image x="48" y="0" opacity="1" href="rgb24-65x65.png" blendmode="min"/> <image x="48" y="48" opacity="1" href="rgb24-65x65.png" blendmode="max"/> </canvas> """) |
for id, touchVis in self.__touchViss: | for id, touchVis in self.__touchViss.items(): | def __switchShowMTEvents(self): self.__showMTEvents = not(self.__showMTEvents) if self.__showMTEvents: self.__oldEventHook = g_player.getEventHook() g_player.setEventHook(self.__showMTEventHook) else: g_player.setEventHook(self.__oldEventHook) for id, touchVis in self.__touchViss: touchVis.unlink(True) self.__touchViss = {} |
if isinstance(event, avg.TouchEvent) and event.source == avg.TOUCH: | if (isinstance(event, avg.TouchEvent) and event.source == avg.TOUCH and (event.type == avg.CURSORDOWN or event.type == avg.CURSORMOTION or event.type == avg.CURSORUP)): try: touchVis = self.__touchViss[event.cursorid] except KeyError: touchVis = TouchVisualization(event, parent=self.__touchVisOverlay) self.__touchViss[event.cursorid] = touchVis | def __showMTEventHook(self, event): if isinstance(event, avg.TouchEvent) and event.source == avg.TOUCH: if event.type == avg.CURSORDOWN: self.__touchViss[event.cursorid] = TouchVisualization(event, parent=self.__touchVisOverlay) elif event.type == avg.CURSORMOTION: self.__touchViss[event.cursorid].move(event) elif event.type == avg.CURSORUP: self.__touchViss[event.cursorid].unlink(True) del self.__touchViss[event.cursorid] if self.__oldEventHook: return self.__oldEventHook() else: return False |
self.__touchViss[event.cursorid] = TouchVisualization(event, parent=self.__touchVisOverlay) | pass | def __showMTEventHook(self, event): if isinstance(event, avg.TouchEvent) and event.source == avg.TOUCH: if event.type == avg.CURSORDOWN: self.__touchViss[event.cursorid] = TouchVisualization(event, parent=self.__touchVisOverlay) elif event.type == avg.CURSORMOTION: self.__touchViss[event.cursorid].move(event) elif event.type == avg.CURSORUP: self.__touchViss[event.cursorid].unlink(True) del self.__touchViss[event.cursorid] if self.__oldEventHook: return self.__oldEventHook() else: return False |
self.__touchViss[event.cursorid].move(event) | touchVis.move(event) | def __showMTEventHook(self, event): if isinstance(event, avg.TouchEvent) and event.source == avg.TOUCH: if event.type == avg.CURSORDOWN: self.__touchViss[event.cursorid] = TouchVisualization(event, parent=self.__touchVisOverlay) elif event.type == avg.CURSORMOTION: self.__touchViss[event.cursorid].move(event) elif event.type == avg.CURSORUP: self.__touchViss[event.cursorid].unlink(True) del self.__touchViss[event.cursorid] if self.__oldEventHook: return self.__oldEventHook() else: return False |
self.__touchViss[event.cursorid].unlink(True) | touchVis.unlink(True) | def __showMTEventHook(self, event): if isinstance(event, avg.TouchEvent) and event.source == avg.TOUCH: if event.type == avg.CURSORDOWN: self.__touchViss[event.cursorid] = TouchVisualization(event, parent=self.__touchVisOverlay) elif event.type == avg.CURSORMOTION: self.__touchViss[event.cursorid].move(event) elif event.type == avg.CURSORUP: self.__touchViss[event.cursorid].unlink(True) del self.__touchViss[event.cursorid] if self.__oldEventHook: return self.__oldEventHook() else: return False |
node.text=u"blindtext1\u00A0blindtext2\u00Ablindtext3 "+ "blindtext4\u00A0lindtext\u00A0blindtext\u00A0" | node.text=(u"blindtext1\u00A0blindtext2\u00Ablindtext3 "+ u"blindtext4\u00A0blindtext\u00A0blindtext\u00A0") | def setNBSP(): node = Player.getElementByID("dynamictext") node.width=100 node.text=u"blindtext1\u00A0blindtext2\u00Ablindtext3 "+ "blindtext4\u00A0lindtext\u00A0blindtext\u00A0" |
) ) | )) def testChangeParentError(self): def changeParent(): div = avg.DivNode() img = avg.ImageNode(href="additive/rgb24-64x64.png", parent=div) Player.getRootNode().appendChild(img) self.loadEmptyScene() self.assertException(changeParent) self.start(None, (self.assertException(changeParent), )) | def testDuplicateID(self): self.loadEmptyScene() root = Player.getRootNode() avg.ImageNode(href="rgb24-64x64.png", id="testdup", parent=root) self.assertException(lambda: avg.ImageNode(href="rgb24-64x64.png", id="testdup", parent=root)) self.start(None, (self.assertException(lambda: avg.ImageNode(href="rgb24-64x64.png", id="testdup", parent=root)), ) ) |
node = avg.VideoNode(href="../video/testfiles/mpeg1-48x48.mpg") | node = avg.VideoNode(href="../video/testfiles/mpeg1-48x48.mpg", threaded=False) | def testPlayBeforeConnect(self): node = avg.VideoNode(href="../video/testfiles/mpeg1-48x48.mpg") node.play() self._loadEmpty() Player.getRootNode().insertChild(node, 0) Player.setFakeFPS(25) self.start(None, (lambda: self.assert_(node.size == (48, 48)), lambda: self.compareImage("testPlayBeforeConnect", False), )) |
not(self.__mainDownCalled)), | self.__mainDownCalled), | def setPos(): self.node.pos = (80, 60) self.node.size = (80, 60) |
def __createOffscreenCanvas(): | def createOffscreenCanvas(): | def __createOffscreenCanvas(): offscreenCanvas = self.__createOffscreenCanvas("offscreencanvas", False) self.node = avg.ImageNode(parent=Player.getRootNode(), href="canvas:offscreencanvas") |
__createOffscreenCanvas, | createOffscreenCanvas, | def __createOffscreenCanvas(): offscreenCanvas = self.__createOffscreenCanvas("offscreencanvas", False) self.node = avg.ImageNode(parent=Player.getRootNode(), href="canvas:offscreencanvas") |
g_Player.clearTimeout(self.__inertiaHandlerID) | g_Player.clearInterval(self.__inertiaHandlerID) | def __onDown(self, event): if self.__dragCursorID == None: if self.__inertiaHandlerID: self.__stopHandler() g_Player.clearTimeout(self.__inertiaHandlerID) self.__dragCursorID = event.cursorid self.__dragStartPos = event.pos self.__node.setEventCapture(event.cursorid) if self.__startHandler: self.__startHandler(event) self.__speed = avg.Point2D(0,0) self.__frameHandlerID = g_Player.setOnFrameHandler(self.__onFrame) |
self.__node.x = self.__startDragPos[0]+event.x-event.lastdownpos[0] self.__node.y = self.__startDragPos[1]+event.y-event.lastdownpos[1] | self.__node.pos = (self.__startDragPos[0]+event.x-event.lastdownpos[0],self.__startDragPos[1]+event.y-event.lastdownpos[1]) | def __onMove(self, event): if event.cursorid == self.__cursorID: self.__node.x = self.__startDragPos[0]+event.x-event.lastdownpos[0] self.__node.y = self.__startDragPos[1]+event.y-event.lastdownpos[1] stopBubble = False if self.__onDragMove: stopBubble = self.__onDragMove(event) if stopBubble == None: stopBubble = False return stopBubble |
relTime = g_Player.getFrameTime() - self.__startTime | relTime = g_Player.getFrameTime() - self.__startTime - self.__holdDelay | def __onFrame(self): relTime = g_Player.getFrameTime() - self.__startTime if self.__state == HoldProcessor.DOWN: if relTime > self.__holdDelay: self.__changeState(HoldProcessor.HOLDING) if self.__state == HoldProcessor.HOLDING: if relTime > self.__activateDelay: self.__changeState(HoldProcessor.ACTIVE) else: self.__holdHandler(float(relTime)/self.__activateDelay) |
self.__holdHandler(float(relTime)/self.__activateDelay) | self.__holdHandler(float(relTime)/(self.__activateDelay-self.__holdDelay)) | def __onFrame(self): relTime = g_Player.getFrameTime() - self.__startTime if self.__state == HoldProcessor.DOWN: if relTime > self.__holdDelay: self.__changeState(HoldProcessor.HOLDING) if self.__state == HoldProcessor.HOLDING: if relTime > self.__activateDelay: self.__changeState(HoldProcessor.ACTIVE) else: self.__holdHandler(float(relTime)/self.__activateDelay) |
ratio = (self.__val/(self.__max-self.__min)) | ratio = ((self.__val-self.__min)/(self.__max-self.__min)) | def __positionSlider(self): if self.__val < self.__min: self.__val = self.__min elif self.__val > self.__max: self.__val = self.__max ratio = (self.__val/(self.__max-self.__min)) self.__slider.pos = (ratio*(self.size.x-14), 0) self.__onChange() |
print "Usage: videoplayer.py <filename>" | print "Usage: avg_videoplayer.py <filename>" | def __makeAlphaBackground(self): global node SQUARESIZE=40 size = node.getMediaSize() avg.RectNode(parent=self._parentNode, size=node.getMediaSize(), strokewidth=0, fillcolor="FFFFFF", fillopacity=1) for y in xrange(0, int(size.y)/SQUARESIZE): for x in xrange(0, int(size.x)/(SQUARESIZE*2)): pos = avg.Point2D(x*SQUARESIZE*2, y*SQUARESIZE) if y%2==1: pos += (SQUARESIZE, 0) avg.RectNode(parent=self._parentNode, pos=pos, size=(SQUARESIZE, SQUARESIZE), strokewidth=0, fillcolor="C0C0C0", fillopacity=1) |
self.start(None, (lambda: videoNode.play(), | videoNode.play() seek(26) self.start(None, (lambda: self.compareImage("testVideoSeek0", False), | def seek(frame): videoNode.seekToFrame(frame) |
return True | return False | def onKeyDown(self, event): global node curTime = node.getCurTime() if event.keystring == "right": node.seekToTime(curTime+10000) elif event.keystring == "left": if curTime > 10000: node.seekToTime(curTime-10000) else: node.seekToTime(0) return True |
self.loadEmptyScene() root = Player.getRootNode() node = avg.ImageNode(parent=root, href="rgb24-64x64.png") effect = avg.BlurFXNode() node.setEffect(effect) | def removeFX(): self.node.setEffect(None) def reAddFX(): self.node.setEffect(self.effect) def addNewFX(): effect = avg.BlurFXNode() effect.setParam(8) self.node.setEffect(effect) self.loadEmptyScene() root = Player.getRootNode() self.node = avg.ImageNode(parent=root, href="rgb24-64x64.png") self.effect = avg.BlurFXNode() self.node.setEffect(self.effect) | def testBlurFX(self): self.loadEmptyScene() root = Player.getRootNode() node = avg.ImageNode(parent=root, href="rgb24-64x64.png") effect = avg.BlurFXNode() node.setEffect(effect) self.start(None, (lambda: self.compareImage("testBlurFX1", False), lambda: effect.setParam(8), lambda: self.compareImage("testBlurFX2", False), )) |
lambda: effect.setParam(8), | lambda: self.effect.setParam(8), lambda: self.compareImage("testBlurFX2", False), removeFX, lambda: self.compareImage("testBlurFX3", False), reAddFX, lambda: self.compareImage("testBlurFX2", False), removeFX, addNewFX, | def testBlurFX(self): self.loadEmptyScene() root = Player.getRootNode() node = avg.ImageNode(parent=root, href="rgb24-64x64.png") effect = avg.BlurFXNode() node.setEffect(effect) self.start(None, (lambda: self.compareImage("testBlurFX1", False), lambda: effect.setParam(8), lambda: self.compareImage("testBlurFX2", False), )) |
posX = rootNode.size.x * 3/4 posY = rootNode.size.y-40 | posX = rootNode.size.x-50 posY = rootNode.size.y-50 | def __init__(self): rootNode = Player.getRootNode() posX = rootNode.size.x * 3/4 posY = rootNode.size.y-40 self.__layer = Player.createNode(''' <words id="displayEmu" x="%(posX)i" y="%(posY)i" fontsize="20" opacity="1" color="DDDDDD" text="Multitouch emulation active" sensitive="False" /> ''' % {'posX':posX, 'posY':posY} ) rootNode.appendChild(self.__layer) self.__container = Player.createNode('div', {}) self.__p1 = Player.createNode('circle', {'r': 10, 'fillcolor':'ff0000', 'fillopacity':0, 'opacity':0, 'sensitive':False}) self.__p2 = Player.createNode('circle', {'r': 10, 'fillcolor':'ff0000', 'fillopacity':0, 'opacity':0, 'sensitive':False}) |
<words id="displayEmu" x="%(posX)i" y="%(posY)i" fontsize="20" opacity="1" | <words id="displayEmu" x="%(posX)i" y="%(posY)i" fontsize="20" opacity="1" alignment="right" | def __init__(self): rootNode = Player.getRootNode() posX = rootNode.size.x * 3/4 posY = rootNode.size.y-40 self.__layer = Player.createNode(''' <words id="displayEmu" x="%(posX)i" y="%(posY)i" fontsize="20" opacity="1" color="DDDDDD" text="Multitouch emulation active" sensitive="False" /> ''' % {'posX':posX, 'posY':posY} ) rootNode.appendChild(self.__layer) self.__container = Player.createNode('div', {}) self.__p1 = Player.createNode('circle', {'r': 10, 'fillcolor':'ff0000', 'fillopacity':0, 'opacity':0, 'sensitive':False}) self.__p2 = Player.createNode('circle', {'r': 10, 'fillcolor':'ff0000', 'fillopacity':0, 'opacity':0, 'sensitive':False}) |
self._getValue = getValue self._values = [] self._xSkip = 2 self._lastCurUsage = 0 self._maxFrameTime = 0 | self._getValue = getValue self._xSkip = 2 | def __init__(self, graph,getValue): self._getValue = getValue |
self._usage = [0] self._maxUsage = [0] self._minutesUsage = [0] self._minutesMaxUsage = [0] | def __init__(self, graph,getValue): self._getValue = getValue |
|
self._sampleNum = 0 | def __init__(self, graph,getValue): self._getValue = getValue |
|
self._memSampleNum = 0 self._usage = [0] self._maxUsage = [0] self._minutesUsage = [0] self._minutesMaxUsage = [0] | def _setup(self): self._interval = g_player.setInterval(1000, self._nextMemSample) |
|
+time.strftime("%H:%M:%S", time.localtime(lastMaxChangeTime))) | +time.strftime("%d.%m.%Y %H:%M:%S", time.localtime(lastMaxChangeTime))) | def _nextMemSample(self): curUsage = self._getValue() self._usage.append(curUsage) maxUsage = self._maxUsage[-1] if curUsage>maxUsage: maxUsage = curUsage lastMaxChangeTime = time.time() self._textNode1.text = ("Last increase in maximum: " +time.strftime("%H:%M:%S", time.localtime(lastMaxChangeTime))) self._maxUsage.append(maxUsage) self._sampleNum += 1 if self._sampleNum % 60 == 0: lastMinuteAverage = sum(self._usage[-60:])/60 self._minutesUsage.append(lastMinuteAverage) self._minutesMaxUsage.append(maxUsage) |
self._sampleNum += 1 if self._sampleNum % 60 == 0: | self._memSampleNum += 1 if self._memSampleNum % 60 == 0: | def _nextMemSample(self): curUsage = self._getValue() self._usage.append(curUsage) maxUsage = self._maxUsage[-1] if curUsage>maxUsage: maxUsage = curUsage lastMaxChangeTime = time.time() self._textNode1.text = ("Last increase in maximum: " +time.strftime("%H:%M:%S", time.localtime(lastMaxChangeTime))) self._maxUsage.append(maxUsage) self._sampleNum += 1 if self._sampleNum % 60 == 0: lastMinuteAverage = sum(self._usage[-60:])/60 self._minutesUsage.append(lastMinuteAverage) self._minutesMaxUsage.append(maxUsage) |
if self._sampleNum < 60*60: | if self._memSampleNum < 60*60: | def _nextMemSample(self): curUsage = self._getValue() self._usage.append(curUsage) maxUsage = self._maxUsage[-1] if curUsage>maxUsage: maxUsage = curUsage lastMaxChangeTime = time.time() self._textNode1.text = ("Last increase in maximum: " +time.strftime("%H:%M:%S", time.localtime(lastMaxChangeTime))) self._maxUsage.append(maxUsage) self._sampleNum += 1 if self._sampleNum % 60 == 0: lastMinuteAverage = sum(self._usage[-60:])/60 self._minutesUsage.append(lastMinuteAverage) self._minutesMaxUsage.append(maxUsage) |
Subsets and Splits