first 2to3 pass + manual fix for metaclass, UserDict and OrderedDict

This commit is contained in:
Mathieu Virbel 2012-12-28 16:11:20 +01:00 committed by Dusty Phillips
parent f492baa714
commit bae94bc3db
131 changed files with 757 additions and 837 deletions

View File

@ -52,7 +52,7 @@ import kivy.interactive
from kivy.factory import Factory
# force loading of all classes from factory
for x in Factory.classes.keys()[:]:
for x in list(Factory.classes.keys())[:]:
getattr(Factory, x)
@ -65,7 +65,7 @@ def writefile(filename, data):
global dest_dir
# avoid to rewrite the file if the content didn't change
f = os.path.join(dest_dir, filename)
print 'write', filename
print('write', filename)
if os.path.exists(f):
with open(f) as fd:
if fd.read() == data:
@ -176,7 +176,7 @@ for package in packages:
t += " api-%s.rst\n" % subpackage
# search modules
m = modules.keys()
m = list(modules.keys())
m.sort(key=lambda x: extract_summary_line(sys.modules[x].__doc__))
for module in m:
packagemodule = module.rsplit('.', 1)[0]
@ -188,7 +188,7 @@ for package in packages:
# Create index for all module
m = modules.keys()
m = list(modules.keys())
m.sort()
refid = 0
for module in m:
@ -233,4 +233,4 @@ for module in m:
# Generation finished
print 'Generation finished, do make html'
print('Generation finished, do make html')

View File

@ -51,7 +51,7 @@ copyright = '2010, The Kivy Authors'
#
os.environ['KIVY_DOC_INCLUDE'] = '1'
import kivy
print kivy.__file__
print(kivy.__file__)
version = kivy.__version__
release = kivy.__version__

View File

@ -17,13 +17,13 @@ class KivyClassDocumenter(ClassDocumenter):
# add inheritance info, if wanted
if not self.doc_as_attr and self.options.show_inheritance:
self.add_line(u'', '<autodoc>')
self.add_line('', '<autodoc>')
if len(self.object.__bases__):
bases = [b.__module__ == '__builtin__' and
u':class:`%s`' % b.__name__ or
u':class:`%s.%s`' % (fix(b.__module__), b.__name__)
':class:`%s`' % b.__name__ or
':class:`%s.%s`' % (fix(b.__module__), b.__name__)
for b in self.object.__bases__]
self.add_line(_(u' Bases: %s') % ', '.join(bases),
self.add_line(_(' Bases: %s') % ', '.join(bases),
'<autodoc>')
def setup(app):
core_setup(app)

View File

@ -36,7 +36,7 @@ def LoggerDisplayMetrics(metrics):
'widthPixels':metrics.widthPixels,
'xdpi':metrics.xdpi,
'ydpi':metrics.ydpi}
for (k,v) in display.items():
for (k,v) in list(display.items()):
Logger.info('COMPASS: display %s = %s'%(k,v))
class CompassWidget(FloatLayout):

View File

@ -50,7 +50,7 @@ class BezierTest(FloatLayout):
def on_touch_down(self, touch):
if self.collide_point(touch.pos[0], touch.pos[1]):
for i, p in enumerate(zip(self.points[::2], self.points[1::2])):
for i, p in enumerate(list(zip(self.points[::2], self.points[1::2]))):
if (
abs(touch.pos[0] - self.pos[0] - p[0]) < self.d and
abs(touch.pos[1] - self.pos[1] - p[1]) < self.d):
@ -85,7 +85,7 @@ class Main(App):
l = 100
# Pacman !
points = [x, y]
for i in xrange(45, 360, 45):
for i in range(45, 360, 45):
i = radians(i)
points.extend([x + cos(i) * l, y + sin(i) * l])
return BezierTest(points=points, loop=True)

View File

@ -20,7 +20,7 @@ class StressCanvasApp(App):
def add_rects(self, label, wid, count, *largs):
label.text = str(int(label.text) + count)
with wid.canvas:
for x in xrange(count):
for x in range(count):
Color(r(), 1, 1, mode='hsv')
Rectangle(pos=(r() * wid.width + wid.x,
r() * wid.height + wid.y), size=(20, 20))

View File

@ -166,7 +166,7 @@ class LinePlayground(FloatLayout):
points = []
points2 = []
self.dt += dt
for i in xrange(int(w / step)):
for i in range(int(w / step)):
x = i * step
points.append(cx + x)
points.append(cy + cos(x / w * 8. + self.dt) * self.height * 0.2)

View File

@ -23,7 +23,7 @@ class MeshTestApp(App):
indices = []
step = 10
istep = (pi * 2) / float(step)
for i in xrange(step):
for i in range(step):
x = 300 + cos(istep * i) * 100
y = 300 + sin(istep * i) * 100
vertices.extend([x, y, 0, 0])

View File

@ -39,7 +39,7 @@ class StencilCanvasApp(App):
def add_rects(self, label, wid, count, *largs):
label.text = str(int(label.text) + count)
with wid.canvas:
for x in xrange(count):
for x in range(count):
Color(r(), 1, 1, mode='hsv')
Rectangle(pos=(r() * wid.width + wid.x,
r() * wid.height + wid.y), size=(10, 10))

View File

@ -25,8 +25,8 @@ class Puzzle(Camera):
return
bs = self.blocksize
tw, th = self.texture_size
for x in xrange(int(tw / bs)):
for y in xrange(int(th / bs)):
for x in range(int(tw / bs)):
for y in range(int(th / bs)):
bx = x * bs
by = y * bs
subtexture = texture.get_region(bx, by, bs, bs)
@ -44,7 +44,7 @@ class Puzzle(Camera):
bs = self.blocksize
tw, th = self.texture_size
count = int(tw / bs) * int(th / bs)
indices = range(count)
indices = list(range(count))
childindex = 0
while indices:
index = indices.pop(randint(0, len(indices) - 1))

View File

@ -63,7 +63,7 @@ class KivyRenderTextInput(CodeInput):
ctrl, cmd = 64, 1024
key, key_str = keycode
if text and not key in (self.interesting_keys.keys() + [27]):
if text and not key in (list(self.interesting_keys.keys()) + [27]):
# This allows *either* ctrl *or* cmd, but not both.
if modifiers == ['ctrl'] or (is_osx and modifiers == ['meta']):
if key == ord('s'):
@ -141,7 +141,7 @@ class Catalog(BoxLayout):
kv_container.add_widget(widget)
except (SyntaxError, ParserException) as e:
self.show_error(e)
except Exception, e:
except Exception as e:
self.show_error(e)
def show_error(self, e):

View File

@ -46,7 +46,7 @@ class PicturesApp(App):
picture = Picture(source=filename, rotation=randint(-30,30))
# add to the main field
root.add_widget(picture)
except Exception, e:
except Exception as e:
Logger.exception('Pictures: Unable to load <%s>' % filename)
def on_pause(self):

View File

@ -58,7 +58,7 @@ class ShaderViewer(FloatLayout):
s = self.canvas
s['projection_mat'] = Window.render_context['projection_mat']
s['time'] = Clock.get_boottime()
s['resolution'] = map(float, self.size)
s['resolution'] = list(map(float, self.size))
s.ask_update()
def on_fs(self, instance, value):
@ -94,14 +94,14 @@ void main (void) {
self.bind(fs=self.trigger_compile, vs=self.trigger_compile)
def compile_shaders(self, *largs):
print 'try compile'
print('try compile')
if not self.viewer:
return
fs = fs_header + self.fs
vs = vs_header + self.vs
print '-->', fs
print('-->', fs)
self.viewer.fs = fs
print '-->', vs
print('-->', vs)
self.viewer.vs = vs
class ShaderEditorApp(App):

View File

@ -184,8 +184,8 @@ class ShowcaseApp(App):
w = getattr(self, 'show_%s' %
value.text.lower().replace(' ', '_'))()
self.content.add_widget(w)
except Exception, e:
print e
except Exception as e:
print(e)
def on_pause(self):
return True
@ -279,13 +279,13 @@ class ShowcaseApp(App):
def populate_treeview(self, tv):
n = tv.add_node(TreeViewLabel(text='Item 1'))
for x in xrange(3):
for x in range(3):
tv.add_node(TreeViewLabel(text='Subitem %d' % x), n)
n = tv.add_node(TreeViewLabel(text='Item 2', is_open=True))
for x in xrange(3):
for x in range(3):
tv.add_node(TreeViewLabel(text='Subitem %d' % x), n)
n = tv.add_node(TreeViewLabel(text='Item 3'))
for x in xrange(3):
for x in range(3):
tv.add_node(TreeViewLabel(text='Subitem %d' % x), n)
return tv

View File

@ -17,7 +17,7 @@ def calculate_points(x1, y1, x2, y2, steps=5):
return None
o = []
m = dist / steps
for i in xrange(1, int(m)):
for i in range(1, int(m)):
mi = i / m
lastx = x1 + dx * mi
lasty = y1 + dy * mi
@ -58,7 +58,7 @@ class Touchtracer(FloatLayout):
if points:
try:
lp = ud['lines'][2].add_point
for idx in xrange(0, len(points), 2):
for idx in range(0, len(points), 2):
lp(points[idx], points[idx+1])
except GraphicException:
pass

View File

@ -52,7 +52,7 @@ class GestureBoard(FloatLayout):
try:
touch.ud['line'].points += [touch.x, touch.y]
return True
except (KeyError), e:
except (KeyError) as e:
pass
def on_touch_up(self, touch):
@ -60,27 +60,27 @@ class GestureBoard(FloatLayout):
# known gesture.
g = simplegesture(
'',
zip(touch.ud['line'].points[::2], touch.ud['line'].points[1::2])
list(zip(touch.ud['line'].points[::2], touch.ud['line'].points[1::2]))
)
# print the gesture representation, you can use that to add
# gestures to my_gestures.py
print "gesture representation:", self.gdb.gesture_to_str(g)
print("gesture representation:", self.gdb.gesture_to_str(g))
# print match scores between all known gestures
print "cross:", g.get_score(cross)
print "check:", g.get_score(check)
print "circle:", g.get_score(circle)
print "square:", g.get_score(square)
print("cross:", g.get_score(cross))
print("check:", g.get_score(check))
print("circle:", g.get_score(circle))
print("square:", g.get_score(square))
# use database to find the more alike gesture, if any
g2 = self.gdb.find(g, minscore=0.70)
print g2
print(g2)
if g2:
if g2[1] == circle: print "circle"
if g2[1] == square: print "square"
if g2[1] == check: print "check"
if g2[1] == cross: print "cross"
if g2[1] == circle: print("circle")
if g2[1] == square: print("square")
if g2[1] == check: print("check")
if g2[1] == cross: print("cross")
# erase the lines on the screen, this is a bit quick&dirty, since we
# can have another touch event on the way...

View File

@ -4,7 +4,7 @@ from kivy.uix.widget import Widget
class MyPaintWidget(Widget):
def on_touch_down(self, touch):
print touch
print(touch)
class MyPaintApp(App):
def build(self):

View File

@ -213,7 +213,7 @@ class KinectViewer(Widget):
# update projection mat and uvsize
self.canvas['projection_mat'] = Window.render_context['projection_mat']
self.canvas['depth_range'] = self.depth_range
self.canvas['size'] = map(float, self.size)
self.canvas['size'] = list(map(float, self.size))
try:
value = self.kinect.pop()
except:

View File

@ -7,8 +7,8 @@ from kivy.core.window import Window
class KvApp(App):
def _print_fps(self, *largs):
print 'FPS: %2.4f (real draw: %d)' % (
Clock.get_fps(), Clock.get_rfps())
print('FPS: %2.4f (real draw: %d)' % (
Clock.get_fps(), Clock.get_rfps()))
def _reload_keypress(self, instance, code, *largs):
if code != 286:
@ -28,7 +28,7 @@ if __name__ == '__main__':
import os
if len(sys.argv) < 2:
print 'Usage: %s filename.kv' % os.path.basename(sys.argv[0])
print('Usage: %s filename.kv' % os.path.basename(sys.argv[0]))
sys.exit(1)
KvApp(filename=sys.argv[1]).run()

View File

@ -77,7 +77,7 @@ class ShaderWidget(FloatLayout):
def update_glsl(self, *largs):
self.canvas['time'] = Clock.get_boottime()
self.canvas['resolution'] = map(float, self.size)
self.canvas['resolution'] = list(map(float, self.size))
# This is needed for the default vertex shader.
self.canvas['projection_mat'] = Window.render_context['projection_mat']

View File

@ -132,7 +132,7 @@ class ShaderWidget(FloatLayout):
def update_glsl(self, *largs):
self.canvas['time'] = Clock.get_boottime()
self.canvas['resolution'] = map(float, self.size)
self.canvas['resolution'] = list(map(float, self.size))
# This is needed for the default vertex shader.
self.fbo['projection_mat'] = Window.render_context['projection_mat']
self.canvas['projection_mat'] = Window.render_context['projection_mat']

View File

@ -5,7 +5,7 @@ from kivy.app import App
class AccordionApp(App):
def build(self):
root = Accordion()
for x in xrange(5):
for x in range(5):
item = AccordionItem(title='Title %d' % x)
item.add_widget(Label(text='Very big content\n' * 10))
root.add_widget(item)

View File

@ -29,7 +29,7 @@ class Page(GridLayout):
class TestApp(App):
def build(self):
root = Carousel()
for x in xrange(10):
for x in range(10):
root.add_widget(Page())
return root

View File

@ -94,7 +94,7 @@ class CodeInputTest(App):
b = BoxLayout(orientation='vertical')
languages = Spinner(
text='language',
values=sorted(['KvLexer', ] + lexers.LEXERS.keys()))
values=sorted(['KvLexer', ] + list(lexers.LEXERS.keys())))
languages.bind(text=self.change_lang)
@ -103,7 +103,7 @@ class CodeInputTest(App):
height='30pt')
fnt_size = Spinner(
text='12',
values=map(str, range(5, 40)))
values=list(map(str, list(range(5, 40)))))
fnt_size.bind(text=self._update_size)
fnt_name = Spinner(
text='DroidSansMono',

View File

@ -52,7 +52,7 @@ def point_inside_polygon(x, y, poly):
inside = False
p1x = poly[0]
p1y = poly[1]
for i in xrange(0, n + 2, 2):
for i in range(0, n + 2, 2):
p2x = poly[i % n]
p2y = poly[(i + 1) % n]
if y > min(p1y, p2y):

View File

@ -98,13 +98,13 @@ if __name__ == '__main__':
size = (s, s)
sh = (None, None)
add = root.add_widget
print 'Creating 5000 widgets...'
for i in xrange(5000):
print('Creating 5000 widgets...')
for i in range(5000):
x = (i % 40) * s
y = int(i / 40) * s
add(Button(text=str(i), pos=(x, y), size_hint=sh, size=size))
if i % 1000 == 1000 - 1:
print 5000 - i - 1, 'left...'
print(5000 - i - 1, 'left...')
return root

View File

@ -13,14 +13,14 @@ class MyKeyboardListener(Widget):
self._keyboard.bind(on_key_down=self._on_keyboard_down)
def _keyboard_closed(self):
print 'My keyboard have been closed!'
print('My keyboard have been closed!')
self._keyboard.unbind(on_key_down=self._on_keyboard_down)
self._keyboard = None
def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
print 'The key', keycode, 'have been pressed'
print ' - text is %r' % text
print ' - modifiers are %r' % modifiers
print('The key', keycode, 'have been pressed')
print(' - text is %r' % text)
print(' - modifiers are %r' % modifiers)
# Keycode is composed of an integer + a string
# If we hit escape, release the keyboard

View File

@ -2,7 +2,7 @@
# A dictionary of dicts, with only the minimum required is_selected attribute,
# for use with examples using a simple list of integers in a list view.
integers_dict = \
{ str(i): {'text': str(i), 'is_selected': False} for i in xrange(100)}
{ str(i): {'text': str(i), 'is_selected': False} for i in range(100)}
# ----------------------------------------------------------------------------
@ -152,7 +152,7 @@ fruit_data_attribute_units = ['(g)',
'(%DV)',
'(%DV)']
attributes_and_units = dict(zip(fruit_data_attributes, fruit_data_attribute_units))
attributes_and_units = dict(list(zip(fruit_data_attributes, fruit_data_attribute_units)))
fruit_data = {}
for fruit_record in fruit_data_list_of_dicts:
@ -161,4 +161,4 @@ for fruit_record in fruit_data_list_of_dicts:
dict({'name': fruit_record['name'],
'Serving Size': fruit_record['Serving Size'],
'is_selected': fruit_record['is_selected']},
**dict(zip(attributes_and_units.keys(), fruit_record['data'])))
**dict(list(zip(list(attributes_and_units.keys()), fruit_record['data']))))

