3,479 data/em.py

This file was deleted.

@@ -45,7 +45,7 @@ def get_aboutcomputer():


def print_aboutcomputer():
print get_aboutcomputer()
print(get_aboutcomputer())


def _get_serial_number():
@@ -74,7 +74,7 @@ def print_serial_number():
serial_no = get_serial_number()
if serial_no is None:
serial_no = _not_available
print serial_no
print(serial_no)


def get_build_number():
@@ -87,12 +87,12 @@ def get_build_number():
try:
popen = subprocess.Popen(['lsb_release', '-ds'],
stdout=subprocess.PIPE)
except OSError, e:
except OSError as e:
if e.errno != errno.ENOENT:
raise
else:
build_no, stderr_ = popen.communicate()
build_no = build_no.strip()
build_no = build_no.strip().decode()

if build_no is None or not build_no:
build_no = _not_available
@@ -101,7 +101,7 @@ def get_build_number():


def print_build_number():
print get_build_number()
print(get_build_number())


def get_firmware_number():
@@ -154,7 +154,7 @@ def get_secondary_licenses():


def print_firmware_number():
print get_firmware_number()
print(get_firmware_number())


def get_wireless_firmware():
@@ -206,15 +206,15 @@ def get_wireless_firmware():
return _not_available

if len(firmware_info) == 1:
return firmware_info.values()[0]
return list(firmware_info.values())[0]

return ', '.join(['%(interface)s: %(info)s' %
{'interface': interface, 'info': info}
for interface, info in firmware_info.items()])
for interface, info in list(firmware_info.items())])


def print_wireless_firmware():
print get_wireless_firmware()
print(get_wireless_firmware())


def _read_file(path):
@@ -39,7 +39,7 @@ def get_nick():


def print_nick():
print get_nick()
print(get_nick())


def set_nick(nick):
@@ -48,8 +48,8 @@ def set_nick(nick):
"""
if not nick:
raise ValueError(_('You must enter a name.'))
if not isinstance(nick, unicode):
nick = unicode(nick, 'utf-8')
if not isinstance(nick, str):
nick = str(nick, 'utf-8')
settings = Gio.Settings('org.sugarlabs.user')
settings.set_string('nick', nick)
return 1
@@ -74,14 +74,14 @@ def print_color():
fill_tuple = (color, hue)

if stroke_tuple is not None:
print ('stroke: color=%s hue=%s') % (stroke_tuple[0],
stroke_tuple[1])
print(('stroke: color=%s hue=%s') % (stroke_tuple[0],
stroke_tuple[1]))
else:
print ('stroke: %s') % (tmp[0])
print(('stroke: %s') % (tmp[0]))
if fill_tuple is not None:
print ('fill: color=%s hue=%s') % (fill_tuple[0], fill_tuple[1])
print(('fill: color=%s hue=%s') % (fill_tuple[0], fill_tuple[1]))
else:
print ('fill: %s') % (tmp[1])
print(('fill: %s') % (tmp[1]))


def set_color(stroke, fill, stroke_modifier='medium', fill_modifier='medium'):
@@ -93,10 +93,10 @@ def set_color(stroke, fill, stroke_modifier='medium', fill_modifier='medium'):
"""

if stroke_modifier not in _MODIFIERS or fill_modifier not in _MODIFIERS:
print (_('Error in specified color modifiers.'))
print((_('Error in specified color modifiers.')))
return
if stroke not in _COLORS or fill not in _COLORS:
print (_('Error in specified colors.'))
print((_('Error in specified colors.')))
return

if stroke_modifier == fill_modifier:
@@ -189,7 +189,7 @@ def __init__(self, model, alerts):

self._nick_entry.connect('changed', self.__nick_changed_cb)

for picker in self._pickers.values():
for picker in list(self._pickers.values()):
picker.connect('color-changed', self.__color_changed_cb)

self._gender_pickers.connect('gender-changed',
@@ -353,7 +353,7 @@ def undo(self):
save_age(self._saved_age)

def _update_pickers(self, color):
for picker in self._pickers.values():
for picker in list(self._pickers.values()):
picker.props.color = color
self._gender_pickers.update_color(color)
self._age_pickers.update_color(color)
@@ -381,7 +381,7 @@ def __nick_timeout_cb(self, widget):
return False
try:
self._model.set_nick(widget.get_text())
except ValueError, detail:
except ValueError as detail:
self._nick_alert.props.msg = detail
self._nick_valid = False
self._nick_alert.show()
@@ -15,7 +15,6 @@

import os
import shutil
import statvfs
import tarfile
import logging
from datetime import datetime
@@ -28,8 +27,8 @@
from sugar3 import profile
from jarabe.journal import model

from backend_tools import Backend, PreConditionsError, PreConditionsChoose
from backend_tools import get_valid_file_name
from .backend_tools import Backend, PreConditionsError, PreConditionsChoose
from .backend_tools import get_valid_file_name

DIR_SIZE = 4096
DS_SOURCE_NAME = 'datastore'
@@ -209,7 +208,7 @@ def verify_preconditions(self, option=None):
raise PreConditionsError(_('Not enough space in disk'))

def _do_continue(self):
tarinfo = self._tarfile.next()
tarinfo = next(self._tarfile)
if tarinfo is not None:
self._tarfile.extract(tarinfo, path='/')
self._bytes += DIR_SIZE if tarinfo.isdir() else tarinfo.size
@@ -244,7 +243,7 @@ def cancel(self):

def _get_volume_space(path):
stat = os.statvfs(path)
return stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL]
return stat[0] * stat[4]


def _get_datastore_size():
@@ -47,7 +47,7 @@ def __init__(self):
module = _load_module(module_name)
if module is not None:
if hasattr(module, 'get_name'):
logging.error('FOUND BACKEND %s', module.get_name())
logging.debug('FOUND BACKEND %s', module.get_name())
self._backends.append(module)

def get_backends(self):
@@ -66,7 +66,7 @@ def need_stop_activities(self):
def _load_module(module):
try:
module = import_module('%s.%s' % (BACKENDS_MODULE, module))
except ImportError, e:
except ImportError as e:
module = None
logging.error('ImportError: %s' % (e))
return module
@@ -28,10 +28,10 @@

from jarabe.controlpanel.sectionview import SectionView

from backupmanager import BackupManager
from backupmanager import OPERATION_BACKUP, OPERATION_RESTORE
from backends.backend_tools import PreConditionsError
from backends.backend_tools import PreConditionsChoose
from .backupmanager import BackupManager
from .backupmanager import OPERATION_BACKUP, OPERATION_RESTORE
from .backends.backend_tools import PreConditionsError
from .backends.backend_tools import PreConditionsChoose


class BackupView(SectionView):
@@ -50,7 +50,7 @@ def read_all_timezones(fn=_zone_tab):
timezones.append(line[2])
timezones.sort()

for offset in xrange(-12, 15):
for offset in range(-12, 15):
if offset < 0:
tz = 'UTC%d' % offset
elif offset > 0:
@@ -67,7 +67,7 @@ def get_timezone():


def print_timezone():
print get_timezone()
print(get_timezone())


def fix_UTC_time_zone(timezone):
@@ -25,7 +25,7 @@ def get_corner_delay():


def print_corner_delay():
print get_corner_delay()
print(get_corner_delay())


def set_corner_delay(delay):
@@ -44,7 +44,7 @@ def get_edge_delay():


def print_edge_delay():
print get_edge_delay()
print(get_edge_delay())


def set_edge_delay(delay):
@@ -63,7 +63,7 @@ def get_trigger_size():