View File

@ -67,7 +67,7 @@ class FruitObserverDetailView(GridLayout):
text=str(fruit_data[self.fruit_name][attribute])))
def update(self, object_adapter, *args):
print 'updating fodv', object_adapter, object_adapter.obj
print('updating fodv', object_adapter, object_adapter.obj)
if object_adapter.obj is None:
return
@ -104,7 +104,7 @@ class FruitImageDetailView(BoxLayout):
for attribute in fruit_data_attributes:
container.add_widget(Label(text="{0}:".format(attribute),
halign='right'))
print 'fruit_name', self.fruit_name
print('fruit_name', self.fruit_name)
container.add_widget(
Label(text=str(fruit_data[self.fruit_name][attribute])))
self.add_widget(container)

View File

@ -131,7 +131,7 @@ class CascadingView(GridLayout):
# instantiation of the fruit_list_adapter.
#
first_category_fruits = \
fruit_categories[fruit_categories.keys()[0]]['fruits']
fruit_categories[list(fruit_categories.keys())[0]]['fruits']
first_category_fruit_data_items = \
[f for f in fruit_data_items if f.name in first_category_fruits]

View File

@ -37,7 +37,7 @@ class MainView(GridLayout):
{'cls': ListItemButton,
'kwargs': {'text': rec['text']}}]}
item_strings = ["{0}".format(index) for index in xrange(100)]
item_strings = ["{0}".format(index) for index in range(100)]
dict_adapter = DictAdapter(sorted_keys=item_strings,
data=integers_dict,

View File

@ -48,7 +48,7 @@ class MainView(GridLayout):
# CompositeListItem kv template for the list item view. Then we
# create a list view using this adapter. args_converter above converts
# dict attributes to ctx attributes.
dict_adapter = DictAdapter(sorted_keys=[str(i) for i in xrange(100)],
dict_adapter = DictAdapter(sorted_keys=[str(i) for i in range(100)],
data=integers_dict,
args_converter=list_item_args_converter,
template='CustomListItem')

View File

@ -26,7 +26,7 @@ class OpsDictAdapter(DictAdapter):
if self.listview_id is 0:
# Scroll to the most recently selected item.
if len(self.selection) > 0:
print 'selection', self.selection
print('selection', self.selection)
self.owning_view.scroll_to(
index=self.sorted_keys.index(self.selection[-1].text))
@ -134,7 +134,7 @@ class OpsView(BoxLayout):
# On the left side of the upper panel, show the selected items. There
# is a total possible of 5 for each listview, so 5 buttons are made.
#
for listview_id in xrange(7):
for listview_id in range(7):
box_layout = BoxLayout()
listview_selection_buttons[listview_id] = []
@ -208,7 +208,7 @@ class OpsView(BoxLayout):
size_hint_y=None,
height=25)]
for listview_id in xrange(7):
for listview_id in range(7):
box_layout = BoxLayout(orientation='vertical')

View File

@ -11,7 +11,7 @@ class MainView(GridLayout):
kwargs['size_hint'] = (1.0, 1.0)
super(MainView, self).__init__(**kwargs)
list_view = ListView(item_strings=[str(index) for index in xrange(100)])
list_view = ListView(item_strings=[str(index) for index in range(100)])
self.add_widget(list_view)

View File

@ -76,7 +76,7 @@ class ScreenManagerApp(App):
def build(self):
root = ScreenManager()
for x in xrange(4):
for x in range(4):
root.add_widget(CustomScreen(name='Screen %d' % x))
return root

View File

@ -8,7 +8,7 @@ spinner = Spinner(
pos_hint={'center_x': .5, 'center_y': .5})
def show_selected_value(spinner, text):
print 'The spinner', spinner, 'have text', text
print('The spinner', spinner, 'have text', text)
spinner.bind(text=show_selected_value)

View File

@ -122,7 +122,7 @@ class LoadDialog(FloatLayout):
class Unicode_TextInput(BoxLayout):
txt_input = ObjectProperty(None)
unicode_string = StringProperty(u'''Latin-1 suppliment: éé çç ßß
unicode_string = StringProperty('''Latin-1 suppliment: éé çç ßß
List of major languages taken from Google Translate
____________________________________________________

View File

@ -42,7 +42,7 @@ from kivy.utils import platform
__kivy_post_configuration = []
if platform() == 'macosx' and sys.maxint < 9223372036854775807:
if platform() == 'macosx' and sys.maxsize < 9223372036854775807:
r = '''Unsupported Python version detected!:
Kivy requires a 64 bit version of Python to run on OS X. We strongly advise
you to use the version of Python that is provided by Apple (don't use ports,
@ -174,7 +174,7 @@ def kivy_usage():
--dpi=96
Manually overload the Window DPI (for testing only.)
'''
print kivy_usage.__doc__ % (basename(sys.argv[0]))
print(kivy_usage.__doc__ % (basename(sys.argv[0])))
# Start !
@ -266,7 +266,7 @@ if not environ.get('KIVY_DOC_INCLUDE'):
if not exists(icon_dir):
try:
shutil.copytree(join(kivy_data_dir, 'logo'), icon_dir)
except shutil.Error, e:
except shutil.Error as e:
Logger.exception('Error when copying logo directory')
# configuration
@ -291,7 +291,7 @@ if not environ.get('KIVY_DOC_INCLUDE'):
'display=', 'size=', 'rotate=', 'config=', 'debug',
'dpi='])
except GetoptError, err:
except GetoptError as err:
Logger.error('Core: %s' % str(err))
kivy_usage()
sys.exit(2)
@ -365,7 +365,7 @@ if not environ.get('KIVY_DOC_INCLUDE'):
try:
with open(kivy_config_fn, 'w') as fd:
Config.write(fd)
except Exception, e:
except Exception as e:
Logger.exception('Core: error while saving default'
'configuration file:', str(e))
Logger.info('Core: Kivy configuration saved.')

View File

@ -427,7 +427,7 @@ class ListAdapter(Adapter, EventDispatcher):
'''
if len(self.selection) > 0:
last_sel_index = max([sel.index for sel in self.selection])
print 'last_sel_index', last_sel_index
print('last_sel_index', last_sel_index)
self.data = self.data[:last_sel_index + 1]
def trim_to_sel(self, *args):

View File

@ -106,7 +106,7 @@ class Animation(EventDispatcher):
self._duration = kw.get('d', kw.get('duration', 1.))
self._transition = kw.get('t', kw.get('transition', 'linear'))
self._step = kw.get('s', kw.get('step', 1. / 60.))
if isinstance(self._transition, basestring):
if isinstance(self._transition, str):
self._transition = getattr(AnimationTransition, self._transition)
for key in ('d', 't', 's', 'step', 'duration', 'transition'):
kw.pop(key, None)
@ -250,7 +250,7 @@ class Animation(EventDispatcher):
# get current values
p = d['properties']
for key, value in self._animated_properties.iteritems():
for key, value in self._animated_properties.items():
p[key] = (getattr(widget, key), value)
# install clock
@ -272,7 +272,7 @@ class Animation(EventDispatcher):
widgets = self._widgets
transition = self._transition
calculate = self._calculate
for widget in widgets.keys()[:]:
for widget in list(widgets.keys())[:]:
anim = widgets[widget]
anim['time'] += dt
@ -281,7 +281,7 @@ class Animation(EventDispatcher):
t = transition(progress)
# apply progression on widget
for key, values in anim['properties'].iteritems():
for key, values in anim['properties'].items():
a, b = values
value = calculate(a, b, t)
setattr(widget, key, value)
@ -299,11 +299,11 @@ class Animation(EventDispatcher):
tp = list
else:
tp = tuple
return tp([_calculate(a[x], b[x], t) for x in xrange(len(a))])
return tp([_calculate(a[x], b[x], t) for x in range(len(a))])
elif isinstance(a, DictType):
d = {}
for x in a.iterkeys():
if not x in b.keys():
for x in a.keys():
if not x in list(b.keys()):
# User requested to animate only part of the dict.
# Copy the rest
d[x] = a[x]

View File

@ -176,7 +176,7 @@ class Atlas(EventDispatcher):
Logger.debug('Atlas: Need to load %d images' % len(meta))
d = dirname(filename)
textures = {}
for subfilename, ids in meta.iteritems():
for subfilename, ids in meta.items():
subfilename = join(d, subfilename)
Logger.debug('Atlas: Load <%s>' % subfilename)
@ -185,7 +185,7 @@ class Atlas(EventDispatcher):
# for all the uid, load the image, get the region, and put it in our
# dict.
for meta_id, meta_coords in ids.iteritems():
for meta_id, meta_coords in ids.items():
x, y, w, h = meta_coords
textures[meta_id] = ci.texture.get_region(*meta_coords)
@ -337,25 +337,25 @@ if __name__ == '__main__':
import sys
argv = sys.argv[1:]
if len(argv) < 3:
print 'Usage: python -m kivy.atlas <outname> <size> <img1.png>' \
'[<img2.png>, ...]'
print('Usage: python -m kivy.atlas <outname> <size> <img1.png>' \
'[<img2.png>, ...]')
sys.exit(1)
outname = argv[0]
try:
size = int(argv[1])
except ValueError:
print 'Error: size must be an integer'
print('Error: size must be an integer')
sys.exit(1)
filenames = argv[2:]
ret = Atlas.create(outname, filenames, size)
if not ret:
print 'Error while creating atlas!'
print('Error while creating atlas!')
sys.exit(1)
fn, meta = ret
print 'Atlas created at', fn
print '%d image%s have been created' % (len(meta),
's' if len(meta) > 1 else '')
print('Atlas created at', fn)
print('%d image%s have been created' % (len(meta),
's' if len(meta) > 1 else ''))

View File

@ -348,7 +348,7 @@ def _run_mainloop():
EventLoop.run()
stopTouchApp()
break
except BaseException, inst:
except BaseException as inst:
# use exception manager first
r = ExceptionManager.handle_exception(inst)
if r == ExceptionManager.RAISE:
@ -411,7 +411,7 @@ def runTouchApp(widget=None, slave=False):
EventLoop.add_input_provider(p, True)
# add postproc modules
for mod in kivy_postproc_modules.values():
for mod in list(kivy_postproc_modules.values()):
EventLoop.add_postproc_module(mod)
# add main widget

View File

@ -164,7 +164,7 @@ class Cache(object):
@staticmethod
def _purge_oldest(category, maxpurge=1):
print 'PURGE', category
print('PURGE', category)
import heapq
heap_list = []
for key in Cache._objects[category]:
@ -172,12 +172,12 @@ class Cache(object):
if obj['lastaccess'] == obj['timestamp']:
continue
heapq.heappush(heap_list, (obj['lastaccess'], key))
print '<<<', obj['lastaccess']
print('<<<', obj['lastaccess'])
n = 0
while n < maxpurge:
try:
lastaccess, key = heapq.heappop(heap_list)
print '=>', key, lastaccess, Clock.get_time()
print('=>', key, lastaccess, Clock.get_time())
except Exception:
return
del Cache._objects[category][key]
@ -200,7 +200,7 @@ class Cache(object):
Cache._categories[category]['timeout'] = timeout
continue
for key in Cache._objects[category].keys()[:]:
for key in list(Cache._objects[category].keys())[:]:
lastaccess = Cache._objects[category][key]['lastaccess']
objtimeout = Cache._objects[category][key]['timeout']
@ -218,13 +218,13 @@ class Cache(object):
@staticmethod
def print_usage():
'''Print the cache usage on the console'''
print 'Cache usage :'
print('Cache usage :')
for category in Cache._categories:
print ' * %s : %d / %s, timeout=%s' % (
print(' * %s : %d / %s, timeout=%s' % (
category.capitalize(),
len(Cache._objects[category]),
str(Cache._categories[category]['limit']),
str(Cache._categories[category]['timeout']))
str(Cache._categories[category]['timeout'])))
if 'KIVY_DOC_INCLUDE' not in environ:
# install the schedule clock for purging

View File

@ -407,19 +407,19 @@ class ClockBase(object):
# call that function to release all the direct reference to any callback
# and replace it with a weakref
events = self._events
for cid in events.keys()[:]:
for cid in list(events.keys())[:]:
[x.release() for x in events[cid] if x.callback is not None]
def _remove_empty(self):
# remove empty entry in the event list
events = self._events
for cid in events.keys()[:]:
for cid in list(events.keys())[:]:
if not events[cid]:
del events[cid]
def _process_events(self):
events = self._events
for cid in events.keys()[:]:
for cid in list(events.keys())[:]:
for event in events[cid][:]:
if event.tick(self._last_tick) is False:
# event may be already removed by the callback
@ -440,7 +440,7 @@ class ClockBase(object):
# search event that have timeout = -1
found = False
for cid in events.keys()[:]:
for cid in list(events.keys())[:]:
for event in events[cid][:]:
if event.timeout != -1:
continue

View File

@ -175,13 +175,13 @@ Available configuration tokens
__all__ = ('Config', 'ConfigParser')
from ConfigParser import ConfigParser as PythonConfigParser
from configparser import ConfigParser as PythonConfigParser
from sys import platform
from os import environ
from os.path import exists
from kivy import kivy_config_fn
from kivy.logger import Logger, logger_config_update
from kivy.utils import OrderedDict
from collections import OrderedDict
# Version number of current configuration format
KIVY_CONFIG_VERSION = 7
@ -229,7 +229,7 @@ class ConfigParser(PythonConfigParser):
Python, this one is able to read only one file at a time. The latest
read file will be used for the :meth:`write` method.
'''
if type(filename) not in (str, unicode):
if type(filename) not in (str, str):
raise Exception('Only one filename is accepted (str or unicode)')
self.filename = filename
PythonConfigParser.read(self, filename)
@ -246,7 +246,7 @@ class ConfigParser(PythonConfigParser):
'''Set a lot of keys/values in one section at the same time
'''
self.adddefaultsection(section)
for key, value in keyvalues.iteritems():
for key, value in keyvalues.items():
self.setdefault(section, key, value)
def setdefault(self, section, option, value):
@ -306,7 +306,7 @@ if not environ.get('KIVY_DOC_INCLUDE'):
'KIVY_NO_CONFIG' not in environ:
try:
Config.read(kivy_config_fn)
except Exception, e:
except Exception as e:
Logger.exception('Core: error while reading local'
'configuration')
@ -447,6 +447,6 @@ if not environ.get('KIVY_DOC_INCLUDE'):
try:
Config.filename = kivy_config_fn
Config.write()
except Exception, e:
except Exception as e:
Logger.exception('Core: Error while saving default config file')

View File

@ -22,5 +22,5 @@ class ClipboardDummy(ClipboardBase):
self._data[mimetype] = data
def get_types(self):
return self._data.keys()
return list(self._data.keys())

View File

@ -23,9 +23,9 @@ from kivy.resources import resource_find
from kivy.utils import platform
import zipfile
try:
import cStringIO as SIO
import io as SIO
except ImportError:
import StringIO as SIO
import io as SIO
# late binding
@ -65,7 +65,7 @@ class ImageData(object):
def release_data(self):
mm = self.mipmaps
for item in mm.itervalues():
for item in mm.values():
item[2] = None
@property
@ -130,7 +130,7 @@ class ImageData(object):
.. versionadded:: 1.0.7
'''
mm = self.mipmaps
for x in xrange(len(mm)):
for x in range(len(mm)):
item = mm.get(x, None)
if item is None:
raise Exception('Invalid mipmap level, found empty one')
@ -161,7 +161,7 @@ class ImageLoaderBase(object):
Logger.trace('Image: %r, populate to textures (%d)' %
(self.filename, len(self._data)))
for count in xrange(len(self._data)):
for count in range(len(self._data)):
# first, check if a texture with the same name already exist in the
# cache
@ -326,7 +326,7 @@ class ImageLoader(object):
atlas = Atlas(afn)
Cache.append('kv.atlas', rfn, atlas)
# first time, fill our texture cache.
for nid, texture in atlas.textures.iteritems():
for nid, texture in atlas.textures.items():
fn = 'atlas://%s/%s' % (rfn, nid)
cid = '%s|%s|%s' % (fn, False, 0)
Cache.append('kv.texture', cid, texture)
@ -421,7 +421,7 @@ class Image(EventDispatcher):
self._size = self.texture.size
elif isinstance(arg, ImageLoaderBase):
self.image = arg
elif isinstance(arg, basestring):
elif isinstance(arg, str):
self.filename = arg
else:
raise Exception('Unable to load image type %s' % str(type(arg)))
@ -691,7 +691,7 @@ class Image(EventDispatcher):
size = 3 if data.fmt in ('rgb', 'bgr') else 4
index = y * data.width * size + x * size
raw = data.data[index:index + size]
color = map(lambda c: ord(c) / 255.0, raw)
color = [ord(c) / 255.0 for c in raw]
# conversion for BGR->RGB, BGR->RGBA format
if data.fmt in ('bgr', 'bgra'):

View File

@ -29,7 +29,7 @@ class ImageLoaderDDS(ImageLoaderBase):
if len(dds.images) > 1:
images = dds.images
images_size = dds.images_size
for index in xrange(1, len(dds.images)):
for index in range(1, len(dds.images)):
w, h = images_size[index]
data = images[index]
im.add_mipmap(index, w, h, data)

View File

@ -59,7 +59,7 @@ class ImageLoaderGIF(ImageLoaderBase):
raise
if Debug:
print im.print_info()
print(im.print_info())
img_data = []
ls_width = im.ls_width
ls_height = im.ls_height
@ -202,17 +202,17 @@ class Gif(object):
def print_info(self):
'''prints out some useful info (..debug?)'''
print "Version: %s" % self.header
print "Logical screen width: %d" % self.ls_width
print "Logical screen height: %d" % self.ls_height
print "Flags: %s" % repr(self.flags)
print " " * 6, "Color resolution: %d" % self.color_resolution
print " " * 6, "Sort flag: %r" % self.sort_flag
print " " * 6, "Global color table flag: %r" % self.color_table_flag
print " " * 22, "...size: %d (%d bytes)" % \
(self.global_color_table_size, self.global_color_table_size * 3)
print "Background color: %d" % self.background_color
print "Aspect ratio info: %d" % self.aspect_ratio
print("Version: %s" % self.header)
print("Logical screen width: %d" % self.ls_width)
print("Logical screen height: %d" % self.ls_height)
print("Flags: %s" % repr(self.flags))
print(" " * 6, "Color resolution: %d" % self.color_resolution)
print(" " * 6, "Sort flag: %r" % self.sort_flag)
print(" " * 6, "Global color table flag: %r" % self.color_table_flag)
print(" " * 22, "...size: %d (%d bytes)" % \
(self.global_color_table_size, self.global_color_table_size * 3))
print("Background color: %d" % self.background_color)
print("Aspect ratio info: %d" % self.aspect_ratio)
def new_image(self, header=None):
'''adds a new image descriptor'''
@ -271,7 +271,7 @@ class ImageDescriptor(object):
self.local_color_table_size = 2 ** (pack_bits(self.flags[:3]) + 1)
if self.local_color_table_flag:
if Debug:
print 'local color table true'
print('local color table true')
self.palette = self.parent.get_color_table(
self.local_color_table_size * 3)
@ -380,7 +380,7 @@ class GifDecoder(Gif):
image_lzwcode = ''.join((image_lzwcode, lzwdata))
if self_debug_enabled:
print 'LZW length:', len(image_lzwcode)
print('LZW length:', len(image_lzwcode))
image.lzwcode = image_lzwcode
image.pixels = self_lzw_decode(image.lzwcode, image.codesize,
@ -425,7 +425,7 @@ class GifDecoder(Gif):
bits_append = bits.append
_get_bits = get_bits
for byte in ordarray:
map(bits_append, _get_bits(byte))
list(map(bits_append, _get_bits(byte)))
return bits
def readable(bool_list):
@ -476,8 +476,8 @@ class GifDecoder(Gif):
clearcode, end_of_info = color_table_size, color_table_size + 1
if Debug:
print 'codesize: %d' % codesize
print 'clearcode %d, end_of_info: %d' % (clearcode, end_of_info)
print('codesize: %d' % codesize)
print('clearcode %d, end_of_info: %d' % (clearcode, end_of_info))
def pop(size, _bits):
''' return bits '''
@ -542,7 +542,7 @@ class GifDecoder(Gif):
index += 1
old = c
output_extend(map(ord, c))
output_extend(list(map(ord, c)))
if index == 2 ** codesize:
codesize += 1
@ -550,7 +550,7 @@ class GifDecoder(Gif):
codesize = 12
if self.debug_enabled:
print 'Output stream len: %d' % len(output)
print('Output stream len: %d' % len(output))
return output

View File

@ -213,11 +213,11 @@ class LabelBase(object):
if segment - margin > 5:
segment -= margin
return u'{0}...{1}'.format(text[:segment].strip(),
return '{0}...{1}'.format(text[:segment].strip(),
text[-segment:].strip())
else:
segment = max_letters - 3 # length of '...'
return u'{0}...'.format(text[:segment].strip())
return '{0}...'.format(text[:segment].strip())
def render(self, real=False):
'''Return a tuple(width, height) to create the image

View File

@ -22,7 +22,7 @@ class LabelPIL(LabelBase):
def _select_font(self):
fontsize = int(self.options['font_size'])
fontname = self.options['font_name_r']
id = '%s.%s' % (unicode(fontname), unicode(fontsize))
id = '%s.%s' % (str(fontname), str(fontsize))
if not id in self._cache:
font = ImageFont.truetype(fontname, fontsize)
self._cache[id] = font

View File