def print_trigger_size():
print '{}px'.format(get_trigger_size())
print('{}px'.format(get_trigger_size()))


def set_trigger_size(size):
@@ -30,7 +30,7 @@

def read_all_languages():
fdp = subprocess.Popen(['locale', '-av'], stdout=subprocess.PIPE)
lines = fdp.stdout.read().split('\n')
lines = fdp.stdout.read().decode().split('\n')
locales = []

for line in lines:
@@ -142,12 +142,12 @@ def print_languages():
found_lang = False
for lang in languages:
if lang[2].split('.')[0] == code.split('.')[0]:
print lang[0].replace(' ', '_') + '/' + \
lang[1].replace(' ', '_')
print(lang[0].replace(' ', '_') + '/' + \
lang[1].replace(' ', '_'))
found_lang = True
break
if not found_lang:
print (_('Language for code=%s could not be determined.') % code)
print((_('Language for code=%s could not be determined.') % code))


def set_languages(languages):
@@ -170,7 +170,7 @@ def set_languages(languages):
if code == languages:
set_languages_list([locale_str])
return 1
print (_("Sorry I do not speak \'%s\'.") % languages)
print((_("Sorry I do not speak \'%s\'.") % languages))


def set_languages_list(languages):
@@ -140,7 +140,7 @@ def _add_row(self, locale_code=None):
locale_country = country