@ -22,7 +22,7 @@ pygame.font.init()
class LabelPygame(LabelBase):
def _get_font_id(self):
return '|'.join([unicode(self.options[x]) for x
return '|'.join([str(self.options[x]) for x
in ('font_size', 'font_name_r', 'bold', 'italic')])
def _get_font(self):

View File

@ -20,7 +20,7 @@ except:
from os import path
from threading import Lock
from urllib import pathname2url
from urllib.request import pathname2url
from kivy.graphics.texture import Texture
from kivy.logger import Logger
from functools import partial
@ -51,7 +51,7 @@ def _on_gst_message(bus, message):
Logger.trace('gst-bus: %s' % str(message))
# log all error messages
if message.type == gst.MESSAGE_ERROR:
error, debug = map(str, message.parse_error())
error, debug = list(map(str, message.parse_error()))
Logger.error('gstreamer_video: %s' % error)
Logger.debug('gstreamer_video: %s' % debug)

View File

@ -156,9 +156,9 @@ class Keyboard(EventDispatcher):
:data:`Keyboard.keycodes`. If the value is not found inside the
keycodes, it will return ''.
'''
keycodes = Keyboard.keycodes.values()
keycodes = list(Keyboard.keycodes.values())
if value in keycodes:
return Keyboard.keycodes.keys()[keycodes.index(value)]
return list(Keyboard.keycodes.keys())[keycodes.index(value)]
return ''
@ -716,7 +716,7 @@ class WindowBase(EventDispatcher):
w.width = shw * width
elif shh:
w.height = shh * height
for key, value in w.pos_hint.iteritems():
for key, value in w.pos_hint.items():
if key == 'x':
w.x = value * width
elif key == 'right':
@ -873,7 +873,7 @@ class WindowBase(EventDispatcher):
This will ensure that no virtual keyboard / system keyboard are actually
requested. All will be closed.
'''
for key in self._keyboards.keys()[:]:
for key in list(self._keyboards.keys())[:]:
keyboard = self._keyboards[key]
if keyboard:
keyboard.release()

View File

@ -54,7 +54,7 @@ class WindowPygame(WindowBase):
try:
pygame.display.init()
except pygame.error, e:
except pygame.error as e:
raise CoreCriticalException(e.message)
multisamples = Config.getint('graphics', 'multisamples')
@ -114,7 +114,7 @@ class WindowPygame(WindowBase):
# try to use mode with multisamples
try:
self._pygame_set_mode()
except pygame.error, e:
except pygame.error as e:
if multisamples:
Logger.warning('WinPygame: Video: failed (multisamples=%d)' %
multisamples)
@ -124,7 +124,7 @@ class WindowPygame(WindowBase):
multisamples = 0
try:
self._pygame_set_mode()
except pygame.error, e:
except pygame.error as e:
raise CoreCriticalException(e.message)
else:
raise CoreCriticalException(e.message)
@ -287,11 +287,11 @@ class WindowPygame(WindowBase):
# don't dispatch more key if down event is accepted
if self.dispatch('on_key_down', event.key,
event.scancode, event.unicode,
event.scancode, event.str,
self.modifiers):
continue
self.dispatch('on_keyboard', event.key,
event.scancode, event.unicode,
event.scancode, event.str,
self.modifiers)
# video resize
@ -324,7 +324,7 @@ class WindowPygame(WindowBase):
self._mainloop()
if not pygame.display.get_active():
pygame.time.wait(100)
except BaseException, inst:
except BaseException as inst:
# use exception manager first
r = ExceptionManager.handle_exception(inst)
if r == ExceptionManager.RAISE:

View File

@ -163,7 +163,7 @@ class WindowSDL(WindowBase):
pass
elif action in ('keydown', 'keyup'):
mod, key, scancode, unicode = args
mod, key, scancode, str = args
# XXX ios keyboard suck, when backspace is hit, the delete
# keycode is sent. fix it.
@ -177,11 +177,11 @@ class WindowSDL(WindowBase):
# don't dispatch more key if down event is accepted
if self.dispatch('on_key_down', key,
scancode, unicode,
scancode, str,
self.modifiers):
continue
self.dispatch('on_keyboard', key,
scancode, unicode,
scancode, str,
self.modifiers)
elif action == 'textinput':
@ -266,7 +266,7 @@ class WindowSDL(WindowBase):
while not EventLoop.quit and EventLoop.status == 'started':
try:
self._mainloop()
except BaseException, inst:
except BaseException as inst:
# use exception manager first
r = ExceptionManager.handle_exception(inst)
if r == ExceptionManager.RAISE:
@ -299,7 +299,7 @@ class WindowSDL(WindowBase):
if mods & (pygame.KMOD_META | pygame.KMOD_LMETA):
self._modifiers.append('meta')
def on_keyboard(self, key, scancode=None, unicode=None, modifier=None):
def on_keyboard(self, key, scancode=None, str=None, modifier=None):
# Quit if user presses ESC or the typical OSX shortcuts CMD+q or CMD+w
# TODO If just CMD+w is pressed, only the window should be closed.
is_osx = sys.platform == 'darwin'
@ -307,7 +307,7 @@ class WindowSDL(WindowBase):
stopTouchApp()
self.close() #not sure what to do here
return True
super(WindowSDL, self).on_keyboard(key, scancode, unicode, modifier)
super(WindowSDL, self).on_keyboard(key, scancode, str, modifier)
def request_keyboard(self, *largs):
self._sdl_keyboard = super(WindowSDL, self).request_keyboard(*largs)

View File

@ -152,7 +152,7 @@ def _is_valid_ext_name(name):
major, minor = version.split('.')
major, minor = int(major), int(minor)
except:
print "The name '%s' is not a valid extension name." % name
print("The name '%s' is not a valid extension name." % name)
return False
return (extname, (major, minor))
@ -231,7 +231,7 @@ def unzip_extensions():
except IOError:
Logger.warn("Malformed zipfile '%s'! Skipping it." % zipfn)
continue
except Exception, e:
except Exception as e:
Logger.warn("Malformed extension '%s'! Skipping it." % zipfn)
zipf.close()
continue
@ -268,7 +268,7 @@ def unzip_extensions():
mkdir(join(epath, extdir, directory))
with open(join(epath, extdir, member), 'wb') as fd:
fd.write(zipf.read(member))
except Exception, e:
except Exception as e:
# Catch any error, e.g. non-writable directory, etc.
Logger.error("Failed installing extension " +
"'%s' %s." % (extname, e))

View File

@ -36,7 +36,6 @@ r('AliasProperty', module='kivy.properties')
r('NumericProperty', module='kivy.properties')
r('Property', module='kivy.properties')
r('SafeList', module='kivy.utils')
r('OrderedDict', module='kivy.utils')
r('Vector', module='kivy.vector')
r('Color', module='kivy.graphics.context_instructions')
r('BindTexture', module='kivy.graphics.context_instructions')

View File

@ -37,7 +37,7 @@ import pickle
import base64
import zlib
import math
from cStringIO import StringIO
from io import StringIO
from kivy.vector import Vector
@ -148,7 +148,7 @@ class GestureStroke:
scale_stroke(scale_factor=float)
Scales the stroke down by scale_factor
'''
self.points = map(lambda pt: pt.scale(scale_factor), self.points)
self.points = [pt.scale(scale_factor) for pt in self.points]
def points_distance(self, point1, point2):
'''
@ -168,7 +168,7 @@ class GestureStroke:
gesture_length = 0.0
if len(point_list) <= 1: # If there is only one point -> no length
return gesture_length
for i in xrange(len(point_list)-1):
for i in range(len(point_list)-1):
gesture_length += self.points_distance(
point_list[i], point_list[i+1])
return gesture_length
@ -255,10 +255,10 @@ class Gesture:
''' Scales down the gesture to a unit of 1 '''
# map() creates a list of min/max coordinates of the strokes
# in the gesture and min()/max() pulls the lowest/highest value
min_x = min(map(lambda stroke: stroke.min_x, self.strokes))
max_x = max(map(lambda stroke: stroke.max_x, self.strokes))
min_y = min(map(lambda stroke: stroke.min_y, self.strokes))
max_y = max(map(lambda stroke: stroke.max_y, self.strokes))
min_x = min([stroke.min_x for stroke in self.strokes])
max_x = max([stroke.max_x for stroke in self.strokes])
min_y = min([stroke.min_y for stroke in self.strokes])
max_y = max([stroke.max_y for stroke in self.strokes])
x_len = max_x - min_x
self.width = x_len
y_len = max_y - min_y
@ -351,9 +351,9 @@ class Gesture:
return -1
dot_product = 0.0
for stroke_index, (my_stroke, cmp_stroke) in enumerate(
zip(self.strokes, comparison_gesture.strokes)):
list(zip(self.strokes, comparison_gesture.strokes))):
for pt_index, (my_point, cmp_point) in enumerate(
zip(my_stroke.points, cmp_stroke.points)):
list(zip(my_stroke.points, cmp_stroke.points))):
dot_product += my_point.x * cmp_point.x +\
my_point.y * cmp_point.y
return dot_product

View File

@ -112,7 +112,10 @@ class MotionEventMetaclass(type):
return super(MotionEventMetaclass, mcs).__new__(mcs, name, bases, attrs)
class MotionEvent(object):
MotionEventBase = MotionEventMetaclass('MotionEvent', (object, ), {})
class MotionEvent(MotionEventBase):
'''Abstract class to represent a touch and no-touch object.
:Parameters:
@ -121,8 +124,6 @@ class MotionEvent(object):
`args` : list
list of parameters, passed to depack() function
'''
__metaclass__ = MotionEventMetaclass
__uniq_id = 0
__attrs__ = \
('device', 'push_attrs', 'push_attrs_stack',
@ -373,7 +374,7 @@ class MotionEvent(object):
'''Pop attributes values from the stack
'''
attrs, values = self.push_attrs_stack.pop()
for i in xrange(len(attrs)):
for i in range(len(attrs)):
setattr(self, attrs[i], values[i])
def apply_transform_2d(self, transform):

View File

@ -79,7 +79,7 @@ class InputPostprocDoubleTap(object):
# second, check if up-touch is timeout for double tap
time_current = Clock.get_time()
for touchid in self.touches.keys()[:]:
for touchid in list(self.touches.keys())[:]:
etype, touch = self.touches[touchid]
if etype != 'end':
continue

View File

@ -51,7 +51,7 @@ class AndroidMotionEventProvider(MotionEventProvider):
def start(self):
pygame.joystick.init()
Logger.info('Android: found %d joystick' % pygame.joystick.get_count())
for i in xrange(pygame.joystick.get_count()):
for i in range(pygame.joystick.get_count()):
self.create_joystick(i)
def stop(self):

View File

@ -239,7 +239,7 @@ else:
touch = HIDMotionEvent(device, tid, args)
touches[touch.id] = touch
for tid in touches.keys()[:]:
for tid in list(touches.keys())[:]:
if tid not in actives:
touch = touches[tid]
if tid in touches_sent:
@ -262,7 +262,7 @@ else:
# get abs infos
bit = fcntl.ioctl(fd, EVIOCGBIT + (EV_MAX << 16), ' ' * sz_l)
bit, = struct.unpack('Q', bit)
for x in xrange(EV_MAX):
for x in range(EV_MAX):
# preserve this, we may want other things than EV_ABS
if x != EV_ABS:
continue
@ -273,7 +273,7 @@ else:
sbit = fcntl.ioctl(fd, EVIOCGBIT + x + (KEY_MAX << 16),
' ' * sz_l)
sbit, = struct.unpack('Q', sbit)
for y in xrange(KEY_MAX):
for y in range(KEY_MAX):
if (sbit & (1 << y)) == 0:
continue
absinfo = fcntl.ioctl(fd, EVIOCGABS + y +
@ -308,7 +308,7 @@ else:
break
# extract each event
for i in xrange(len(data) / struct_input_event_sz):
for i in range(len(data) / struct_input_event_sz):
ev = data[i * struct_input_event_sz:]
# extract timeval + event infos

View File

@ -224,8 +224,8 @@ else:
reset_touch = False
def process(points):
actives = points.keys()
for args in points.itervalues():
actives = list(points.keys())
for args in points.values():
tid = args['id']
try:
touch = touches[tid]
@ -242,7 +242,7 @@ else:
touches_sent.append(tid)
queue.append(('update', touch))
for tid in touches.keys()[:]:
for tid in list(touches.keys())[:]:
if tid not in actives:
touch = touches[tid]
if tid in touches_sent:
@ -269,7 +269,7 @@ else:
# get abs infos
bit = fcntl.ioctl(fd, EVIOCGBIT + (EV_MAX << 16), ' ' * sz_l)
bit, = struct.unpack('Q', bit)
for x in xrange(EV_MAX):
for x in range(EV_MAX):
# preserve this, we may want other things than EV_ABS
if x != EV_ABS:
continue
@ -280,7 +280,7 @@ else:
sbit = fcntl.ioctl(fd, EVIOCGBIT + x + (KEY_MAX << 16),
' ' * sz_l)
sbit, = struct.unpack('Q', sbit)
for y in xrange(KEY_MAX):
for y in range(KEY_MAX):
if (sbit & (1 << y)) == 0:
continue
absinfo = fcntl.ioctl(fd, EVIOCGABS + y +
@ -320,7 +320,7 @@ else:
break
# extract each event
for i in xrange(len(data) / struct_input_event_sz):
for i in range(len(data) / struct_input_event_sz):
ev = data[i * struct_input_event_sz:]
# extract timeval + event infos

View File

@ -132,7 +132,7 @@ class MacMotionEventProvider(MotionEventProvider):
devices = MultitouchSupport.MTDeviceCreateList()
num_devices = CFArrayGetCount(devices)
# print 'num_devices =', num_devices
for i in xrange(num_devices):
for i in range(num_devices):
device = CFArrayGetValueAtIndex(devices, i)
# print 'device #%d: %016x' % (i, device)
# create touch dict for this device
@ -169,7 +169,7 @@ class MacMotionEventProvider(MotionEventProvider):
touches = _instance.touches[devid]
actives = []
for i in xrange(n_fingers):
for i in range(n_fingers):
# get pointer on data
data = data_ptr[i]
@ -204,7 +204,7 @@ class MacMotionEventProvider(MotionEventProvider):
_instance.queue.append(('update', touch))
# delete old touchs
for tid in touches.keys()[:]:
for tid in list(touches.keys())[:]:
if tid not in actives:
touch = touches[tid]
touch.update_time_end()

View File

@ -140,7 +140,7 @@ class MouseMotionEventProvider(MotionEventProvider):
def find_touch(self, x, y):
factor = 10. / EventLoop.window.system_size[0]
for t in self.touches.itervalues():
for t in self.touches.values():
if abs(x - t.sx) < factor and abs(y - t.sy) < factor:
return t
return False
@ -202,7 +202,7 @@ class MouseMotionEventProvider(MotionEventProvider):
def on_mouse_release(self, win, x, y, button, modifiers):
# special case, if button is all, then remove all the current mouses.
if button == 'all':
for cur in self.touches.values()[:]:
for cur in list(self.touches.values())[:]:
self.remove_touch(cur)
self.current_drag = None

View File

@ -247,15 +247,15 @@ class Tuio2dCurMotionEvent(TuioMotionEvent):
def depack(self, args):
self.is_touch = True
if len(args) < 5:
self.sx, self.sy = map(float, args[0:2])
self.sx, self.sy = list(map(float, args[0:2]))
self.profile = ('pos', )
elif len(args) == 5:
self.sx, self.sy, self.X, self.Y, self.m = map(float, args[0:5])
self.sx, self.sy, self.X, self.Y, self.m = list(map(float, args[0:5]))
self.Y = -self.Y
self.profile = ('pos', 'mov', 'motacc')
else:
self.sx, self.sy, self.X, self.Y = map(float, args[0:4])
self.m, width, height = map(float, args[4:7])
self.sx, self.sy, self.X, self.Y = list(map(float, args[0:4]))
self.m, width, height = list(map(float, args[4:7]))
self.Y = -self.Y
self.profile = ('pos', 'mov', 'motacc', 'shape')
if self.shape is None:

View File

@ -205,7 +205,7 @@ else:
wParam,
touches,
sizeof(TOUCHINPUT))
for i in xrange(wParam):
for i in range(wParam):
self.touch_events.appendleft(touches[i])
return True

View File

@ -105,7 +105,7 @@ from functools import partial
class RecorderMotionEvent(MotionEvent):
def depack(self, args):
for key, value in args.items():
for key, value in list(args.items()):
setattr(self, key, value)
super(RecorderMotionEvent, self).depack(args)

View File

@ -201,8 +201,8 @@ class SafeMembrane(object):
def __call__(self, *args, **kw):
self.safeIn()
args = map(unwrap, args)
for k in kw.keys():
args = list(map(unwrap, args))
for k in list(kw.keys()):
kw[k] = unwrap(kw[k])
r = self._ref(*args, **kw)
self.safeOut()
@ -236,7 +236,7 @@ class SafeMembrane(object):
delattr(self._ref, attr)
self.safeOut()
def __nonzero__(self):
def __bool__(self):
return bool(self._ref)
def __getitem__(self, arg):

View File

@ -472,9 +472,10 @@ from os.path import join
from copy import copy
from types import ClassType, CodeType
from functools import partial
from collections import OrderedDict
from kivy.factory import Factory
from kivy.logger import Logger
from kivy.utils import OrderedDict, QueryDict
from kivy.utils import QueryDict
from kivy.cache import Cache
from kivy import kivy_data_dir, require
from kivy.lib.debug import make_traceback
@ -526,7 +527,7 @@ class ProxyApp(object):
object.__getattribute__(self, '_ensure_app')()
setattr(object.__getattribute__(self, '_obj'), name, value)
def __nonzero__(self):
def __bool__(self):
object.__getattribute__(self, '_ensure_app')()
return bool(object.__getattribute__(self, '_obj'))
@ -683,7 +684,7 @@ class ParserRule(object):
self._forbid_selectors()
def precompile(self):
for x in self.properties.itervalues():
for x in self.properties.values():
x.precompile()
for x in self.handlers:
x.precompile()
@ -770,11 +771,11 @@ class Parser(object):
'''
PROP_ALLOWED = ('canvas.before', 'canvas.after')
CLASS_RANGE = range(ord('A'), ord('Z') + 1)
CLASS_RANGE = list(range(ord('A'), ord('Z') + 1))
PROP_RANGE = (
range(ord('A'), ord('Z') + 1) +
range(ord('a'), ord('z') + 1) +
range(ord('0'), ord('9') + 1) + [ord('_')])
list(range(ord('A'), ord('Z') + 1)) +
list(range(ord('a'), ord('z') + 1)) +
list(range(ord('0'), ord('9') + 1)) + [ord('_')])
__slots__ = ('rules', 'templates', 'root', 'sourcecode',
'directives', 'filename')
@ -850,7 +851,7 @@ class Parser(object):
if not lines:
return
num_lines = len(lines)
lines = zip(range(num_lines), lines)
lines = list(zip(list(range(num_lines)), lines))
self.sourcecode = lines[:]
if __debug__:
@ -1032,12 +1033,12 @@ class Parser(object):
def custom_callback(__kvlang__, idmap, *largs, **kwargs):
idmap['args'] = largs
try:
exec __kvlang__.co_value in idmap
exec(__kvlang__.co_value, idmap)
except:
exc_info = sys.exc_info()
traceback = make_traceback(exc_info)
exc_type, exc_value, tb = traceback.standard_exc_info
raise exc_type, exc_value, tb
raise exc_type(exc_value).with_traceback(tb)
def create_handler(iself, element, key, value, rule, idmap):
@ -1073,7 +1074,7 @@ def create_handler(iself, element, key, value, rule, idmap):
try:
return eval(value, idmap)
except Exception, e:
except Exception as e:
raise BuilderException(rule.ctx, rule.line, str(e))
@ -1180,7 +1181,7 @@ class BuilderBase(object):
self.rules = [x for x in self.rules if x[1].ctx.filename != filename]
self._clear_matchcache()
templates = {}
for x, y in self.templates.iteritems():
for x, y in self.templates.items():
if y[2] != filename:
templates[x] = y
self.templates = templates
@ -1323,7 +1324,7 @@ class BuilderBase(object):
if 'ctx' in rctx['ids']:
idmap.update({'ctx': rctx['ids']['ctx']})
try:
for prule in crule.properties.itervalues():
for prule in crule.properties.values():
value = prule.co_value
if type(value) is CodeType:
value = eval(value, idmap)
@ -1331,7 +1332,7 @@ class BuilderBase(object):
for prule in crule.handlers:
value = eval(prule.value, idmap)
ctx[prule.name] = value
except Exception, e:
except Exception as e:
raise BuilderException(prule.ctx, prule.line, str(e))
# create the template with an explicit ctx
@ -1354,7 +1355,7 @@ class BuilderBase(object):
# append the properties and handlers to our final resolution task
if rule.properties:
rctx['set'].append((widget, rule.properties.values()))
rctx['set'].append((widget, list(rule.properties.values())))
if rule.handlers:
rctx['hdl'].append((widget, rule.handlers))
@ -1426,14 +1427,14 @@ class BuilderBase(object):
crule.ctx, crule.line,
'You can add only graphics Instruction in canvas.')
try:
for prule in crule.properties.itervalues():
for prule in crule.properties.values():
key = prule.name
value = prule.co_value
if type(value) is CodeType:
value = create_handler(
widget, instr, key, value, prule, idmap)
setattr(instr, key, value)
except Exception, e:
except Exception as e:
raise BuilderException(prule.ctx, prule.line, str(e))
#: Main instance of a :class:`BuilderBase`.

View File

@ -263,7 +263,7 @@ class DDSFile(object):
h = meta.height
images = self.images
images_size = self.images_size
for i in xrange(self.count):
for i in range(self.count):
if dxt in (0, 1, 2, 3):
size = align_value(block * w, 4) * h
else:
@ -290,11 +290,11 @@ class DDSFile(object):
raise DDSException('No images to save')
fields = dict(DDSFile.fields)
fields_keys = fields.keys()
fields_index = fields.values()
fields_keys = list(fields.keys())
fields_index = list(fields.values())
mget = self.meta.get
header = []
for idx in xrange(31):
for idx in range(31):
if idx in fields_index:
value = mget(fields_keys[fields_index.index(idx)], 0)
else:
@ -320,7 +320,7 @@ class DDSFile(object):
assert(level == 0)
# first image, set defaults !
for k in meta.iterkeys():
for k in meta.keys():
meta[k] = 0
self._fmt = fmt
@ -397,15 +397,15 @@ class DDSFile(object):
if __name__ == '__main__':
import sys
if len(sys.argv) == 1:
print 'Usage: python ddsfile.py <file1> <file2> ...'
print('Usage: python ddsfile.py <file1> <file2> ...')
sys.exit(0)
for filename in sys.argv[1:]:
print '=== Loading', filename
print('=== Loading', filename)
try:
dds = DDSFile(filename=filename)
print dds
print(dds)
dds.save('bleh.dds')
except IOError, e:
print 'ERR>', e
except DDSException, e:
print 'DDS>', e
except IOError as e:
print('ERR>', e)
except DDSException as e:
print('DDS>', e)

View File

@ -30,7 +30,7 @@ internal_code = []
# how does the raise helper look like?
try:
exec "raise TypeError, 'foo'"
exec("raise TypeError, 'foo'")
except SyntaxError:
raise_helper = 'raise __jinja_exception__[1]'
except TypeError:
@ -142,7 +142,7 @@ def translate_exception(exc_info, initial_skip=0):
frames = []
# skip some internal frames if wanted
for x in xrange(initial_skip):
for x in range(initial_skip):
if tb is not None:
tb = tb.tb_next
@ -173,7 +173,7 @@ def translate_exception(exc_info, initial_skip=0):
# reraise it unchanged.
# XXX: can we backup here? when could this happen?
if not frames:
raise exc_info[0], exc_info[1], exc_info[2]
raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
return ProcessedTraceback(exc_info[0], exc_info[1], frames)
@ -190,7 +190,7 @@ def fake_exc_info(exc_info, filename, lineno):
locals = ctx.get_all()
else:
locals = {}
for name, value in real_locals.iteritems():
for name, value in real_locals.items():
if name.startswith('l_'):
locals[name[2:]] = value
@ -233,7 +233,7 @@ def fake_exc_info(exc_info, filename, lineno):
# execute the code and catch the new traceback
try:
exec code in globals, locals
exec(code, globals, locals)
except:
exc_info = sys.exc_info()
new_tb = exc_info[2].tb_next

View File

@ -41,10 +41,10 @@ def hexDump(bytes):
for i in range(len(bytes)):
sys.stdout.write("%2x " % (ord(bytes[i])))
if (i+1) % 8 == 0:
print repr(bytes[i-7:i+1])
print(repr(bytes[i-7:i+1]))
if(len(bytes) % 8 != 0):
print string.rjust("", 11), repr(bytes[i-len(bytes)%8:i+1])
print(string.rjust("", 11), repr(bytes[i-len(bytes)%8:i+1]))
class OSCMessage:
@ -113,7 +113,7 @@ def readBlob(data):
def readInt(data):
if(len(data)<4):
print "Error: too few bytes for int", data, len(data)
print("Error: too few bytes for int", data, len(data))
rest = data
integer = 0
else:
@ -128,7 +128,7 @@ def readLong(data):
"""Tries to interpret the next 8 bytes of the data
as a 64-bit signed integer."""
high, low = struct.unpack(">ll", data[0:8])
big = (long(high) << 32) + low
big = (int(high) << 32) + low
rest = data[8:]
return (big, rest)
@ -145,7 +145,7 @@ def readDouble(data):
def readFloat(data):
if(len(data)<4):
print "Error: too few bytes for float", data, len(data)
print("Error: too few bytes for float", data, len(data))
rest = data
float = 0
else:
@ -199,7 +199,7 @@ def parseArgs(args):
possible) as floats or integers."""
parsed = []
for arg in args:
print arg
print(arg)
arg = arg.strip()
interpretation = None
try:
@ -240,7 +240,7 @@ def decodeOSC(data):
value, rest = table[tag](rest)
decoded.append(value)
else:
print "Oops, typetag lacks the magic ,"
print("Oops, typetag lacks the magic ,")
return decoded
@ -275,15 +275,15 @@ class CallbackManager:
for msg in message :
self.dispatch(msg, source)
except KeyError, e:
except KeyError as e:
# address not found
print 'address %s not found ' % address
print('address %s not found ' % address)
pprint.pprint(message)
except IndexError, e:
print 'got malformed OSC message'
except IndexError as e:
print('got malformed OSC message')
pass
except None, e:
print "Exception in", address, "callback :", e
except None as e:
print("Exception in", address, "callback :", e)
return
@ -311,7 +311,7 @@ class CallbackManager:
if __name__ == "__main__":
hexDump("Welcome to the OSC testing program.")
print
print()
message = OSCMessage()
message.setAddress("/foo/play")
message.append(44)
@ -320,7 +320,7 @@ if __name__ == "__main__":
message.append("the white cliffs of dover")
hexDump(message.getBinary())
print "Making and unmaking a message.."
print("Making and unmaking a message..")
strings = OSCMessage()
strings.append("Mary had a little lamb")
@ -335,26 +335,26 @@ if __name__ == "__main__":
hexDump(raw)
print "Retrieving arguments..."
print("Retrieving arguments...")
data = raw
for i in range(6):
text, data = readString(data)
print text
print(text)
number, data = readFloat(data)
print number
print(number)
number, data = readFloat(data)
print number
print(number)
number, data = readInt(data)
print number
print(number)
hexDump(raw)
print decodeOSC(raw)
print decodeOSC(message.getBinary())
print(decodeOSC(raw))
print(decodeOSC(message.getBinary()))
print "Testing Blob types."
print("Testing Blob types.")
blob = OSCMessage()
blob.append("","b")
@ -367,7 +367,7 @@ if __name__ == "__main__":
hexDump(blob.getBinary())
print decodeOSC(blob.getBinary())
print(decodeOSC(blob.getBinary()))
def printingCallback(*stuff):
sys.stdout.write("Got: ")
@ -375,7 +375,7 @@ if __name__ == "__main__":
sys.stdout.write(str(i) + " ")
sys.stdout.write("\n")
print "Testing the callback manager."
print("Testing the callback manager.")
c = CallbackManager()
c.add(printingCallback, "/print")
@ -402,5 +402,5 @@ if __name__ == "__main__":
bundlebinary = bundle.message
print "sending a bundle to the callback manager"
print("sending a bundle to the callback manager")
c.handle(bundlebinary)

View File

@ -11,7 +11,7 @@ __author__ = "www.ixi-software.net"
__license__ = "GNU General Public License"
__all__ = ("oscAPI", "OSC")
from OSC import *
from oscAPI import *
from .OSC import *
from .oscAPI import *

View File

@ -29,7 +29,7 @@
Thanks for the support to Buchsenhausen, Innsbruck, Austria.
'''
import OSC
from . import OSC
import socket, os, time, errno, sys
from threading import Lock
from kivy.logger import Logger
@ -203,7 +203,7 @@ class OSCServer(_OSCServer):
self.socket.settimeout(0.5)
self.haveSocket = True
except socket.error, e:
except socket.error as e:
error, message = e.args
# special handle for EADDRINUSE
@ -221,7 +221,7 @@ class OSCServer(_OSCServer):
try:
message = self.socket.recv(65535)
self._queue_message(message)
except Exception, e:
except Exception as e:
if type(e) == socket.timeout:
continue
Logger.exception('OSC: Error in Tuio recv()')
@ -248,7 +248,7 @@ def dontListen(id = None):
if id and id in oscThreads:
ids = [id]
else:
ids = oscThreads.keys()
ids = list(oscThreads.keys())
for id in ids:
#oscThreads[id].socket.close()
Logger.debug('OSC: Stop thread <%s>' % id)
@ -267,9 +267,9 @@ if __name__ == '__main__':
def printStuff(msg):
'''deals with "print" tagged OSC addresses
'''
print "printing in the printStuff function ", msg
print "the oscaddress is ", msg[0]
print "the value is ", msg[2]
print("printing in the printStuff function ", msg)
print("the oscaddress is ", msg[0])
print("the value is ", msg[2])
bind(printStuff, "/test")

View File

@ -271,7 +271,7 @@ class LoaderBase(object):
def _load_urllib(self, filename, kwargs):
'''(internal) Loading a network file. First download it, save it to a
temporary file, and pass it to _load_local()'''
import urllib2
import urllib.request, urllib.error, urllib.parse
proto = filename.split(':', 1)[0]
if proto == 'smb':
try:
@ -292,10 +292,10 @@ class LoaderBase(object):
if proto == 'smb':
# read from samba shares
fd = urllib2.build_opener(SMBHandler).open(filename)
fd = urllib.request.build_opener(SMBHandler).open(filename)
else:
# read from internet
fd = urllib2.urlopen(filename)
fd = urllib.request.urlopen(filename)
idata = fd.read()
fd.close()
fd = None

View File

@ -63,7 +63,7 @@ __all__ = ('Logger', 'LOG_LEVELS', 'COLORS', 'LoggerHistory')
Logger = None
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = list(range(8))
#These are the sequences need to get colored ouput
RESET_SEQ = "\033[0m"
@ -115,28 +115,28 @@ class FileHandler(logging.Handler):
# Use config ?
maxfiles = 100
print 'Purge log fired. Analysing...'
print('Purge log fired. Analysing...')
join = os.path.join
unlink = os.unlink
# search all log files
l = map(lambda x: join(directory, x), os.listdir(directory))
l = [join(directory, x) for x in os.listdir(directory)]
if len(l) > maxfiles:
# get creation time on every files
l = zip(l, map(os.path.getctime, l))
l = list(zip(l, list(map(os.path.getctime, l))))
# sort by date
l.sort(cmp=lambda x, y: cmp(x[1], y[1]))
# get the oldest (keep last maxfiles)
l = l[:-maxfiles]
print 'Purge %d log files' % len(l)
print('Purge %d log files' % len(l))
# now, unlink every files in the list
for filename in l:
unlink(filename[0])
print 'Purge finished !'
print('Purge finished !')
def _configure(self):
from time import strftime

View File

@ -173,7 +173,7 @@ class ModuleBase:
def update(self):
'''Update status of module for each windows'''
modules_to_activate = map(lambda x: x[0], Config.items('modules'))
modules_to_activate = [x[0] for x in Config.items('modules')]
for win in self.wins:
for name in self.mods:
if not name in modules_to_activate:
@ -189,7 +189,7 @@ class ModuleBase:
def configure(self):
'''(internal) Configure all the modules before using it.
'''
modules_to_configure = map(lambda x: x[0], Config.items('modules'))
modules_to_configure = [x[0] for x in Config.items('modules')]
for name in modules_to_configure:
if name not in self.mods:
Logger.warning('Modules: Module <%s> not found' % name)
@ -226,15 +226,15 @@ class ModuleBase:
def usage_list(self):
print
print 'Available modules'
print '================='
print()
print('Available modules')
print('=================')
for module in self.list():
if not 'module' in self.mods[module]:
self.import_module(module)
text = self.mods[module]['module'].__doc__.strip("\n ")
print '%-12s: %s' % (module, text)
print
print('%-12s: %s' % (module, text))
print()
Modules = ModuleBase()
Modules.add_path(kivy.kivy_modules_dir)
@ -242,4 +242,4 @@ if not 'KIVY_DOC' in os.environ:
Modules.add_path(kivy.kivy_usermodules_dir)
if __name__ == '__main__':
print Modules.list()
print(Modules.list())

View File

@ -311,7 +311,7 @@ class Inspector(FloatLayout):
for node in list(treeview.iterate_all_nodes())[:]:
treeview.remove_node(node)
keys = widget.properties().keys()
keys = list(widget.properties().keys())
keys.sort()
node = None
wk_widget = weakref.ref(widget)
@ -368,7 +368,7 @@ class Inspector(FloatLayout):
dtype = None
if isinstance(prop, AliasProperty) or nested:
# trying to resolve type dynamicly
if type(value) in (unicode, str):
if type(value) in (str, str):
dtype = 'string'
elif type(value) in (int, float):
dtype = 'numeric'

View File

@ -60,7 +60,7 @@ def start(win, ctx):
ctx.color = Color(1, 1, 1)
ctx.rectangle = Rectangle(pos=(5, win.height - 20))
ctx.color = Color(1, 1, 1, .5)
for x in xrange(64):
for x in range(64):
ctx.stats.append(0)
ctx.statsr.append(
Rectangle(pos=(win.width - 64 * 4 + x * 4, win.height - 25),

View File

@ -68,20 +68,20 @@ def usage(device=None):
if device:
Logger.error('Screen: The specified device ({0}) is unknow.',
device)
print '\nModule usage: python main.py -m screen,deviceid[,orientation]\n'
print 'Availables devices:\n'
print '{0:12} {1:<22} {2:<8} {3:<8} {4:<5} {5:<8}'.format(
'Device ID', 'Name', 'Width', 'Height', 'DPI', 'Density')
for device, info in devices.iteritems():
print '{0:12} {1:<22} {2:<8} {3:<8} {4:<5} {5:<8}'.format(
device, *info)
print '\n'
print 'Simulate a medium-density screen as Motolora Droid 2:\n'
print ' python main.py -m screen,droid2\n'
print 'Simulate a high-density screen as HTC One X, in portrait:\n'
print ' python main.py -m screen,onex,portrait\n'
print 'Simulate the iPad 2 screen\n'
print ' python main.py -m screen,ipad\n'
print('\nModule usage: python main.py -m screen,deviceid[,orientation]\n')
print('Availables devices:\n')
print('{0:12} {1:<22} {2:<8} {3:<8} {4:<5} {5:<8}'.format(
'Device ID', 'Name', 'Width', 'Height', 'DPI', 'Density'))
for device, info in devices.items():
print('{0:12} {1:<22} {2:<8} {3:<8} {4:<5} {5:<8}'.format(
device, *info))
print('\n')
print('Simulate a medium-density screen as Motolora Droid 2:\n')
print(' python main.py -m screen,droid2\n')
print('Simulate a high-density screen as HTC One X, in portrait:\n')
print(' python main.py -m screen,onex,portrait\n')
print('Simulate the iPad 2 screen\n')
print(' python main.py -m screen,ipad\n')
sys.exit(1)
@ -93,7 +93,7 @@ def configure(ctx):
orientation = 'portrait'
if not ctx:
return usage(None)
device = ctx.keys()[0]
device = list(ctx.keys())[0]
if device not in devices:
return usage('')
apply_device(device, scale, orientation)

View File

@ -24,7 +24,7 @@ import json
from gc import get_objects, garbage
from kivy.clock import Clock
from kivy.cache import Cache
from kivy.utils import OrderedDict
from collections import OrderedDict
from kivy.logger import Logger
try:
@ -83,11 +83,11 @@ class FlaskThread(threading.Thread):
m['Python garbage'].append(len(garbage))
m['FPS (internal)'].append(Clock.get_fps())
m['FPS (real)'].append(Clock.get_rfps())
m['Events'].append(sum([len(x) for x in Clock._events.itervalues()]))
m['Events'].append(sum([len(x) for x in Clock._events.values()]))
for category in Cache._categories:
m['Cache ' + category].append(
len(Cache._objects.get(category, [])))
for values in m.itervalues():
for values in m.values():
values.pop(0)
values[0] = 0

View File

@ -57,17 +57,17 @@ Example of Posting data (adapted from httplib example)::
from collections import deque
from threading import Thread
from json import loads
from httplib import HTTPConnection
from http.client import HTTPConnection
from time import sleep
HTTPSConnection = None
try:
from httplib import HTTPSConnection
from http.client import HTTPSConnection
except ImportError:
# on android platform, this is not available yet.
pass
from urlparse import urlparse
from urllib.parse import urlparse
from kivy.clock import Clock
from kivy.weakmethod import WeakMethod
from kivy.logger import Logger
@ -163,7 +163,7 @@ class UrlRequest(Thread):
try:
result, resp = self._fetch_url(url, req_body, req_headers, q)
result = self.decode_result(result, resp)
except Exception, e:
except Exception as e:
pass
if e is not None:
@ -412,6 +412,6 @@ if __name__ == '__main__':
sleep(1)
Clock.tick()
print 'result =', req.result
print 'error =', req.error
print('result =', req.result)
print('error =', req.error)

View File

@ -76,7 +76,7 @@ def parse_color(text):
'ColorParser: Invalid color format for %r' % text)
try:
value = [int(res[i:i + 2], 16) / 255.
for i in xrange(0, len(res), 2)]
for i in range(0, len(res), 2)]
except ValueError:
return color_error('ColorParser: Invalid color for %r' % text)
if lres == 6:
@ -109,7 +109,7 @@ def parse_int2(text):
'''
texts = [x for x in text.split(' ') if x.strip() != '']
value = map(parse_int, texts)
value = list(map(parse_int, texts))
if len(value) < 1:
raise Exception('Invalid int2 format: %s' % text)
elif len(value) == 1:
@ -127,11 +127,11 @@ def parse_float4(text):
'''
texts = [x for x in text.split(' ') if x.strip() != '']
value = map(parse_float, texts)
value = list(map(parse_float, texts))
if len(value) < 1:
raise Exception('Invalid float4 format: %s' % text)
elif len(value) == 1:
return map(lambda x: value[0], range(4))
return [value[0] for x in range(4)]
elif len(value) == 2:
return [value[0], value[1], value[0], value[1]]
elif len(value) == 3:

View File

@ -63,7 +63,7 @@ def install_android():
try:
import android
except ImportError:
print 'Android lib is missing, cannot install android hooks'
print('Android lib is missing, cannot install android hooks')
return
from kivy.clock import Clock

View File

@ -209,7 +209,7 @@ class GraphicUnitTest(unittest.TestCase):
if 'UNITTEST_INTERACTIVE' not in environ:
return True
from Tkinter import Tk, Label, LEFT, RIGHT, BOTTOM, Button
from tkinter import Tk, Label, LEFT, RIGHT, BOTTOM, Button
from PIL import Image, ImageTk
self.retval = False
@ -240,7 +240,7 @@ class GraphicUnitTest(unittest.TestCase):
if 'UNITTEST_INTERACTIVE' not in environ:
return False
from Tkinter import Tk, Label, LEFT, RIGHT, BOTTOM, Button
from tkinter import Tk, Label, LEFT, RIGHT, BOTTOM, Button
from PIL import Image, ImageTk
self.retval = False

View File

@ -51,10 +51,10 @@ class PerfApp(App, FloatLayout):
self.test_done = True
def load_large_text(self, *largs):
print 'loading uix/textinput.py....'
print('loading uix/textinput.py....')
self.test_done = False
fd = open(resource_find('uix/textinput.py'), 'r')
print 'putting text in textinput'
print('putting text in textinput')
def load_text(*l):
self.text_input.text = fd.read()
@ -63,11 +63,11 @@ class PerfApp(App, FloatLayout):
ttk = t.timeit(1)
fd.close()
import resource
print 'mem usage after test'
print resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024, 'MB'
print '------------------------------------------'
print 'Loaded', len(self.text_input._lines), 'lines', ttk, 'secs'
print '------------------------------------------'
print('mem usage after test')
print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024, 'MB')
print('------------------------------------------')
print('Loaded', len(self.text_input._lines), 'lines', ttk, 'secs')
print('------------------------------------------')
self.test_done = True
def stress_del(self, *largs):
@ -80,17 +80,17 @@ class PerfApp(App, FloatLayout):
def dlt(*l):
if len(text_input.text) <= target:
Clock.unschedule(dlt)
print 'Done!'
print('Done!')
m_len = len(text_input._lines)
print 'deleted 210 characters 9 times'
print('deleted 210 characters 9 times')
import resource
print 'mem usage after test'
print resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\
/ 1024, 'MB'
print 'total lines in text input:', m_len
print '--------------------------------------'
print 'total time elapsed:', self.tot_time
print '--------------------------------------'
print('mem usage after test')
print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\
/ 1024, 'MB')
print('total lines in text input:', m_len)
print('--------------------------------------')
print('total time elapsed:', self.tot_time)
print('--------------------------------------')
self.test_done = True
return
text_input.select_text(self.lt - 220, self.lt - 10)
@ -114,18 +114,18 @@ class PerfApp(App, FloatLayout):
def pste(*l):
if len(text_input._lines) >= (len_text) * 9:
Clock.unschedule(pste)
print 'Done!'
print('Done!')
m_len = len(text_input._lines)
print 'pasted', len_text, 'lines', \
round((m_len - len_text) / len_text), 'times'
print('pasted', len_text, 'lines', \
round((m_len - len_text) / len_text), 'times')
import resource
print 'mem usage after test'
print resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\
/ 1024, 'MB'
print 'total lines in text input:', m_len
print '--------------------------------------'
print 'total time elapsed:', self.tot_time
print '--------------------------------------'
print('mem usage after test')
print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\
/ 1024, 'MB')
print('total lines in text input:', m_len)
print('--------------------------------------')
print('total time elapsed:', self.tot_time)
print('--------------------------------------')
self.test_done = True
return
self.tot_time += l[0]
@ -142,14 +142,14 @@ class PerfApp(App, FloatLayout):
def pste(*l):
if text_input.selection_from >= old_selection_from:
Clock.unschedule(pste)
print 'Done!'
print('Done!')
import resource
print 'mem usage after test'
print resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\
/ 1024, 'MB'
print '--------------------------------------'
print 'total time elapsed:', self.tot_time
print '--------------------------------------'
print('mem usage after test')
print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\
/ 1024, 'MB')
print('--------------------------------------')
print('total time elapsed:', self.tot_time)
print('--------------------------------------')
self.test_done = True
return
text_input.select_text(text_input.selection_from - 1,
@ -167,18 +167,18 @@ class PerfApp(App, FloatLayout):
but = self.tests[int(self.slider.value)]
self.slider.value += 1
but.state = 'down'
print '====================='
print 'Test:', but.text
print '====================='
print('=====================')
print('Test:', but.text)
print('=====================')
but.test(but)
except IndexError:
for but in self.tests:
but.state = 'normal'
self.but.text = 'Start Test'
self.slider.value = 0
print '==================='
print 'All Tests Completed'
print '==================='
print('===================')
print('All Tests Completed')
print('===================')
Clock.unschedule(test)
Clock.schedule_interval(test, 1)

View File

@ -34,7 +34,7 @@ from nose.tools import raises
# A dictionary of dicts, with only the minimum required is_selected attribute,
# for use with examples using a simple list of integers in a list view.
integers_dict = \
{str(i): {'text': str(i), 'is_selected': False} for i in xrange(100)}
{str(i): {'text': str(i), 'is_selected': False} for i in range(100)}
# ----------------------------------------------------------------------------
@ -187,7 +187,7 @@ fruit_data_attribute_units = ['(g)',
'(%DV)']
attributes_and_units = \
dict(zip(fruit_data_attributes, fruit_data_attribute_units))
dict(list(zip(fruit_data_attributes, fruit_data_attribute_units)))
fruit_data = {}
for fruit_record in fruit_data_list_of_dicts:
@ -196,7 +196,7 @@ for fruit_record in fruit_data_list_of_dicts:
dict({'name': fruit_record['name'],
'Serving Size': fruit_record['Serving Size'],
'is_selected': fruit_record['is_selected']},
**dict(zip(attributes_and_units.keys(), fruit_record['data'])))
**dict(list(zip(list(attributes_and_units.keys()), fruit_record['data']))))
class CategoryItem(SelectableDataItem):
@ -281,7 +281,7 @@ class AdaptersTestCase(unittest.TestCase):
'height': 25}
self.integers_dict = \
{str(i): {'text': str(i), 'is_selected': False} for i in xrange(100)}
{str(i): {'text': str(i), 'is_selected': False} for i in range(100)}
# The third of the four cls_dict items has no kwargs nor text, so
# rec['text'] will be set for it. Likewise, the fifth item has kwargs,
@ -753,7 +753,7 @@ class AdaptersTestCase(unittest.TestCase):
def test_list_adapter_with_dicts_as_data(self):
bare_minimum_dicts = \
[{'text': str(i), 'is_selected': False} for i in xrange(100)]
[{'text': str(i), 'is_selected': False} for i in range(100)]
args_converter = lambda row_index, rec: {'text': rec['text'],
'size_hint_y': None,
@ -766,7 +766,7 @@ class AdaptersTestCase(unittest.TestCase):
cls=ListItemButton)
self.assertEqual([rec['text'] for rec in list_adapter.data],
[str(i) for i in xrange(100)])
[str(i) for i in range(100)])
self.assertEqual(list_adapter.cls, ListItemButton)
self.assertEqual(list_adapter.args_converter, args_converter)
@ -784,7 +784,7 @@ class AdaptersTestCase(unittest.TestCase):
def test_list_adapter_with_dicts_as_data_multiple_selection(self):
bare_minimum_dicts = \
[{'text': str(i), 'is_selected': False} for i in xrange(100)]
[{'text': str(i), 'is_selected': False} for i in range(100)]
args_converter = lambda row_index, rec: {'text': rec['text'],
'size_hint_y': None,
@ -797,7 +797,7 @@ class AdaptersTestCase(unittest.TestCase):
cls=ListItemButton)
self.assertEqual([rec['text'] for rec in list_adapter.data],
[str(i) for i in xrange(100)])
[str(i) for i in range(100)])
self.assertEqual(list_adapter.cls, ListItemButton)
self.assertEqual(list_adapter.args_converter, args_converter)
@ -828,7 +828,7 @@ class AdaptersTestCase(unittest.TestCase):
cls=ListItemButton)
first_category_fruits = \
fruit_categories[fruit_categories.keys()[0]]['fruits']
fruit_categories[list(fruit_categories.keys())[0]]['fruits']
first_category_fruit_data_items = \
[f for f in fruit_data_items if f.name in first_category_fruits]
@ -1041,7 +1041,7 @@ class AdaptersTestCase(unittest.TestCase):
self.assertEqual(pet_listener.current_pet, ['cat'])
def test_dict_adapter_composite(self):
item_strings = ["{0}".format(index) for index in xrange(100)]
item_strings = ["{0}".format(index) for index in range(100)]
# And now the list adapter, constructed with the item_strings as
# the data, a dict to add the required is_selected boolean onto