language_palette = []
key_list = self._language_dict.keys()
key_list = list(self._language_dict.keys())
for language_key in sorted(key_list):
language_palette.append(
{'label': self._language_dict[language_key],
@@ -327,7 +327,7 @@ def __remove_button_clicked_cb(self, button):
def _language_changed(self, widget, event, item):
i = item['index']

for language_key in self._language_dict.keys():
for language_key in list(self._language_dict.keys()):
if self._language_dict[language_key] == item['label']:
new_country_list = \
self._build_country_list(language_key, idx=i)
@@ -215,7 +215,7 @@ def __init__(self):
# Check service provider database file exists
try:
tree = ElementTree(file=PROVIDERS_PATH)
except (IOError, SyntaxError), e:
except (IOError, SyntaxError) as e:
msg = ("Mobile broadband provider database: Could not read "
"provider information %s error=%s") % (PROVIDERS_PATH, e)
logging.warning(msg)
@@ -317,7 +317,7 @@ def _get_initial_config(self):

provider_name = self._settings.get_string(CONF_SP_PROVIDER)
if not provider_name:
provider_name = u''
provider_name = ''
else:
provider_name = provider_name.decode('utf-8')

@@ -15,8 +15,6 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

import logging

import gi
gi.require_version('NM', '1.0')
from gettext import gettext as _
@@ -62,7 +60,7 @@ def get_jabber():


def print_jabber():
print get_jabber()
print(get_jabber())


def set_jabber(server):
@@ -82,7 +80,7 @@ def get_radio():


def print_radio():
print ('off', 'on')[get_radio()]
print(('off', 'on')[get_radio()])


def set_radio(state):
@@ -119,7 +117,7 @@ def get_publish_information():


def print_publish_information():
print get_publish_information()
print(get_publish_information())


def set_publish_information(value):
@@ -597,7 +597,7 @@ def setup(self):

try:
radio_state = self._model.get_radio()
except self._model.ReadError, detail:
except self._model.ReadError as detail:
self._radio_alert.props.msg = detail
self._radio_alert.show()
else:
@@ -675,15 +675,15 @@ def _verify_settings(self):
icon.show()

def _apply_proxy_settings(self):
for setting in self._proxy_settings.values():
for setting in list(self._proxy_settings.values()):
if (Gio.Settings.get_has_unapplied(setting)):
setting.apply()

def apply(self):
self._apply_jabber(self._entry.get_text())
self._model.set_social_help(self._social_help_entry.get_text())
settings_changed = False
for setting in self._proxy_settings.values():
for setting in list(self._proxy_settings.values()):
if (Gio.Settings.get_has_unapplied(setting)):
settings_changed = True
if settings_changed:
@@ -697,9 +697,9 @@ def apply(self):
def undo(self):
self._button.disconnect(self._radio_change_handler)
self._radio_alert.hide()
for setting in self._proxy_settings.values():
for setting in list(self._proxy_settings.values()):
setting.revert()
for alert in self._proxy_inline_alerts.values():
for alert in list(self._proxy_inline_alerts.values()):
alert.hide()

def _validate(self):
@@ -712,7 +712,7 @@ def __radio_toggled_cb(self, widget, data=None):
radio_state = widget.get_active()
try:
self._model.set_radio(radio_state)
except self._model.ReadError, detail:
except self._model.ReadError as detail:
self._radio_alert.props.msg = detail
self._radio_valid = False
else:
@@ -55,7 +55,7 @@ def get_automatic_pm():


def print_automatic_pm():
print ('off', 'on')[get_automatic_pm()]
print(('off', 'on')[get_automatic_pm()])


def set_automatic_pm(enabled):
@@ -88,7 +88,7 @@ def __init__(self, model, alerts):
def setup(self):
try:
automatic_state = self._model.get_automatic_pm()
except Exception, detail:
except Exception as detail:
self._automatic_pm_alert.props.msg = detail
self._automatic_pm_alert.show()
else:
@@ -114,8 +114,8 @@ def __automatic_pm_toggled_cb(self, widget, data=None):
state = widget.get_active()
try:
self._model.set_automatic_pm(state)
except Exception, detail:
print detail
except Exception as detail:
print(detail)
self._automatic_pm_alert.props.msg = detail
else:
self._automatic_pm_valid = True
@@ -515,8 +515,8 @@ def _update_properties(self, properties):
self._color = profile.get_color()
else:
sha_hash = hashlib.sha1()
data = self._ssid + hex(self._flags)
sha_hash.update(data)
data = self._ssid.decode() + hex(self._flags)
sha_hash.update(data.encode('utf-8'))
digest = hash(sha_hash.digest())
index = digest % len(xocolor.colors)

@@ -129,7 +129,7 @@ def _write_touchpad_mode_str(mode_str):
""" Write the touchpad mode to the node path. """
try:
node_file_handle = open(NODE_PATH, 'w')
except IOError, e:
except IOError as e:
logging.error('Error opening %s for writing: %s', NODE_PATH, e)
return
node_file_handle.write(mode_str)
@@ -17,6 +17,7 @@
import os
import struct
import time
import binascii

import dbus
from gi.repository import GLib
@@ -287,7 +288,7 @@ def __init__(self):
self._server = Server()
self._server.connect("session-started", self._session_started_cb)
self._port = self._server.start()
self._key = os.urandom(16).encode("hex")
self._key = binascii.hexlify(os.urandom(16)).decode()

self._apis = {}
self._apis["activity"] = ActivityAPI
@@ -298,7 +299,7 @@ def setup_environment(self):
os.environ["SUGAR_APISOCKET_KEY"] = self._key

def _open_stream(self, client, request):
for stream_id in xrange(0, 255):
for stream_id in range(0, 255):
if stream_id not in client.stream_monitors:
client.stream_monitors[stream_id] = StreamMonitor()
break
@@ -35,7 +35,7 @@ def cmd_help():
"""Print the help to the screen"""
# TRANS: Translators, there's a empty line at the end of this string,
# which must appear in the translated string (msgstr) as well.
print _('Usage: sugar-control-panel [ option ] key [ args ... ] \n\
print(_('Usage: sugar-control-panel [ option ] key [ args ... ] \n\
Control for the sugar environment. \n\
Options: \n\
-h show this help message and exit \n\
@@ -44,13 +44,13 @@ def cmd_help():
-g key get the current value of the key \n\
-s key set the current value for the key \n\
-c key clear the current value for the key \n\
')
'))


def note_restart():
"""Instructions how to restart sugar"""
print _('To apply your changes you have to restart Sugar.\n' +
'Hit ctrl+alt+erase on the keyboard to trigger a restart.')
print(_('To apply your changes you have to restart Sugar.\n' +
'Hit ctrl+alt+erase on the keyboard to trigger a restart.'))


def load_modules():
@@ -96,22 +96,22 @@ def main():
if method:
found += 1
if found == 1:
print method.__doc__
print(method.__doc__)
else:
print _same_option_warning % \
{'key': key, 'module': module}
print(_same_option_warning % \
{'key': key, 'module': module})
if found == 0:
print _no_option_error % key
print(_no_option_error % key)
if option in ('-l'):
for module in modules:
methods = dir(module)
print '%s:' % module.__name__.split('.')[1]
print('%s:' % module.__name__.split('.')[1])
for method in methods:
if method.startswith('get_'):
print ' %s' % method[4:]
print(' %s' % method[4:])
elif method.startswith('clear_'):
print ' %s (use the -c argument with this option)' \
% method[6:]
print(' %s (use the -c argument with this option)' \
% method[6:])
if option in ('-g'):
for module in modules:
method = getattr(module, 'print_' + key, None)
@@ -121,12 +121,12 @@ def main():
try:
method()
except Exception as detail:
print _general_error % detail
print(_general_error % detail)
else:
print _same_option_warning % \
{'key': key, 'module': module}
print(_same_option_warning % \
{'key': key, 'module': module})
if found == 0:
print _no_option_error % key
print(_no_option_error % key)
if option in ('-s'):
for module in modules:
method = getattr(module, 'set_' + key, None)
@@ -137,14 +137,14 @@ def main():
try:
note = method(*args)
except Exception as detail:
print _general_error % detail
print(_general_error % detail)
if note == _RESTART:
note_restart()
else:
print _same_option_warning % \
{'key': key, 'module': module}
print(_same_option_warning % \
{'key': key, 'module': module})
if found == 0:
print _no_option_error % key
print(_no_option_error % key)
if option in ('-c'):
for module in modules:
method = getattr(module, 'clear_' + key, None)
@@ -155,11 +155,11 @@ def main():
try:
note = method(*args)
except Exception as detail:
print _general_error % detail
print(_general_error % detail)
if note == _RESTART:
note_restart()
else:
print _same_option_warning % \
{'key': key, 'module': module}
print(_same_option_warning % \
{'key': key, 'module': module})
if found == 0:
print _no_option_error % key
print(_no_option_error % key)
@@ -197,7 +197,7 @@ def _setup_options(self):
row = 0
column = 2

options = self._options.keys()
options = list(self._options.keys())
options.sort()

for option in options:
@@ -497,7 +497,7 @@ def __getattr__(self, name):
return getattr(self._module, name)

def undo(self):
for key in self._options.keys():
for key in list(self._options.keys()):
method = getattr(self._module, 'set_' + key, None)
if method and self._options[key] is not None:
try:
@@ -243,14 +243,18 @@ def set_filter(self, query):
of matching activities.
"""
self._query = normalize_string(query.decode('utf-8'))
if isinstance(query, bytes):
query = query.decode()
self._query = normalize_string(query)
self.get_model().refilter()
matches = self.get_model().iter_n_children(None)
return matches

def __model_visible_cb(self, model, tree_iter, data):
title = model[tree_iter][self._model.column_title]
title = normalize_string(title.decode('utf-8'))
if isinstance(title, bytes):
title = title.decode('utf-8')
title = normalize_string(title)
return title is not None and title.find(self._query) > -1

def create_palette(self, path, column):
@@ -243,7 +243,7 @@ def allocate_children(self, allocation, children):
x = min(x, allocation.width - child_requisition.width)
y = min(y, allocation.height - child_requisition.height)
elif hasattr(child, 'get_bundle_id'):
name_hash = hashlib.md5(child.get_bundle_id())
name_hash = hashlib.md5(child.get_bundle_id().decode())
x = int(name_hash.hexdigest()[:5], 16) % \
(allocation.width - child_requisition.width)
y = int(name_hash.hexdigest()[-5:], 16) % \
@@ -396,7 +396,7 @@ def _calculate_angle_and_radius(self, icon_count, icon_size):
def allocate_children(self, allocation, children):
radius, icon_size = self._calculate_radius_and_icon_size(len(children))

children.sort(self.compare_activities)
children.sort(key = lambda x:(x.get_activity_name().lower(), x.get_activity_name()))
height = allocation.height + allocation.y
for n in range(len(children)):
child = children[n]
@@ -423,9 +423,6 @@ def allocate_children(self, allocation, children):
child_allocation.height = new_height
child.size_allocate(child_allocation)

def compare_activities(self, icon_a, icon_b):
return cmp(icon_a.get_activity_name(), icon_b.get_activity_name())


_SUNFLOWER_CONSTANT = style.STANDARD_ICON_SIZE * .75
"""Chose a constant such that STANDARD_ICON_SIZE icons are nicely spaced."""
@@ -358,7 +358,9 @@ def set_filter(self, query):
query = query.strip()
for icon in self.get_children():
if icon not in [self._owner_icon, self._activity_icon]:
activity_name = icon.get_activity_name().decode('utf-8')
activity_name = icon.get_activity_name()
if isinstance(activity_name, bytes):
activity_name = activity_name.decode()
normalized_name = normalize_string(activity_name)
if normalized_name.find(query) > -1:
icon.alpha = 1.0
@@ -370,7 +372,9 @@ def _get_selected(self, query):
selected = []
for icon in self.get_children():
if icon not in [self._owner_icon, self._activity_icon]:
activity_name = icon.get_activity_name().decode('utf-8')
activity_name = icon.get_activity_name()
if isinstance(activity_name, bytes):
activity_name = activity_name.decode()
normalized_name = normalize_string(activity_name)
if normalized_name.find(query) > -1:
selected.append(icon)
@@ -70,7 +70,7 @@ def _friend_removed_cb(self, data_model, key):
icon.destroy()

def _toolbar_query_changed_cb(self, toolbar, query):
self._query = normalize_string(query.decode('utf-8'))
self._query = normalize_string(query)
for icon in self.get_children():
if hasattr(icon, 'set_filter'):
icon.set_filter(self._query)
@@ -84,7 +84,7 @@ def __desktop_view_icons_changed_cb(self, model):
(self._list_view_index))

def __toolbar_query_changed_cb(self, toolbar, query):
self._query = normalize_string(query.decode('utf-8'))
self._query = normalize_string(query)
self._list_view.set_filter(self._query)
for i in range(desktop.get_number_of_views()):
self._favorites_boxes[i].set_filter(self._query)
@@ -197,8 +197,8 @@ def _get_security(self):

def print_security(self):
(key, auth_alg) = self._get_security()
print 'Key: %s' % key
print 'Auth: %d' % auth_alg
print('Key: %s' % key)
print('Auth: %d' % auth_alg)

def create_security(self):
(key, auth_alg) = self._get_security()
@@ -254,7 +254,7 @@ def _get_security(self):

def print_security(self):
key = self._get_security()
print 'Key: %s' % key
print('Key: %s' % key)

def create_security(self):
wsec = {'psk': self._get_security()}
@@ -163,7 +163,7 @@ def set_filter(self, query):
self._icon.alpha = _FILTERED_ALPHA
else:
self._icon.alpha = 1.0
for icon in self._icons.itervalues():
for icon in list(self._icons.values()):
if hasattr(icon, 'set_filter'):
icon.set_filter(query)

@@ -284,7 +284,7 @@ def __secrets_request_cb(self, **kwargs):
'SpecificObject')
found = False
if ap_o != '/':
for net in self._box.wireless_networks.values():
for net in list(self._box.wireless_networks.values()):
if net.find_ap(ap_o) is not None:
found = True
net.create_keydialog(kwargs['response'])
@@ -509,7 +509,8 @@ def _ap_props_changed_cb(self, ap, old_hash_value):
hash_value = ap.network_hash()
if old_hash_value == hash_value:
# no change in network identity, so just update signal strengths
self.wireless_networks[hash_value].update_strength()
if hash_value in self.wireless_networks:
self.wireless_networks[hash_value].update_strength()
return

# properties change includes a change of the identity of the network
@@ -532,7 +533,7 @@ def remove_access_point(self, ap_o):

# we don't keep an index of ap object path to network, but since
# we'll only ever have a handful of networks, just try them all...
for net in self.wireless_networks.values():
for net in list(self.wireless_networks.values()):
ap = net.find_ap(ap_o)
if not ap:
continue
@@ -581,7 +582,7 @@ def enable_olpc_mesh(self, mesh_device):

# the OLPC mesh can be recognised as a "normal" wifi network. remove
# any such normal networks if they have been created
for hash_value, net in self.wireless_networks.iteritems():
for hash_value, net in list(self.wireless_networks.items()):
if not net.is_olpc_mesh():
continue

@@ -600,17 +601,17 @@ def disable_olpc_mesh(self, mesh_device):
def suspend(self):
if not self._suspended:
self._suspended = True
for net in self.wireless_networks.values() + self._mesh:
for net in list(self.wireless_networks.values()) + self._mesh:
net.props.paused = True

def resume(self):
if self._suspended:
self._suspended = False
for net in self.wireless_networks.values() + self._mesh:
for net in list(self.wireless_networks.values()) + self._mesh:
net.props.paused = False

def _toolbar_query_changed_cb(self, toolbar, query):
self._query = normalize_string(query.decode('utf-8'))
self._query = normalize_string(query)
for icon in self.get_children():
if hasattr(icon, 'set_filter'):
icon.set_filter(self._query)
@@ -79,8 +79,8 @@ def __init__(self, initial_ap):
self._color = profile.get_color()
else:
sha_hash = hashlib.sha1()
data = self._ssid + hex(self._flags)
sha_hash.update(data)
data = self._ssid.decode() + hex(self._flags)
sha_hash.update(data.encode('utf-8'))
digest = hash(sha_hash.digest())
index = digest % len(xocolor.colors)

@@ -204,7 +204,7 @@ def _update_icon(self):
if self._mode == network.NM_802_11_MODE_ADHOC and \
network.is_sugar_adhoc_network(self._ssid):
channel = max([1] + [ap.channel for ap in
self._access_points.values()])
list(self._access_points.values())])
if self._device_state == network.NM_DEVICE_STATE_ACTIVATED and \
self._active_ap is not None:
icon_name = 'network-adhoc-%s-connected' % channel
@@ -297,7 +297,7 @@ def _update_color(self):
self.props.alpha = 1.0

def __disconnect_activate_cb(self, item):
ap_paths = self._access_points.keys()
ap_paths = list(self._access_points.keys())
network.disconnect_access_points(ap_paths)

def __forget_activate_cb(self, item):
@@ -422,7 +422,7 @@ def update_strength(self):
# display the strength of the strongest AP that makes up this
# network, also considering that there may be no APs
new_strength = max([0] + [ap.strength for ap in
self._access_points.values()])
list(self._access_points.values())])

if new_strength != self._strength:
self._strength = new_strength
@@ -450,14 +450,14 @@ def find_ap(self, ap_path):
return self._access_points[ap_path]

def get_first_ap(self):
return self._access_points.values()[0]
return list(self._access_points.values())[0]

def is_olpc_mesh(self):
return self._mode == network.NM_802_11_MODE_ADHOC \
and self._ssid == 'olpc-mesh'

def remove_all_aps(self):
for ap in self._access_points.values():
for ap in list(self._access_points.values()):
ap.disconnect()
self._access_points = {}
self._active_ap = None
@@ -15,9 +15,9 @@

import logging
from gettext import gettext as _
import xmlrpclib
import xmlrpc.client
import socket
import httplib
import http.client
import os
from string import ascii_uppercase
import random
@@ -87,7 +87,7 @@ class RegisterError(Exception):
pass


class _TimeoutHTTP(httplib.HTTP):
class _TimeoutHTTP(http.client.HTTPConnection):

def __init__(self, host='', port=None, strict=None, timeout=None):
if port == 0:
@@ -99,7 +99,7 @@ def __init__(self, host='', port=None, strict=None, timeout=None):
port, strict, timeout=_REGISTER_TIMEOUT))


class _TimeoutTransport(xmlrpclib.Transport):
class _TimeoutTransport(xmlrpc.client.Transport):

def make_connection(self, host):
host, extra_headers, x509_ = self.get_host_info(host)
@@ -132,13 +132,13 @@ def register_laptop(url=_REGISTER_URL):
url = 'http://' + jabber_server + ':8080/'

if sys.hexversion < 0x2070000:
server = xmlrpclib.ServerProxy(url, _TimeoutTransport())
server = xmlrpc.client.ServerProxy(url, _TimeoutTransport())
else:
socket.setdefaulttimeout(_REGISTER_TIMEOUT)
server = xmlrpclib.ServerProxy(url)
server = xmlrpc.client.ServerProxy(url)
try:
data = server.register(sn, nick, uuid_, profile.pubkey)
except (xmlrpclib.Error, TypeError, socket.error):
except (xmlrpc.client.Error, TypeError, socket.error):
logging.exception('Registration: cannot connect to server')
raise RegisterError(_('Cannot connect to the server.'))
finally:
@@ -37,7 +37,7 @@ def __init__(self):
def do_realize(self):
self.set_realized(True)
self.set_window(self.get_parent_window())
for child in self._children.keys():
for child in list(self._children.keys()):
child.set_parent_window(self.get_parent_window())
self.queue_resize()

@@ -47,7 +47,7 @@ def do_add(self, child):
child.set_parent(self)

def do_forall(self, include_internals, callback):
for child in self._children.keys():
for child in list(self._children.keys()):
callback(child)

def do_remove(self, child):
@@ -91,7 +91,7 @@ def do_size_allocate(self, allocation):
r = self._get_radius()
index = 0

for child, centered in self._children.items():
for child, centered in list(self._children.items()):
child_request = child.size_request()
child_width, child_height = \
child_request.width, child_request.height
@@ -124,7 +124,7 @@ def do_size_allocate(self, allocation):

def _get_radius(self):
radius = int(_BASE_DISTANCE + _CHILDREN_FACTOR * self._nflakes)
for child, centered in self._children.items():
for child, centered in list(self._children.items()):
if centered:
child_request = child.size_request()
child_width, child_height = \
@@ -135,7 +135,7 @@ def _get_radius(self):

def _calculate_size(self):
thickness = 0
for child in self._children.keys():
for child in list(self._children.keys()):
child_request = child.size_request()
child_width, child_height = \
child_request.width, child_request.height
@@ -147,6 +147,8 @@ def _entry_activated_cb(self, entry):
new_query = entry.props.text
if self._query != new_query:
self._query = new_query
if isinstance(self._query, bytes):
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pro-panda why did you add this line in the code,because it not not related to this issue of porting to a different version @quozl Your suggestions will also be helpful

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@manddy, thanks for asking. The change seems common to me. @pro-panda didn't explain the change in the commit message. I'm not sure why the change is needed though. I've no suggestions.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for asking @manddy.
Most of such changes were introduced since sugarlabs/sugar-toolkit-gtk3#383 supported both Python 2 and 3, which implied that you could expect bytes or unicode, depending on the version an interacting sugar activity is written in.

From what I recall, this instance was also implemented for a similar reason.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, of course, thanks.

self._query = self._query.decode()
self.emit('query-changed', self._query)

def _entry_changed_cb(self, entry):
@@ -16,7 +16,7 @@
import logging
import os
import shutil
import urlparse
import urllib.parse
import tempfile

from gi.repository import GObject
@@ -37,9 +37,9 @@ class Clipboard(GObject.GObject):
'object-added': (GObject.SignalFlags.RUN_FIRST, None,
([object])),
'object-deleted': (GObject.SignalFlags.RUN_FIRST, None,
([long])),
([int])),
'object-selected': (GObject.SignalFlags.RUN_FIRST, None,
([long])),
([int])),
'object-state-changed': (GObject.SignalFlags.RUN_FIRST, None,
([object])),
}
@@ -123,18 +123,18 @@ def set_object_percent(self, object_id, percent):

def _process_object(self, cb_object):
formats = cb_object.get_formats()
for format_name, format_ in formats.iteritems():
for format_name, format_ in list(formats.items()):
if format_.is_on_disk() and not format_.owns_disk_data:
new_uri = self._copy_file(format_.get_data())
format_.set_data(new_uri)

# Add a text/plain format to objects that are text but lack it
if 'text/plain' not in formats.keys():
if 'UTF8_STRING' in formats.keys():
if 'text/plain' not in list(formats.keys()):
if 'UTF8_STRING' in list(formats.keys()):
self.add_object_format(
cb_object.get_id(), 'text/plain',
data=formats['UTF8_STRING'].get_data(), on_disk=False)
elif 'text/unicode' in formats.keys():
elif 'text/unicode' in list(formats.keys()):
self.add_object_format(
cb_object.get_id(), 'text/plain',
data=formats['UTF8_STRING'].get_data(), on_disk=False)
@@ -150,7 +150,7 @@ def get_object_data(self, object_id, format_type):
return format_

def _copy_file(self, original_uri):
uri = urlparse.urlparse(original_uri)
uri = urllib.parse.urlparse(original_uri)
path = uri.path # pylint: disable=E1101
directory_, file_name = os.path.split(path)

@@ -197,7 +197,7 @@ def _notify_active_cb(self, widget, pspec):

def _get_targets(self):
targets = []
for format_type in self._cb_object.get_formats().keys():
for format_type in list(self._cb_object.get_formats().keys()):
targets.append(Gtk.TargetEntry.new(format_type,
Gtk.TargetFlags.SAME_APP, 0))
return targets
@@ -15,7 +15,7 @@

from gettext import gettext as _
import tempfile
import urlparse
import urllib.parse
import os
import logging
from gi.repository import Gio
@@ -187,15 +187,15 @@ def _write_to_temp_file(self, data):
return file_path

def _copy_to_journal(self):
formats = self._cb_object.get_formats().keys()
formats = list(self._cb_object.get_formats().keys())
most_significant_mime_type = mime.choose_most_significant(formats)
format_ = self._cb_object.get_formats()[most_significant_mime_type]

transfer_ownership = False
if most_significant_mime_type == 'text/uri-list':
uri = format_.get_data()
if uri.startswith('file://'):
parsed_url = urlparse.urlparse(uri)
parsed_url = urllib.parse.urlparse(uri)
file_path = parsed_url.path # pylint: disable=E1101
transfer_ownership = False
mime_type = mime.get_for_file(file_path)
@@ -205,7 +205,7 @@ def _copy_to_journal(self):
mime_type = 'text/uri-list'
else:
if format_.is_on_disk():
parsed_url = urlparse.urlparse(format_.get_data())
parsed_url = urllib.parse.urlparse(format_.get_data())
file_path = parsed_url.path # pylint: disable=E1101
transfer_ownership = False
mime_type = mime.get_for_file(file_path)
@@ -15,7 +15,7 @@

import os
import logging
import urlparse
import urllib.parse
from gi.repository import Gio
from gi.repository import Gtk

@@ -33,7 +33,7 @@ def __init__(self, object_path, name):
self._formats = {}

def destroy(self):
for format_ in self._formats.itervalues():
for format_ in list(self._formats.values()):
format_.destroy()

def get_id(self):
@@ -83,7 +83,7 @@ def is_bundle(self):
if not self._formats:
return False
else:
return self._formats.keys()[0] == ActivityBundle.MIME_TYPE
return list(self._formats.keys())[0] == ActivityBundle.MIME_TYPE

def get_percent(self):
return self._percent
@@ -101,10 +101,10 @@ def get_mime_type(self):
if not self._formats:
return ''

format_ = mime.choose_most_significant(self._formats.keys())
format_ = mime.choose_most_significant(list(self._formats.keys()))
if format_ == 'text/uri-list':
uri_data = self._formats[format_].get_data()
uri = urlparse.urlparse(uri_data, 'file')
uri = urllib.parse.urlparse(uri_data, 'file')
scheme = uri.scheme # pylint: disable=E1101
if scheme == 'file':
path = uri.path # pylint: disable=E1101
@@ -128,7 +128,7 @@ def __init__(self, mime_type, data, on_disk):

def destroy(self):
if self._on_disk:
uri = urlparse.urlparse(self._data)
uri = urllib.parse.urlparse(self._data)
path = uri.path # pylint: disable=E1101
if os.path.isfile(path):
os.remove(path)
@@ -14,7 +14,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import logging
from urlparse import urlparse
from urllib.parse import urlparse
import hashlib

from gi.repository import Gtk
@@ -70,7 +70,7 @@ def __init__(self):
cb_service.connect('object-deleted', self._object_deleted_cb)

def owns_clipboard(self):
for icon in self._icons.values():
for icon in list(self._icons.values()):
if icon.owns_clipboard:
return True
return False
@@ -105,7 +105,7 @@ def _add_selection(self, object_id, selection):

def _object_added_cb(self, cb_service, cb_object):
if self._icons:
group = self._icons.values()[0]
group = list(self._icons.values())[0]
else:
group = None

@@ -146,13 +146,13 @@ def _drag_leave_cb(self, widget, drag_context, timestamp):
return True

def show(self):
for box in self._boxes.itervalues():
for box in list(self._boxes.values()):
box.show()

def hide(self):
for box in self._boxes.itervalues():
for box in list(self._boxes.values()):
box.hide()

def _window_stacking_changed_cb(self, screen):
for box in self._boxes.itervalues():
for box in list(self._boxes.values()):
box.get_window().raise_()
@@ -18,7 +18,7 @@
import logging
from gettext import gettext as _
import pwd
import commands
import subprocess

from gi.repository import Gtk
from gi.repository import Gdk
@@ -81,7 +81,7 @@ def create_profile(user_profile):
logging.debug("Generating user keypair")

cmd = "ssh-keygen -q -t dsa -f %s -C '' -N ''" % (keypath, )
(s, o) = commands.getstatusoutput(cmd)
(s, o) = subprocess.getstatusoutput(cmd)
if s != 0:
logging.error('Could not generate key pair: %d %s', s, o)

@@ -365,7 +365,7 @@ def _setup_age_page(self):
button_box.show()

if not self.PAGES[self._page]:
self.next()
next(self)

def _update_next_button(self):
self._next_button.set_sensitive(self._current_page.props.valid)
@@ -382,9 +382,9 @@ def back(self):
self._setup_page()

def _next_activated_cb(self, widget):
self.next()
next(self)

def next(self):
def __next__(self):
if self._current_page.props.valid or not self.PAGES[self._page]:
if self._page == self.PAGE_LAST:
self.done()
@@ -446,7 +446,7 @@ def _create_profile_cb(self, user_profile):

def __key_press_cb(self, widget, event):
if Gdk.keyval_name(event.keyval) == 'Return':
self._intro_box.next()
next(self._intro_box)
return True
elif Gdk.keyval_name(event.keyval) == 'Escape':
self._intro_box.back()
@@ -446,7 +446,7 @@ def _create_buddy_list(self):
vbox.pack_start(halign, False, False, 0)

if self._metadata.get('buddies'):
buddies = json.loads(self._metadata['buddies']).values()
buddies = list(json.loads(self._metadata['buddies']).values())
vbox.pack_start(BuddyList(buddies), False, False, 0)
return vbox
else:
@@ -25,7 +25,6 @@
from gi.repository import GdkX11
from gi.repository import Gio
import dbus
import statvfs
import os

from sugar3.graphics.alert import ErrorAlert
@@ -549,7 +548,7 @@ def _check_available_space(self):
if self._critical_space_alert:
return
stat = os.statvfs(env.get_profile_path())
free_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL]
free_space = stat[0] * stat[4]
if free_space < (_SPACE_THRESHOLD * 1024 * 1024):
self._critical_space_alert = ModalAlert()
self._critical_space_alert.connect('destroy',
@@ -458,13 +458,7 @@ def refresh_filters(self):
'callback': self._what_palette_cb,
'id': bundle_id})
finally:
def _cmp(a, b):
if a['label'] < b['label']:
return -1
else:
return 1

for item in sorted(what_list_activities, _cmp):
for item in sorted(what_list_activities, key = lambda x:x['label']):
self._what_list.append(item)

if self._what_widget_contents is not None:
@@ -214,7 +214,7 @@ def do_get_value(self, iterator, column):
buddies = []
if metadata.get('buddies'):
try:
buddies = json.loads(metadata['buddies']).values()
buddies = list(json.loads(metadata['buddies']).values())
except json.decoder.JSONDecodeError as exception:
logging.warning('Cannot decode buddies for %r: %s',
metadata['uid'], exception)
@@ -224,7 +224,7 @@ def do_get_value(self, iterator, column):
metadata['uid'], buddies)
buddies = []

for n_ in xrange(0, 3):
for n_ in range(0, 3):
if buddies:
try:
nick, color = buddies.pop(0)
@@ -291,9 +291,8 @@ def setup_ready(self):
else:
# timestamp
keygetter = itemgetter(2)
self._file_list.sort(lambda a, b: cmp(b, a),
key=keygetter,
reverse=(self._sort[0] == '-'))
self._file_list.sort(key=keygetter,
reverse=not self._sort[0] == '-')
self.ready.send(self)

def find(self, query):
@@ -949,7 +948,7 @@ def get_documents_path():
try:
pipe = subprocess.Popen(['xdg-user-dir', 'DOCUMENTS'],
stdout=subprocess.PIPE)
documents_path = os.path.normpath(pipe.communicate()[0].strip())
documents_path = os.path.normpath(pipe.communicate()[0].strip().decode())
if os.path.exists(documents_path) and \
os.environ.get('HOME') != documents_path:
_documents_path = documents_path
@@ -16,15 +16,14 @@

import logging
import os
import statvfs
from gettext import gettext as _

from gi.repository import GObject
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import Gtk
from gi.repository import Gdk
import cPickle
import pickle
import xapian
import json
import tempfile
@@ -100,8 +99,8 @@ def _convert_entries(root):

def _convert_entry(root, document):
try:
metadata_loaded = cPickle.loads(document.get_data())
except cPickle.PickleError as e:
metadata_loaded = pickle.loads(document.get_data())
except pickle.PickleError as e:
logging.debug('Convert DS-0 Journal entries: '
'error converting metadata: %s', e)
return
@@ -117,7 +116,7 @@ def _convert_entry(root, document):
if uid is None:
return

for key, value in metadata_loaded.items():
for key, value in list(metadata_loaded.items()):
metadata[str(key)] = str(value[0])

if 'uid' not in metadata:
@@ -368,8 +367,8 @@ def __init__(self, mount):

def __popup_cb(self, palette):
stat = os.statvfs(env.get_profile_path())
free_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL]
total_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BLOCKS]
free_space = stat[0] * stat[4]
total_space = stat[0] * stat[2]

fraction = (total_space - free_space) / float(total_space)
self._progress_bar.props.fraction = fraction
@@ -28,11 +28,6 @@
import subprocess
import shutil

# Change the default encoding to avoid UnicodeDecodeError
# http://lists.sugarlabs.org/archive/sugar-devel/2012-August/038928.html
reload(sys)
sys.setdefaultencoding('utf-8')

# Disable overlay scrolling before GTK is loaded
os.environ['GTK_OVERLAY_SCROLLING'] = '0'
os.environ['LIBOVERLAY_SCROLLBAR'] = '0'
@@ -247,7 +242,7 @@ def cleanup_temporary_files():
except OSError as e:
# temporary files cleanup is not critical; it should not prevent
# sugar from starting if (for example) the disk is full or read-only.
print 'temporary files cleanup failed: %s' % e
print('temporary files cleanup failed: %s' % e)


def setup_timezone():
@@ -377,7 +372,7 @@ def main():
try:
Gtk.main()
except KeyboardInterrupt:
print 'Ctrl+C pressed, exiting...'
print('Ctrl+C pressed, exiting...')

_stop_window_manager()

@@ -269,7 +269,7 @@ def is_sugar_adhoc_access_point(self, ap_object_path):
Return: Boolean
"""
for access_point in self._networks.values():
for access_point in list(self._networks.values()):
if access_point is not None:
if access_point.model.object_path == ap_object_path:
return True
@@ -81,7 +81,7 @@ def _helper_read(self, option):
result, output, error, status = GLib.spawn_command_line_sync(cmd)
if status != 0:
return None
return output.rstrip('\0\n')
return output.rstrip(b'\0\n')

def _helper_write(self, option, value):
cmd = 'pkexec sugar-backlight-helper --%s %d' % (option, value)
@@ -136,6 +136,8 @@ def _sync_properties_on_connection(self, connection):
if CONNECTION_INTERFACE_BUDDY_INFO in connection:
properties = {}
if self.props.key is not None:
if isinstance(self.props.key, str):
self.props.key = self.props.key.encode()
properties['key'] = dbus.ByteArray(self.props.key)
if self.props.color is not None:
properties['color'] = self.props.color.to_string()
@@ -196,12 +196,12 @@ def _load_favorites(self):
if not isinstance(favorite_bundles, dict):
raise ValueError('Invalid format in %s.' % favorites_path)
if favorite_bundles:
first_key = favorite_bundles.keys()[0]
if not isinstance(first_key, basestring):
first_key = list(favorite_bundles.keys())[0]
if not isinstance(first_key, str):
raise ValueError('Invalid format in %s.' %
favorites_path)

first_value = favorite_bundles.values()[0]
first_value = list(favorite_bundles.values())[0]
if first_value is not None and \
not isinstance(first_value, dict):
raise ValueError('Invalid format in %s.' %
@@ -222,7 +222,7 @@ def _load_hidden_activities(self):

def _convert_old_favorites(self):
for i in range(desktop.get_number_of_views()):
for key in self._favorite_bundles[i].keys():
for key in list(self._favorite_bundles[i].keys()):
data = self._favorite_bundles[i][key]
if data is None:
data = {}
@@ -273,8 +273,8 @@ def _scan_directory(self, path):
logging.exception('Error while processing installed activity'
' bundle %s:', bundle_dir)

bundle_dirs = bundles.keys()
bundle_dirs.sort(lambda d1, d2: cmp(bundles[d1], bundles[d2]))
bundle_dirs = list(bundles.keys())
bundle_dirs.sort(key = lambda x: bundles[x])
for folder in bundle_dirs:
try:
self.add_bundle(folder, emit_signals=False)
@@ -346,7 +346,7 @@ def file_transfer_available():

test_file_name = '/home/humitos/test.py'
test_temp_file = tempfile.mkstemp()[1]
print test_temp_file
print(test_temp_file)
test_input_stream = Gio.File.new_for_path(test_file_name).read(None)
test_output_stream = Gio.File.new_for_path(test_temp_file)\
.append_to(Gio.FileCreateFlags.PRIVATE, None)
@@ -15,7 +15,7 @@

import os
import logging
from ConfigParser import ConfigParser
from configparser import ConfigParser

from gi.repository import GObject

@@ -135,7 +135,7 @@ def remove(self, buddy_info):
self.emit('friend-removed', buddy_info.get_key())

def __iter__(self):
return self._friends.values().__iter__()
return list(self._friends.values()).__iter__()

def load(self):
cp = ConfigParser()
@@ -290,7 +290,7 @@ def remove_invite(self, invite):
self.emit('invite-removed', invite)

def __iter__(self):
return self._dispatch_operations.values().__iter__()
return list(self._dispatch_operations.values()).__iter__()


def get_instance():
@@ -300,11 +300,11 @@ def _update_status(self, status):
'Connection.GetSelfHandle'))
self.emit('connected')
else:
for contact_handle, contact_id in self._buddy_handles.items():
for contact_handle, contact_id in list(self._buddy_handles.items()):
if contact_id is not None:
self.emit('buddy-removed', contact_id)

for room_handle, activity_id in self._activity_handles.items():
for room_handle, activity_id in list(self._activity_handles.items()):
self.emit('activity-removed', activity_id)

self._buddy_handles = {}
@@ -401,7 +401,7 @@ def __active_activity_changed_cb(self, model, home_activity):

room_handle = 0
home_activity_id = home_activity.get_activity_id()
for handle, activity_id in self._activity_handles.items():
for handle, activity_id in list(self._activity_handles.items()):
if home_activity_id == activity_id:
room_handle = handle
break
@@ -436,7 +436,7 @@ def __aliases_changed_cb(self, aliases):

def __presences_changed_cb(self, presences):
logging.debug('_Account.__presences_changed_cb %r', presences)
for handle, presence in presences.iteritems():
for handle, presence in list(presences.items()):
if handle in self._buddy_handles:
presence_type, status_, message_ = presence
if presence_type == CONNECTION_PRESENCE_TYPE_OFFLINE:
@@ -612,9 +612,9 @@ def __got_buddy_info_cb(self, handle, nick, properties):

def __get_contact_attributes_cb(self, attributes):
logging.debug('_Account.__get_contact_attributes_cb %r',
attributes.keys())
list(attributes.keys()))

for handle in attributes.keys():
for handle in list(attributes.keys()):
nick = attributes[handle][CONNECTION_INTERFACE_ALIASING + '/alias']

if handle == self._self_handle:
@@ -774,7 +774,7 @@ def _get_published_name(self):
the room name, the published name and the host name.

"""
public_key_hash = sha1(get_profile().pubkey).hexdigest()
public_key_hash = sha1(get_profile().pubkey.encode('utf-8')).hexdigest()
return public_key_hash[:8]

def _ensure_link_local_account(self, account_paths):
@@ -852,7 +852,7 @@ def _ensure_server_account(self, account_paths):
return _Account(account_path)

def _get_jabber_account_id(self):
public_key_hash = sha1(get_profile().pubkey).hexdigest()
public_key_hash = sha1(get_profile().pubkey.encode('utf-8')).hexdigest()
server = self._settings_collaboration.get_string('jabber-server')
return '%s@%s' % (public_key_hash, server)

@@ -1067,16 +1067,16 @@ def __buddy_left_activity_cb(self, account, contact_id, activity_id):
self._activities[activity_id].remove_buddy(self._buddies[contact_id])

def get_buddies(self):
return self._buddies.values()
return list(self._buddies.values())

def get_buddy_by_key(self, key):
for buddy in self._buddies.values():
for buddy in list(self._buddies.values()):
if buddy.key == key:
return buddy
return None

def get_buddy_by_handle(self, contact_handle):
for buddy in self._buddies.values():
for buddy in list(self._buddies.values()):
if not buddy.is_owner() and buddy.handle == contact_handle:
return buddy
return None
@@ -1085,13 +1085,13 @@ def get_activity(self, activity_id):
return self._activities.get(activity_id, None)

def get_activity_by_room(self, room_handle):
for activity in self._activities.values():
for activity in list(self._activities.values()):
if activity.room_handle == room_handle:
return activity
return None

def get_activities(self):
return self._activities.values()
return list(self._activities.values())


def get_model():
@@ -25,7 +25,7 @@
import dbus
import dbus.service
from gi.repository import GObject
import ConfigParser
import configparser
from gi.repository import Gio
import ctypes

@@ -701,7 +701,7 @@ def network_hash(self):
else:
fl |= 1 << 6

hashstr = str(fl) + '@' + self.ssid
hashstr = str(fl) + '@' + self.ssid.decode()
return hash(hashstr)

def _update_properties(self, properties):
@@ -957,12 +957,12 @@ def _migrate_old_wifi_connections():
if not os.path.exists(config_path):
return

config = ConfigParser.ConfigParser()
config = configparser.ConfigParser()
try:
if not config.read(config_path):
logging.error('Error reading the nm config file')
return
except ConfigParser.ParsingError:
except configparser.ParsingError:
logging.exception('Error reading the nm config file')
return

@@ -1005,7 +1005,7 @@ def _migrate_old_wifi_connections():
if config.has_option(section, 'pairwise'):
value = config.get(section, 'pairwise')
settings.wireless_security.pairwise = value
except ConfigParser.Error:
except configparser.Error:
logging.exception('Error reading section')
else:
add_connection(settings)
@@ -1095,7 +1095,7 @@ def _is_non_printable(char):
"""
Return True if char is a non-printable unicode character, False otherwise
"""
return (char < u' ') or (u'~' < char < u'\xA0') or (char == u'\xAD')
return (char < ' ') or ('~' < char < '\xA0') or (char == '\xAD')


def ssid_to_display_name(ssid):
@@ -1123,7 +1123,7 @@ def ssid_to_display_name(ssid):
"""
for encoding in ['utf-8', 'iso-8859-1', 'windows-1251']:
try:
display_name = unicode(ssid, encoding)
display_name = str(ssid, encoding)
except UnicodeDecodeError:
continue

@@ -17,7 +17,7 @@
import os
import tempfile
from gettext import gettext as _
import StringIO
import io
import cairo

from gi.repository import Gdk
@@ -114,6 +114,6 @@ def _get_preview_data(screenshot_surface):
cr.set_source_surface(screenshot_surface)
cr.paint()

preview_str = StringIO.StringIO()
preview_str = io.StringIO()
preview_surface.write_to_png(preview_str)
return dbus.ByteArray(preview_str.getvalue())
@@ -128,7 +128,7 @@ def __downloader_complete_cb(self, downloader, result):
link = document.find(_FIND_LINK).text

try:
size = long(document.find(_FIND_SIZE).text) * 1024
size = int(document.find(_FIND_SIZE).text) * 1024
except ValueError:
_logger.exception('Exception occurred while parsing size')
size = 0
@@ -27,11 +27,11 @@
import logging
from tempfile import NamedTemporaryFile

from StringIO import StringIO
from ConfigParser import ConfigParser
from io import StringIO
from configparser import ConfigParser
from zipfile import ZipFile
from urlparse import urljoin
from HTMLParser import HTMLParser
from urllib.parse import urljoin
from html.parser import HTMLParser

from gi.repository import GLib
from gi.repository import GObject
@@ -231,7 +231,7 @@ def _filter_results(self):
# version installed. Queue the remaining ones to be checked.
registry = bundleregistry.get_registry()
self._bundles_to_check = []
for bundle_id, data in self._parser.results.iteritems():
for bundle_id, data in list(self._parser.results.items()):
# filter optional activities for automatic updates
if self._auto and data[2] is True:
logging.debug('filtered optional activity %s', bundle_id)
@@ -365,7 +365,7 @@ def run(self):
try:
name = self._do_name_lookup()
self._complete(name)
except Exception, e:
except Exception as e:
self._complete(e)

def _do_name_lookup(self):
@@ -16,7 +16,7 @@


import os
from urlparse import urlparse
from urllib.parse import urlparse
import tempfile

import gi
@@ -81,7 +81,7 @@ def _setup_message(self, method="GET"):
self._message.connect('got-chunk', self._got_chunk_cb)
self._message.connect('got-headers', self._headers_cb, None)
if self._request_headers is not None:
for header_key in self._request_headers.keys():
for header_key in list(self._request_headers.keys()):
self._message.request_headers.append(
header_key, self._request_headers[header_key])

@@ -18,7 +18,7 @@


def normalize_string(unicode_string):
u"""Return unicode_string normalized for searching.
"""Return unicode_string normalized for searching.

>>> normalize_string(u'Mónica Viñao')
'monica vinao'
@@ -27,4 +27,4 @@ def normalize_string(unicode_string):
'abaco'

"""
return normalize('NFKD', unicode_string).encode('ASCII', 'ignore').lower()
return normalize('NFKD', unicode_string).lower()
@@ -96,7 +96,7 @@ def _remove_connection(self, service_name, path):
self.emit('connection-removed', conn)

def get_connections(self):
return self._connections.values()
return list(self._connections.values())


def get_instance():
@@ -110,10 +110,10 @@ def get_instance():
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

def connection_added_cb(conn_watcher, conn):
print 'new connection', conn.service_name
print('new connection', conn.service_name)

def connection_removed_cb(conn_watcher, conn):
print 'removed connection', conn.service_name
print('removed connection', conn.service_name)

watcher = ConnectionWatcher()
watcher.connect('connection-added', connection_added_cb)
@@ -66,8 +66,11 @@ def _update_color(self):
palette.props.icon.props.xo_color = self._buddy.get_color()

def set_filter(self, query):
normalized_name = normalize_string(
self._buddy.get_nick().decode('utf-8'))
if isinstance(self._buddy.get_nick(), bytes):
nick = self._buddy.get_nick().decode()
else:
nick = self._buddy.get_nick()
normalized_name = normalize_string(nick)
self._filtered = (normalized_name.find(query) == -1) \
and not self._buddy.is_owner()
self._update_color()
@@ -101,7 +101,7 @@ def __init__(self, frame):
except Exception:
logging.exception('Exception while loading extension:')

self._key_grabber.grab_keys(_actions_table.keys())
self._key_grabber.grab_keys(list(_actions_table.keys()))

def _change_volume(self, step=None, value=None):
if step is not None:
@@ -193,7 +193,7 @@ def handle_open_controlpanel(self, event_time):
panel.show()

def handle_dump_ui_tree(self, event_time):
print uitree.get_root().dump()
print(uitree.get_root().dump())

def _key_pressed_cb(self, grabber, keycode, state, event_time):
key = grabber.get_key(keycode, state)
@@ -221,7 +221,7 @@ def _key_pressed_cb(self, grabber, keycode, state, event_time):

if hasattr(action, 'handle_key_press'):
action.handle_key_press(key)
elif isinstance(action, basestring):
elif isinstance(action, str):
method = getattr(self, 'handle_' + action)
method(event_time)
else:
@@ -15,7 +15,6 @@

import os
import signal
import statvfs
from gettext import gettext as _
import logging

@@ -255,8 +254,8 @@ def __open_activate_cb(self, menu_item):

def __popup_cb(self, palette):
stat = os.statvfs(env.get_profile_path())
free_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL]
total_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BLOCKS]
free_space = stat[0] * stat[4]
total_space = stat[0] * stat[2]

fraction = (total_space - free_space) / float(total_space)
self._progress_bar.props.fraction = fraction
@@ -322,8 +321,8 @@ def __unmount_cb(self, mount, result, user_data):
def __popup_cb(self, palette):
mount_point = self._mount.get_root().get_path()
stat = os.statvfs(mount_point)
free_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL]
total_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BLOCKS]
free_space = stat[0] * stat[4]
total_space = stat[0] * stat[2]

fraction = (total_space - free_space) / float(total_space)
self._progress_bar.props.fraction = fraction
@@ -36,7 +36,7 @@


try:
olpc_build = file('/boot/olpc_build', 'r').readline()
olpc_build = open('/boot/olpc_build', 'r').readline()
except:
olpc_build = ''

@@ -114,7 +114,7 @@ def get_help_url_and_title(activity):
_logger.error('helplink.json malformed, or can\'t be read')

if links:
if link_id in links.keys():
if link_id in list(links.keys()):
return links[link_id], title

return None, title
@@ -103,7 +103,7 @@ def load_state(self, state, url):

def _items_history_as_list(self, history):
back_items = []
for n in reversed(range(1, history.get_back_length() + 1)):
for n in reversed(list(range(1, history.get_back_length() + 1))):
item = history.get_nth_item(n * -1)
back_items.append(item)

@@ -102,7 +102,7 @@ def get_all_accounts():
_ensure_module_repository()

accounts = []
for service, service_info in _module_repository.iteritems():
for service, service_info in list(_module_repository.items()):
accounts.append(service_info['account'])

return accounts
@@ -14,7 +14,6 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.



class WebService():
def get_icon_name(self):
raise "Not implemented"
@@ -16,8 +16,8 @@
import os
import unittest
import threading
import SimpleHTTPServer
import SocketServer
import http.server
import socketserver

from gi.repository import Gtk
from gi.repository import GLib
@@ -37,8 +37,8 @@

class TestDownloader(unittest.TestCase):
def setUp(self):
handler = SimpleHTTPServer.SimpleHTTPRequestHandler
self._server = SocketServer.TCPServer(("", 0), handler)
handler = http.server.SimpleHTTPRequestHandler
self._server = socketserver.TCPServer(("", 0), handler)
self._port = self._server.server_address[1]
self._server_thread = threading.Thread(target=self._run_http_server)
self._server_thread.daemon = True
@@ -33,8 +33,8 @@ def test_html_parser(self):
parser.close()

results = parser.results
self.assertIn('org.sugarlabs.AbacusActivity', results.keys())
self.assertIn('org.laptop.WebActivity', results.keys())
self.assertIn('org.sugarlabs.AbacusActivity', list(results.keys()))
self.assertIn('org.laptop.WebActivity', list(results.keys()))

# test that we picked the newest version
version, url = results['org.sugarlabs.AbacusActivity']