View File

@ -65,7 +65,7 @@ class VertexInstructionTestCase(GraphicUnitTest):
wid = Widget()
with wid.canvas:
Color(1, 1, 1)
Point(points=[x * 5 for x in xrange(50)])
Point(points=[x * 5 for x in range(50)])
r(wid)
def test_point_add(self):

View File

@ -8,7 +8,7 @@ class ImageTestCase(unittest.TestCase):
import os
self.cls = Image
self.image = os.path.join(os.path.dirname(__file__), 'test_button.png')
print self.image
print(self.image)
self.root = Image(self.image)
def test_keep_data(self):

View File

@ -21,7 +21,7 @@ from kivy.adapters.models import SelectableDataItem
# A dictionary of dicts, with only the minimum required is_selected attribute,
# for use with examples using a simple list of integers in a list view.
integers_dict = \
{str(i): {'text': str(i), 'is_selected': False} for i in xrange(100)}
{str(i): {'text': str(i), 'is_selected': False} for i in range(100)}
# ----------------------------------------------------------------------------
@ -164,7 +164,7 @@ fruit_data_attribute_units = ['(g)',
'(%DV)']
attributes_and_units = \
dict(zip(fruit_data_attributes, fruit_data_attribute_units))
dict(list(zip(fruit_data_attributes, fruit_data_attribute_units)))
fruit_data = {}
for fruit_record in fruit_data_list_of_dicts:
@ -173,7 +173,7 @@ for fruit_record in fruit_data_list_of_dicts:
dict({'name': fruit_record['name'],
'Serving Size': fruit_record['Serving Size'],
'is_selected': fruit_record['is_selected']},
**dict(zip(attributes_and_units.keys(), fruit_record['data'])))
**dict(list(zip(list(attributes_and_units.keys()), fruit_record['data']))))
class CategoryItem(SelectableDataItem):

View File

@ -19,7 +19,7 @@ class ListViewTestCase(unittest.TestCase):
def test_simple_list_view(self):
list_view = \
ListView(item_strings=[str(index) for index in xrange(100)])
ListView(item_strings=[str(index) for index in range(100)])
self.assertEqual(type(list_view.adapter), SimpleListAdapter)
self.assertFalse(hasattr(list_view.adapter, 'selection'))
@ -29,7 +29,7 @@ class ListViewTestCase(unittest.TestCase):
simple_list_adapter = \
SimpleListAdapter(
data=["Item #{0}".format(i) for i in xrange(100)],
data=["Item #{0}".format(i) for i in range(100)],
cls=Label)
list_view = ListView(adapter=simple_list_adapter)
@ -84,7 +84,7 @@ class ListViewTestCase(unittest.TestCase):
def test_list_view_with_list_of_integers(self):
data = [{'text': str(i), 'is_selected': False} for i in xrange(100)]
data = [{'text': str(i), 'is_selected': False} for i in range(100)]
args_converter = lambda row_index, rec: {'text': rec['text'],
'size_hint_y': None,
@ -105,7 +105,7 @@ class ListViewTestCase(unittest.TestCase):
def test_list_view_with_list_of_integers_scrolling(self):
data = [{'text': str(i), 'is_selected': False} for i in xrange(100)]
data = [{'text': str(i), 'is_selected': False} for i in range(100)]
args_converter = lambda row_index, rec: {'text': rec['text'],
'size_hint_y': None,
@ -125,7 +125,7 @@ class ListViewTestCase(unittest.TestCase):
def test_simple_list_view_deletion(self):
list_view = \
ListView(item_strings=[str(index) for index in xrange(100)])
ListView(item_strings=[str(index) for index in range(100)])
self.assertEqual(len(list_view.adapter.data), 100)
del list_view.adapter.data[49]

View File

@ -4,7 +4,7 @@ UrlRequest tests
'''
import unittest
import thread
import _thread
from kivy.network.urlrequest import UrlRequest
from time import sleep
from kivy.clock import Clock
@ -13,13 +13,13 @@ from kivy.clock import Clock
class UrlRequestTest(unittest.TestCase):
def _on_success(self, req, *args):
self.queue.append((thread.get_ident(), 'success', args))
self.queue.append((_thread.get_ident(), 'success', args))
def _on_error(self, req, *args):
self.queue.append((thread.get_ident(), 'error', args))
self.queue.append((_thread.get_ident(), 'error', args))
def _on_progress(self, req, *args):
self.queue.append((thread.get_ident(), 'progress', args))
self.queue.append((_thread.get_ident(), 'progress', args))
def test_callbacks(self):
self.queue = []
@ -29,7 +29,7 @@ class UrlRequestTest(unittest.TestCase):
on_error=self._on_error)
# don't use wait, but maximum 10s timeout
for i in xrange(50):
for i in range(50):
Clock.tick()
sleep(.5)
if req.is_finished:
@ -39,10 +39,10 @@ class UrlRequestTest(unittest.TestCase):
# we should have 2 progress minimum and one success
self.assertTrue(len(self.queue) >= 3)
print self.queue
print(self.queue)
# ensure the callback is called from this thread (main).
tid = thread.get_ident()
tid = _thread.get_ident()
self.assertEqual(self.queue[0][0], tid)
self.assertEqual(self.queue[-2][0], tid)
self.assertEqual(self.queue[-1][0], tid)

View File

@ -4,6 +4,8 @@ Benchmark
'''
from __future__ import print_function
benchmark_version = '1'
import os
@ -35,7 +37,7 @@ class bench_widget_creation:
def run(self):
o = []
for x in xrange(10000):
for x in range(10000):
o.append(Widget())
@ -44,7 +46,7 @@ class bench_widget_creation_with_root:
def run(self):
o = Widget()
for x in xrange(10000):
for x in range(10000):
o.add_widget(Widget())
@ -54,7 +56,7 @@ class bench_widget_draw:
def __init__(self):
self.ctx = RenderContext()
self.root = root = Widget()
for x in xrange(10000):
for x in range(10000):
root.add_widget(Widget())
self.ctx.add(self.root.canvas)
@ -67,9 +69,9 @@ class bench_widget_dispatch:
def __init__(self):
root = Widget()
for x in xrange(10):
for x in range(10):
parent = Widget()
for y in xrange(1000):
for y in range(1000):
parent.add_widget(Widget())
root.add_widget(parent)
self.root = root
@ -86,8 +88,8 @@ class bench_label_creation:
def __init__(self):
labels = []
for x in xrange(10000):
label = map(lambda x: chr(randint(ord('a'), ord('z'))), xrange(10))
for x in range(10000):
label = [chr(randint(ord('a'), ord('z'))) for x in range(10)]
labels.append(''.join(label))
self.labels = labels
@ -102,8 +104,8 @@ class bench_label_creation_with_tick:
def __init__(self):
labels = []
for x in xrange(10000):
label = map(lambda x: chr(randint(ord('a'), ord('z'))), xrange(10))
for x in range(10000):
label = [chr(randint(ord('a'), ord('z'))) for x in range(10)]
labels.append(''.join(label))
self.labels = labels
@ -127,15 +129,15 @@ if __name__ == '__main__':
else:
report.append(s)
if newline:
print s
print(s)
report_newline = True
else:
print s,
print(s, end=' ')
report_newline = False
sys.stdout.flush()
clock_total = 0
benchs = locals().keys()
benchs = list(locals().keys())
benchs.sort()
benchs = [locals()[x] for x in benchs if x.startswith('bench_')]
@ -181,7 +183,7 @@ if __name__ == '__main__':
try:
sys.stderr.write('.')
test = x()
except Exception, e:
except Exception as e:
log('failed %s' % str(e))
import traceback
traceback.print_exc()
@ -194,7 +196,7 @@ if __name__ == '__main__':
test.run()
clock_end = clockfn() - clock_start
log('%.6f' % clock_end)
except Exception, e:
except Exception as e:
log('failed %s' % str(e))
continue
@ -205,18 +207,18 @@ if __name__ == '__main__':
log('')
try:
reply = raw_input(
reply = input(
'Do you want to send benchmark to gist.github.com (Y/n) : ')
except EOFError:
sys.exit(0)
if reply.lower().strip() in ('', 'y'):
print 'Please wait while sending the benchmark...'
print('Please wait while sending the benchmark...')
try:
import requests
except ImportError:
print "`requests` module not found, no benchmark posted."
print("`requests` module not found, no benchmark posted.")
sys.exit(1)
payload = {
@ -226,10 +228,10 @@ if reply.lower().strip() in ('', 'y'):
r = requests.post('https://api.github.com/gists', data=json.dumps(payload))
print
print
print 'REPORT posted at {0}'.format(r.json['html_url'])
print
print
print()
print()
print('REPORT posted at {0}'.format(r.json['html_url']))
print()
print()
else:
print 'No benchmark posted.'
print('No benchmark posted.')

View File

@ -13,19 +13,19 @@
(Originally developed for flask.pocoo.org)
:license: BSD, see LICENSE for more details.
"""
from __future__ import with_statement
import re
import os
import sys
import getpass
from datetime import datetime
from urllib import quote
from urllib.parse import quote
_sep_re = re.compile(r'[\s.,;_-]+')
FILE_HEADER_TEMPLATE = u'''\
FILE_HEADER_TEMPLATE = '''\
# -*- coding: utf-8 -*-
"""
%(module)s
@ -37,7 +37,7 @@ FILE_HEADER_TEMPLATE = u'''\
"""
'''
SETUP_PY_TEMPLATE = u'''\
SETUP_PY_TEMPLATE = '''\
"""
%(name)s
%(namedecor)s
@ -119,7 +119,7 @@ def prompt(name, default=None):
prompt = name + (default and ' [%s]' % default or '')
prompt += name.endswith('?') and ' ' or ': '
while True:
rv = raw_input(prompt)
rv = input(prompt)
if rv:
return rv
if default is not None:
@ -193,11 +193,11 @@ class Extension(object):
def main():
if len(sys.argv) not in (1, 2):
print 'usage: make-kivyext.py [output-folder]'
print('usage: make-kivyext.py [output-folder]')
return
msg = 'Welcome to the Kivy Extension Creator Wizard'
print msg
print '~' * len(msg)
print(msg)
print('~' * len(msg))
name = prompt('Extension Name (human readable)')
shortname = prompt('Extension Name (for filesystem)', guess_package(name))
@ -208,7 +208,7 @@ def main():
while 1:
folder = prompt('Output folder', default=output_folder)
if os.path.isfile(folder):
print 'Error: output folder is a file'
print('Error: output folder is a file')
elif os.path.isdir(folder) and os.listdir(folder):
if prompt_bool('Warning: output folder is not empty. Continue'):
break
@ -227,7 +227,7 @@ def main():
populate the placeholder values. Obviously you will also need to add the
actual extension code.
''' % dict(output_folder=output_folder)
print msg
print(msg)
if __name__ == '__main__':

View File

@ -23,6 +23,7 @@
extension.
'''
from __future__ import print_function
gl = open("/Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/" +
"OpenGL.framework/Versions/A/Headers/gl.h", 'r')
@ -54,9 +55,9 @@ def add_defines_to_set(header):
symbol = element
if symbol:
symbols.append((symbol, lineno, line, hexcode))
except Exception, e:
print 'error:', lineno, ':', line
print e
except Exception as e:
print('error:', lineno, ':', line)
print(e)
return symbols
@ -69,21 +70,21 @@ def extract_common_symbols(symbols1, symbols2, already_extracted):
if symbol1 == symbol2 + 'f':
# There is no `double` type in GLES; Functions that were using
# a double were renamed with the suffix 'f'.
print "// Different Name; Redefine"
print line2
print "#define %s %s" % (symbol1, symbol2)
print("// Different Name; Redefine")
print(line2)
print("#define %s %s" % (symbol1, symbol2))
elif symbol1 == symbol2:
already_extracted.append(symbol1)
print line1
print(line1)
if symbol1 == 'GLclampf;':
# See explanation about doubles on GLES above.
print 'typedef GLclampf GLclampd;'
print('typedef GLclampf GLclampd;')
elif hexcode1 and hexcode2 and hexcode1 == hexcode2:
already_extracted.append(symbol1)
already_extracted.append(symbol2)
print "// Different Name; Redefine"
print line2
print "#define %s %s" % (symbol1, symbol2)
print("// Different Name; Redefine")
print(line2)
print("#define %s %s" % (symbol1, symbol2))
# Generate ------------------------------------------------
# pipe to kivy/kivy/graphics/common_subset.h
@ -92,33 +93,33 @@ gl_symbols = add_defines_to_set(gl)
glext_symbols = add_defines_to_set(glext)
gles_symbols = add_defines_to_set(gles)
print '// GLES 2.0 Header file, generated for Kivy'
print '// Check kivy/kivy/tools/gles_compat/subset_gles.py'
print '#pragma once'
print '#include "gl2platform.h"'
print '#ifdef __cplusplus'
print 'extern "C" {'
print '#endif'
print('// GLES 2.0 Header file, generated for Kivy')
print('// Check kivy/kivy/tools/gles_compat/subset_gles.py')
print('#pragma once')
print('#include "gl2platform.h"')
print('#ifdef __cplusplus')
print('extern "C" {')
print('#endif')
# Don't add the same symbol more than once
already_extracted = []
print '\n// Subset common to GLES and GL: ===================================='
print('\n// Subset common to GLES and GL: ====================================')
extract_common_symbols(gles_symbols, gl_symbols, already_extracted)
print '\n// Subset common to GLES and GLEXT: ================================='
print('\n// Subset common to GLES and GLEXT: =================================')
extract_common_symbols(gles_symbols, glext_symbols, already_extracted)
print
print '// What follows was manually extracted from the GLES2 headers because'
print '// it was not present in any other header.',
print '''
print()
print('// What follows was manually extracted from the GLES2 headers because')
print('// it was not present in any other header.', end=' ')
print('''
#define GL_SHADER_BINARY_FORMATS 0x8DF8
#define GL_RGB565 0x8D62
'''
''')
print '#ifdef __cplusplus'
print '}'
print '#endif'
print
print('#ifdef __cplusplus')
print('}')
print('#endif')
print()

View File

@ -1,3 +1,5 @@
from __future__ import print_function
__all__ = ('FactoryBuild', )
from distutils.cmd import Command
@ -28,9 +30,9 @@ class FactoryBuild(Command):
pass
def run(self):
print '--------------------------------------------'
print 'Building factory relation file'
print '--------------------------------------------'
print('--------------------------------------------')
print('Building factory relation file')
print('--------------------------------------------')
root_dir = os.path.dirname(kivy.__file__)
filename = os.path.join(root_dir, 'factory_registers.py')
@ -63,31 +65,31 @@ class FactoryBuild(Command):
#print '<<< ignored (not a __init__.py)'
continue
print '>>>', module, '::',
print('>>>', module, '::', end=' ')
try:
m = __import__(name=module, fromlist='.')
except Exception, e:
print
print 'ERROR:', e
except Exception as e:
print()
print('ERROR:', e)
continue
if not hasattr(m, '__all__'):
print
print()
continue
for symbol in getattr(m, '__all__'):
if symbol.startswith('_'):
continue
attr = getattr(m, symbol)
if type(attr) not in (types.TypeType, types.ClassType):
if type(attr) not in (type, type):
continue
symbols.append((symbol, module))
print symbol,
print
print(symbol, end=' ')
print()
print
print '--------------------------------------------'
print 'Found %d symbols, generating file' % len(symbols)
print '--------------------------------------------'
print()
print('--------------------------------------------')
print('Found %d symbols, generating file' % len(symbols))
print('--------------------------------------------')
filename = os.path.join(root_dir, 'factory_registers.py')
with open(filename, 'w') as fd:
@ -99,4 +101,4 @@ class FactoryBuild(Command):
for x in symbols:
fd.write("r('%s', module='%s')\n" % x)
print 'File written at', filename
print('File written at', filename)

View File

@ -1,11 +1,12 @@
from __future__ import print_function
import os
import sys
import shutil
import shlex
import re
import time
from urllib import urlretrieve
from urllib2 import urlopen
from urllib.request import urlretrieve
from urllib.request import urlopen
from subprocess import Popen, PIPE
from distutils.cmd import Command
@ -43,32 +44,32 @@ class OSXPortableBuild(Command):
def run(self):
intro = "Building Kivy Portable for OSX (%s)" % (self.dist_name)
print "-" * len(intro)
print intro
print "-" * len(intro)
print("-" * len(intro))
print(intro)
print("-" * len(intro))
print "\nPreparing Build..."
print "---------------------------------------"
print("\nPreparing Build...")
print("---------------------------------------")
if os.path.exists(self.build_dir):
print "*Cleaning old build dir"
print("*Cleaning old build dir")
shutil.rmtree(self.build_dir, ignore_errors=True)
print "*Creating build directory:", self.build_dir
print("*Creating build directory:", self.build_dir)
os.makedirs(self.build_dir)
def download_deps():
print "\nGetting binary dependencies..."
print "*Downloading:", self.deps_url
print("\nGetting binary dependencies...")
print("*Downloading:", self.deps_url)
# report_hook is called every time a piece of teh file is
# downloaded to print progress
def report_hook(block_count, block_size, total_size):
p = block_count * block_size * 100.0 / total_size
print "\b\b\b\b\b\b\b\b\b", "%06.2f" % p + "%",
print " Progress: 000.00%",
print("\b\b\b\b\b\b\b\b\b", "%06.2f" % p + "%", end=' ')
print(" Progress: 000.00%", end=' ')
# location of binary dependencioes needed for portable kivy
urlretrieve(self.deps_url,
# tmp file to store the archive
os.path.join(self.dist_dir, 'deps.zip'),
reporthook=report_hook)
print " [Done]"
print(" [Done]")
fn = '.last_known_portable_deps_hash'
@ -79,18 +80,18 @@ class OSXPortableBuild(Command):
start_index = c.find(start) + len(start)
# SHA1 hash is 40 chars long
latest_hash = c[start_index:start_index+40]
print "Latest SHA1 Hash for deps is:", repr(latest_hash)
print("Latest SHA1 Hash for deps is:", repr(latest_hash))
return latest_hash
print "\nChecking binary dependencies..."
print "---------------------------------------"
print("\nChecking binary dependencies...")
print("---------------------------------------")
download = False
try:
with open(fn, 'r') as fd:
last_hash = fd.read()
print "Stored SHA1 Hash for deps is:", repr(last_hash)
print("Stored SHA1 Hash for deps is:", repr(last_hash))
except:
print 'No cached copy of binary dependencies found.'
print('No cached copy of binary dependencies found.')
download = True
latest_hash = get_latest_hash()
deps = os.path.join(self.dist_dir, 'deps.zip')
@ -99,17 +100,17 @@ class OSXPortableBuild(Command):
with open(fn, 'w') as fd:
fd.write(latest_hash)
else:
print "Using CACHED COPY for binary dependencies!"
print("Using CACHED COPY for binary dependencies!")
print "*Extracting binary dependencies..."
print("*Extracting binary dependencies...")
# using osx sysetm command, because python zipfile cant
# handle the hidden files in teh archive
Popen(['unzip', os.path.join(self.dist_dir, 'deps.zip')],
cwd=self.build_dir, stdout=PIPE).communicate()
print "\nPutting kivy into portable environment"
print "---------------------------------------"
print "*Building kivy source distribution"
print("\nPutting kivy into portable environment")
print("---------------------------------------")
print("*Building kivy source distribution")
sdist_cmd = [sys.executable, #path to python.exe
os.path.join(self.src_dir, 'setup.py'), #path to setup.py
'sdist', #make setup.py create a src distribution
@ -117,17 +118,17 @@ class OSXPortableBuild(Command):
Popen(sdist_cmd, stdout=PIPE).communicate()
print "*Placing kivy source distribution in portable context"
print("*Placing kivy source distribution in portable context")
src_dist = os.path.join(self.build_dir, self.dist_name)
# using osx sysetm command, becasue python zipfile
# cant handle the hidden files in teh archive
Popen(['tar', 'xfv', src_dist + '.tar.gz'], cwd=self.build_dir,
stdout=PIPE, stderr=PIPE).communicate()
if self.no_cext:
print "*Skipping C Extension build",
print "(either --no_cext or --no_mingw option set)"
print("*Skipping C Extension build", end=' ')
print("(either --no_cext or --no_mingw option set)")
else:
print "*Compiling C Extensions inplace for portable distribution"
print("*Compiling C Extensions inplace for portable distribution")
cext_cmd = [sys.executable, #path to python.exe
'setup.py',
'build_ext', #make setup.py create a src distribution
@ -137,9 +138,9 @@ class OSXPortableBuild(Command):
#for teh target, instead of the source were building from)
Popen(cext_cmd, cwd=src_dist).communicate()
print "\nFinalizing Application Bundle"
print "---------------------------------------"
print "*Copying launcher script into the app bundle"
print("\nFinalizing Application Bundle")
print("---------------------------------------")
print("*Copying launcher script into the app bundle")
script_target = os.path.join(self.build_dir, 'portable-deps-osx',
'Kivy.app', 'Contents', 'Resources', 'script')
script = os.path.join(src_dist, 'kivy', 'tools', 'packaging',
@ -155,7 +156,7 @@ class OSXPortableBuild(Command):
version = self.dist_name.replace("Kivy-", "")
def write_plist(fn, target):
print "*Writing", fn
print("*Writing", fn)
plist_template = os.path.join(self.dist_dir, 'kivy', 'tools',
'packaging', 'osx', fn)
with open(plist_template, 'r') as fd:
@ -175,18 +176,18 @@ class OSXPortableBuild(Command):
'Contents', fn)
write_plist(fn, plist_target)
print "*Moving examples out of app bundle to be included in disk image"
print("*Moving examples out of app bundle to be included in disk image")
examples_target = os.path.join(self.build_dir, 'portable-deps-osx',
'examples')
examples = os.path.join(src_dist, 'examples')
shutil.move(examples, examples_target)
print "*Moving newly build kivy distribution into app bundle"
print("*Moving newly build kivy distribution into app bundle")
kivy_target = os.path.join(self.build_dir, 'portable-deps-osx',
'Kivy.app', 'Contents', 'Resources', 'kivy')
shutil.move(src_dist, kivy_target)
print "*Removing intermediate file"
print("*Removing intermediate file")
os.remove(os.path.join(self.build_dir, src_dist + '.tar.gz'))
shutil.rmtree(os.path.join(self.build_dir, '__MACOSX'),
ignore_errors=True)
@ -195,29 +196,29 @@ class OSXPortableBuild(Command):
dmg_dir = os.path.join(self.build_dir, 'portable-deps-osx')
vol_name = "Kivy"
print "\nCreating disk image for distribution"
print "---------------------------------------"
print "\nCreating intermediate DMG disk image: temp.dmg"
print "*checking how much space is needed for disk image..."
print("\nCreating disk image for distribution")
print("---------------------------------------")
print("\nCreating intermediate DMG disk image: temp.dmg")
print("*checking how much space is needed for disk image...")
du_cmd = 'du -sh %s' % dmg_dir
du_out = Popen(shlex.split(du_cmd), stdout=PIPE).communicate()[0]
size, unit = re.search('(\d+)(.*)\s+/.*', du_out).group(1, 2)
print " build needs at least %s%s." % (size, unit)
print(" build needs at least %s%s." % (size, unit))
size = int(size) + 10
print "*allocating %d%s for temp.dmg" % (size, unit, )
print "(volume name:%s)" % (vol_name, )
print("*allocating %d%s for temp.dmg" % (size, unit, ))
print("(volume name:%s)" % (vol_name, ))
create_dmg_cmd = 'hdiutil create -srcfolder %s -volname %s -fs HFS+ \
-fsargs "-c c=64,a=16,e=16" -format UDRW -size %d%s \
temp.dmg' % (dmg_dir, vol_name, size+10, unit)
Popen(shlex.split(create_dmg_cmd), cwd=self.build_dir).communicate()
print "*mounting intermediate disk image:"
print("*mounting intermediate disk image:")
mount_cmd = 'hdiutil attach -readwrite -noverify -noautoopen "temp.dmg"'
Popen(shlex.split(mount_cmd), cwd=self.build_dir,
stdout=PIPE).communicate()
print "*running Apple Script to configure DMG layout properties:"
print("*running Apple Script to configure DMG layout properties:")
dmg_config_script = """
tell application "Finder"
tell disk "%s"
@ -252,18 +253,18 @@ class OSXPortableBuild(Command):
end tell
end tell
""" % vol_name
print Popen(['osascript'], cwd=self.build_dir, stdin=PIPE,
stdout=PIPE).communicate(dmg_config_script)[0]
print(Popen(['osascript'], cwd=self.build_dir, stdin=PIPE,
stdout=PIPE).communicate(dmg_config_script)[0])
print "\nCreating final disk image"
print("\nCreating final disk image")
print "*unmounting intermediate disk image"
print("*unmounting intermediate disk image")
umount_cmd = 'hdiutil detach /Volumes/%s' % vol_name
Popen(shlex.split(umount_cmd), cwd=self.build_dir,
stdout=PIPE).communicate()
print "*compressing and finalizing disk image"
print("*compressing and finalizing disk image")
fn = os.path.join(self.dist_dir, self.dist_name + "-osx.dmg")
try:
@ -275,5 +276,5 @@ class OSXPortableBuild(Command):
Popen(shlex.split(convert_cmd), cwd=self.build_dir,
stdout=PIPE).communicate()
print "*Writing disk image, and cleaning build directory"
print("*Writing disk image, and cleaning build directory")
shutil.rmtree(self.build_dir, ignore_errors=True)

View File

@ -16,7 +16,7 @@ from kivy.factory import Factory
def get_modules():
return [x.get('module', None) for x in Factory.classes.itervalues()]
return [x.get('module', None) for x in Factory.classes.values()]
datas = [

Some files were not shown because too many files have changed in this diff Show More