futurize --stage2 --all-imports src/**/*.py -w

This commit is contained in:
Chapman Shoop 2019-08-08 23:36:59 -07:00
parent f4fdb94a56
commit 309fa40120
109 changed files with 1057 additions and 239 deletions

View File

@ -1,4 +1,7 @@
from __future__ import print_function from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
# Copyright (c) 2014 Luke Montalvo <lukemontalvo@gmail.com> # Copyright (c) 2014 Luke Montalvo <lukemontalvo@gmail.com>
# This file adds a alternative commandline interface, feel free to critique and fork # This file adds a alternative commandline interface, feel free to critique and fork
# #
@ -8,9 +11,17 @@ from __future__ import print_function
# * python2-pythondialog # * python2-pythondialog
# * dialog # * dialog
from future import standard_library
standard_library.install_aliases()
from builtins import chr
from builtins import ascii
from builtins import str
from builtins import range
from builtins import *
from builtins import object
import os import os
import sys import sys
import StringIO import io
from textwrap import * from textwrap import *
import time import time
@ -24,7 +35,7 @@ from helper_sql import *
from helper_ackPayload import genAckPayload from helper_ackPayload import genAckPayload
from addresses import * from addresses import *
import ConfigParser import configparser
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from inventory import Inventory from inventory import Inventory
import l10n import l10n
@ -61,13 +72,13 @@ bwtype = "black"
BROADCAST_STR = "[Broadcast subscribers]" BROADCAST_STR = "[Broadcast subscribers]"
class printLog: class printLog(object):
def write(self, output): def write(self, output):
global log global log
log += output log += output
def flush(self): def flush(self):
pass pass
class errLog: class errLog(object):
def write(self, output): def write(self, output):
global log global log
log += "!"+output log += "!"+output
@ -79,7 +90,7 @@ errlog = errLog()
def cpair(a): def cpair(a):
r = curses.color_pair(a) r = curses.color_pair(a)
if r not in range(1, curses.COLOR_PAIRS-1): if r not in list(range(1, curses.COLOR_PAIRS-1)):
r = curses.color_pair(0) r = curses.color_pair(0)
return r return r
def ascii(s): def ascii(s):
@ -304,11 +315,11 @@ def handlech(c, stdscr):
msg = "" msg = ""
for i, item in enumerate(data.split("\n")): for i, item in enumerate(data.split("\n")):
msg += fill(item, replace_whitespace=False)+"\n" msg += fill(item, replace_whitespace=False)+"\n"
scrollbox(d, unicode(ascii(msg)), 30, 80) scrollbox(d, str(ascii(msg)), 30, 80)
sqlExecute("UPDATE inbox SET read=1 WHERE msgid=?", inbox[inboxcur][0]) sqlExecute("UPDATE inbox SET read=1 WHERE msgid=?", inbox[inboxcur][0])
inbox[inboxcur][7] = 1 inbox[inboxcur][7] = 1
else: else:
scrollbox(d, unicode("Could not fetch message.")) scrollbox(d, str("Could not fetch message."))
elif t == "2": # Mark unread elif t == "2": # Mark unread
sqlExecute("UPDATE inbox SET read=0 WHERE msgid=?", inbox[inboxcur][0]) sqlExecute("UPDATE inbox SET read=0 WHERE msgid=?", inbox[inboxcur][0])
inbox[inboxcur][7] = 0 inbox[inboxcur][7] = 0
@ -322,7 +333,7 @@ def handlech(c, stdscr):
ischan = True ischan = True
break break
if not addresses[i][1]: if not addresses[i][1]:
scrollbox(d, unicode("Sending address disabled, please either enable it or choose a different address.")) scrollbox(d, str("Sending address disabled, please either enable it or choose a different address."))
return return
toaddr = m[2] toaddr = m[2]
if ischan: if ischan:
@ -352,7 +363,7 @@ def handlech(c, stdscr):
addrbook.append([label, addr]) addrbook.append([label, addr])
addrbook.reverse() addrbook.reverse()
else: else:
scrollbox(d, unicode("The selected address is already in the Address Book.")) scrollbox(d, str("The selected address is already in the Address Book."))
elif t == "5": # Save message elif t == "5": # Save message
set_background_title(d, "Save \""+inbox[inboxcur][5]+"\" as text file") set_background_title(d, "Save \""+inbox[inboxcur][5]+"\" as text file")
r, t = d.inputbox("Filename", init=inbox[inboxcur][5]+".txt") r, t = d.inputbox("Filename", init=inbox[inboxcur][5]+".txt")
@ -366,11 +377,11 @@ def handlech(c, stdscr):
fh.write(msg) fh.write(msg)
fh.close() fh.close()
else: else:
scrollbox(d, unicode("Could not fetch message.")) scrollbox(d, str("Could not fetch message."))
elif t == "6": # Move to trash elif t == "6": # Move to trash
sqlExecute("UPDATE inbox SET folder='trash' WHERE msgid=?", inbox[inboxcur][0]) sqlExecute("UPDATE inbox SET folder='trash' WHERE msgid=?", inbox[inboxcur][0])
del inbox[inboxcur] del inbox[inboxcur]
scrollbox(d, unicode("Message moved to trash. There is no interface to view your trash, \nbut the message is still on disk if you are desperate to recover it.")) scrollbox(d, str("Message moved to trash. There is no interface to view your trash, \nbut the message is still on disk if you are desperate to recover it."))
elif menutab == 2: elif menutab == 2:
a = "" a = ""
if addresses[addrcur][3] != 0: # if current address is a chan if addresses[addrcur][3] != 0: # if current address is a chan
@ -393,13 +404,13 @@ def handlech(c, stdscr):
msg = "" msg = ""
for i, item in enumerate(data.split("\n")): for i, item in enumerate(data.split("\n")):
msg += fill(item, replace_whitespace=False)+"\n" msg += fill(item, replace_whitespace=False)+"\n"
scrollbox(d, unicode(ascii(msg)), 30, 80) scrollbox(d, str(ascii(msg)), 30, 80)
else: else:
scrollbox(d, unicode("Could not fetch message.")) scrollbox(d, str("Could not fetch message."))
elif t == "2": # Move to trash elif t == "2": # Move to trash
sqlExecute("UPDATE sent SET folder='trash' WHERE subject=? AND ackdata=?", sentbox[sentcur][4], sentbox[sentcur][6]) sqlExecute("UPDATE sent SET folder='trash' WHERE subject=? AND ackdata=?", sentbox[sentcur][4], sentbox[sentcur][6])
del sentbox[sentcur] del sentbox[sentcur]
scrollbox(d, unicode("Message moved to trash. There is no interface to view your trash, \nbut the message is still on disk if you are desperate to recover it.")) scrollbox(d, str("Message moved to trash. There is no interface to view your trash, \nbut the message is still on disk if you are desperate to recover it."))
elif menutab == 4: elif menutab == 4:
set_background_title(d, "Your Identities Dialog Box") set_background_title(d, "Your Identities Dialog Box")
if len(addresses) <= addrcur: if len(addresses) <= addrcur:
@ -417,7 +428,7 @@ def handlech(c, stdscr):
if r == d.DIALOG_OK: if r == d.DIALOG_OK:
if t == "1": # Create new address if t == "1": # Create new address
set_background_title(d, "Create new address") set_background_title(d, "Create new address")
scrollbox(d, unicode("Here you may generate as many addresses as you like.\n" scrollbox(d, str("Here you may generate as many addresses as you like.\n"
"Indeed, creating and abandoning addresses is encouraged.\n" "Indeed, creating and abandoning addresses is encouraged.\n"
"Deterministic addresses have several pros and cons:\n" "Deterministic addresses have several pros and cons:\n"
"\nPros:\n" "\nPros:\n"
@ -475,12 +486,12 @@ def handlech(c, stdscr):
choices=[("1", "Spend time shortening the address", 1 if shorten else 0)]) choices=[("1", "Spend time shortening the address", 1 if shorten else 0)])
if r == d.DIALOG_OK and "1" in t: if r == d.DIALOG_OK and "1" in t:
shorten = True shorten = True
scrollbox(d, unicode("In addition to your passphrase, be sure to remember the following numbers:\n" scrollbox(d, str("In addition to your passphrase, be sure to remember the following numbers:\n"
"\n * Address version number: "+str(4)+"\n" "\n * Address version number: "+str(4)+"\n"
" * Stream number: "+str(stream))) " * Stream number: "+str(stream)))
queues.addressGeneratorQueue.put(('createDeterministicAddresses', 4, stream, "unused deterministic address", number, str(passphrase), shorten)) queues.addressGeneratorQueue.put(('createDeterministicAddresses', 4, stream, "unused deterministic address", number, str(passphrase), shorten))
else: else:
scrollbox(d, unicode("Passphrases do not match")) scrollbox(d, str("Passphrases do not match"))
elif t == "2": # Send a message elif t == "2": # Send a message
a = "" a = ""
if addresses[addrcur][3] != 0: # if current address is a chan if addresses[addrcur][3] != 0: # if current address is a chan
@ -528,7 +539,7 @@ def handlech(c, stdscr):
a = addresses[addrcur][2] a = addresses[addrcur][2]
set_background_title(d, "Special address behavior") set_background_title(d, "Special address behavior")
if BMConfigParser().safeGetBoolean(a, "chan"): if BMConfigParser().safeGetBoolean(a, "chan"):
scrollbox(d, unicode("This is a chan address. You cannot use it as a pseudo-mailing list.")) scrollbox(d, str("This is a chan address. You cannot use it as a pseudo-mailing list."))
else: else:
m = BMConfigParser().safeGetBoolean(a, "mailinglist") m = BMConfigParser().safeGetBoolean(a, "mailinglist")
r, t = d.radiolist("Select address behavior", r, t = d.radiolist("Select address behavior",
@ -544,7 +555,7 @@ def handlech(c, stdscr):
elif t == "2" and m == False: elif t == "2" and m == False:
try: try:
mn = BMConfigParser().get(a, "mailinglistname") mn = BMConfigParser().get(a, "mailinglistname")
except ConfigParser.NoOptionError: except configparser.NoOptionError:
mn = "" mn = ""
r, t = d.inputbox("Mailing list name", init=mn) r, t = d.inputbox("Mailing list name", init=mn)
if r == d.DIALOG_OK: if r == d.DIALOG_OK:
@ -633,7 +644,7 @@ def handlech(c, stdscr):
addrbook.append([t, addr]) addrbook.append([t, addr])
addrbook.reverse() addrbook.reverse()
else: else:
scrollbox(d, unicode("The selected address is already in the Address Book.")) scrollbox(d, str("The selected address is already in the Address Book."))
elif t == "4": elif t == "4":
r, t = d.inputbox("Type in \"I want to delete this Address Book entry\"") r, t = d.inputbox("Type in \"I want to delete this Address Book entry\"")
if r == d.DIALOG_OK and t == "I want to delete this Address Book entry": if r == d.DIALOG_OK and t == "I want to delete this Address Book entry":
@ -772,20 +783,20 @@ def sendMessage(sender="", recv="", broadcast=None, subject="", body="", reply=F
err += "Some data encoded in the address is malformed. There might be something wrong with the software of your acquaintance." err += "Some data encoded in the address is malformed. There might be something wrong with the software of your acquaintance."
else: else:
err += "It is unknown what is wrong with the address." err += "It is unknown what is wrong with the address."
scrollbox(d, unicode(err)) scrollbox(d, str(err))
else: else:
addr = addBMIfNotPresent(addr) addr = addBMIfNotPresent(addr)
if version > 4 or version <= 1: if version > 4 or version <= 1:
set_background_title(d, "Recipient address error") set_background_title(d, "Recipient address error")
scrollbox(d, unicode("Could not understand version number " + version + "of address" + addr + ".")) scrollbox(d, str("Could not understand version number " + version + "of address" + addr + "."))
continue continue
if stream > 1 or stream == 0: if stream > 1 or stream == 0:
set_background_title(d, "Recipient address error") set_background_title(d, "Recipient address error")
scrollbox(d, unicode("Bitmessage currently only supports stream numbers of 1, unlike as requested for address " + addr + ".")) scrollbox(d, str("Bitmessage currently only supports stream numbers of 1, unlike as requested for address " + addr + "."))
continue continue
if not network.stats.connectedHostsList(): if not network.stats.connectedHostsList():
set_background_title(d, "Not connected warning") set_background_title(d, "Not connected warning")
scrollbox(d, unicode("Because you are not currently connected to the network, ")) scrollbox(d, str("Because you are not currently connected to the network, "))
stealthLevel = BMConfigParser().safeGetInt('bitmessagesettings', 'ackstealthlevel') stealthLevel = BMConfigParser().safeGetInt('bitmessagesettings', 'ackstealthlevel')
ackdata = genAckPayload(streamNumber, stealthLevel) ackdata = genAckPayload(streamNumber, stealthLevel)
sqlExecute( sqlExecute(
@ -809,7 +820,7 @@ def sendMessage(sender="", recv="", broadcast=None, subject="", body="", reply=F
else: # Broadcast else: # Broadcast
if recv == "": if recv == "":
set_background_title(d, "Empty sender error") set_background_title(d, "Empty sender error")
scrollbox(d, unicode("You must specify an address to send the message from.")) scrollbox(d, str("You must specify an address to send the message from."))
else: else:
# dummy ackdata, no need for stealth # dummy ackdata, no need for stealth
ackdata = genAckPayload(streamNumber, 0) ackdata = genAckPayload(streamNumber, 0)

View File

@ -1,3 +1,10 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from helper_sql import * from helper_sql import *

View File

@ -1,5 +1,10 @@
from __future__ import print_function from __future__ import print_function
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import *
from . import kivy_helper_search from . import kivy_helper_search
import os import os
import queues import queues

View File

@ -2,7 +2,16 @@
PyQt based UI for bitmessage, the main module PyQt based UI for bitmessage, the main module
""" """
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
from builtins import *
from past.utils import old_div
import hashlib import hashlib
import locale import locale
import os import os
@ -405,7 +414,7 @@ class MyForm(settingsmixin.SMainWindow):
def rerenderTabTreeSubscriptions(self): def rerenderTabTreeSubscriptions(self):
treeWidget = self.ui.treeWidgetSubscriptions treeWidget = self.ui.treeWidgetSubscriptions
folders = Ui_FolderWidget.folderWeight.keys() folders = list(Ui_FolderWidget.folderWeight.keys())
folders.remove("new") folders.remove("new")
# sort ascending when creating # sort ascending when creating
@ -453,7 +462,7 @@ class MyForm(settingsmixin.SMainWindow):
# add missing folders # add missing folders
if len(db[toAddress]) > 0: if len(db[toAddress]) > 0:
j = 0 j = 0
for f, c in db[toAddress].iteritems(): for f, c in db[toAddress].items():
try: try:
subwidget = Ui_FolderWidget(widget, j, toAddress, f, c['count']) subwidget = Ui_FolderWidget(widget, j, toAddress, f, c['count'])
except KeyError: except KeyError:
@ -492,7 +501,7 @@ class MyForm(settingsmixin.SMainWindow):
treeWidget = self.ui.treeWidgetYourIdentities treeWidget = self.ui.treeWidgetYourIdentities
elif tab == 'chan': elif tab == 'chan':
treeWidget = self.ui.treeWidgetChans treeWidget = self.ui.treeWidgetChans
folders = Ui_FolderWidget.folderWeight.keys() folders = list(Ui_FolderWidget.folderWeight.keys())
# sort ascending when creating # sort ascending when creating
if treeWidget.topLevelItemCount() == 0: if treeWidget.topLevelItemCount() == 0:
@ -573,7 +582,7 @@ class MyForm(settingsmixin.SMainWindow):
# add missing folders # add missing folders
if len(db[toAddress]) > 0: if len(db[toAddress]) > 0:
j = 0 j = 0
for f, c in db[toAddress].iteritems(): for f, c in db[toAddress].items():
if toAddress is not None and tab == 'messages' and folder == "new": if toAddress is not None and tab == 'messages' and folder == "new":
continue continue
subwidget = Ui_FolderWidget(widget, j, toAddress, f, c) subwidget = Ui_FolderWidget(widget, j, toAddress, f, c)
@ -836,7 +845,7 @@ class MyForm(settingsmixin.SMainWindow):
BMConfigParser().save() BMConfigParser().save()
def updateHumanFriendlyTTLDescription(self, TTL): def updateHumanFriendlyTTLDescription(self, TTL):
numberOfHours = int(round(TTL / (60*60))) numberOfHours = int(round(old_div(TTL, (60*60))))
font = QtGui.QFont() font = QtGui.QFont()
stylesheet = "" stylesheet = ""
@ -849,7 +858,7 @@ class MyForm(settingsmixin.SMainWindow):
stylesheet = "QLabel { color : red; }" stylesheet = "QLabel { color : red; }"
font.setBold(True) font.setBold(True)
else: else:
numberOfDays = int(round(TTL / (24*60*60))) numberOfDays = int(round(old_div(TTL, (24*60*60))))
self.ui.labelHumanFriendlyTTLDescription.setText(_translate("MainWindow", "%n day(s)", None, QtCore.QCoreApplication.CodecForTr, numberOfDays)) self.ui.labelHumanFriendlyTTLDescription.setText(_translate("MainWindow", "%n day(s)", None, QtCore.QCoreApplication.CodecForTr, numberOfDays))
font.setBold(False) font.setBold(False)
self.ui.labelHumanFriendlyTTLDescription.setStyleSheet(stylesheet) self.ui.labelHumanFriendlyTTLDescription.setStyleSheet(stylesheet)
@ -956,7 +965,7 @@ class MyForm(settingsmixin.SMainWindow):
# rrow = related.row(msgid), msgid should be QTableWidgetItem # rrow = related.row(msgid), msgid should be QTableWidgetItem
# related = related.findItems(msgid, QtCore.Qt.MatchExactly), # related = related.findItems(msgid, QtCore.Qt.MatchExactly),
# returns an empty list # returns an empty list
for rrow in xrange(related.rowCount()): for rrow in range(related.rowCount()):
if msgid == str(related.item(rrow, 3).data( if msgid == str(related.item(rrow, 3).data(
QtCore.Qt.UserRole).toPyObject()): QtCore.Qt.UserRole).toPyObject()):
break break
@ -1023,7 +1032,7 @@ class MyForm(settingsmixin.SMainWindow):
for i in range(root.childCount()): for i in range(root.childCount()):
addressItem = root.child(i) addressItem = root.child(i)
if addressItem.type == AccountMixin.ALL: if addressItem.type == AccountMixin.ALL:
newCount = sum(totalUnread.itervalues()) newCount = sum(totalUnread.values())
self.drawTrayIcon(self.currentTrayIconFileName, newCount) self.drawTrayIcon(self.currentTrayIconFileName, newCount)
else: else:
try: try:
@ -1031,7 +1040,7 @@ class MyForm(settingsmixin.SMainWindow):
broadcastsUnread broadcastsUnread
if addressItem.type == AccountMixin.SUBSCRIPTION if addressItem.type == AccountMixin.SUBSCRIPTION
else normalUnread else normalUnread
)[addressItem.address].itervalues()) )[addressItem.address].values())
except KeyError: except KeyError:
newCount = 0 newCount = 0
if newCount != addressItem.unreadCount: if newCount != addressItem.unreadCount:
@ -1074,9 +1083,9 @@ class MyForm(settingsmixin.SMainWindow):
acct.parseMessage(toAddress, fromAddress, subject, "") acct.parseMessage(toAddress, fromAddress, subject, "")
items = [] items = []
MessageList_AddressWidget(items, str(toAddress), unicode(acct.toLabel, 'utf-8')) MessageList_AddressWidget(items, str(toAddress), str(acct.toLabel, 'utf-8'))
MessageList_AddressWidget(items, str(fromAddress), unicode(acct.fromLabel, 'utf-8')) MessageList_AddressWidget(items, str(fromAddress), str(acct.fromLabel, 'utf-8'))
MessageList_SubjectWidget(items, str(subject), unicode(acct.subject, 'utf-8', 'replace')) MessageList_SubjectWidget(items, str(subject), str(acct.subject, 'utf-8', 'replace'))
if status == 'awaitingpubkey': if status == 'awaitingpubkey':
statusText = _translate( statusText = _translate(
@ -1145,11 +1154,11 @@ class MyForm(settingsmixin.SMainWindow):
items = [] items = []
#to #to
MessageList_AddressWidget(items, toAddress, unicode(acct.toLabel, 'utf-8'), not read) MessageList_AddressWidget(items, toAddress, str(acct.toLabel, 'utf-8'), not read)
# from # from
MessageList_AddressWidget(items, fromAddress, unicode(acct.fromLabel, 'utf-8'), not read) MessageList_AddressWidget(items, fromAddress, str(acct.fromLabel, 'utf-8'), not read)
# subject # subject
MessageList_SubjectWidget(items, str(subject), unicode(acct.subject, 'utf-8', 'replace'), not read) MessageList_SubjectWidget(items, str(subject), str(acct.subject, 'utf-8', 'replace'), not read)
# time received # time received
time_item = myTableWidgetItem(l10n.formatTimestamp(received)) time_item = myTableWidgetItem(l10n.formatTimestamp(received))
time_item.setToolTip(l10n.formatTimestamp(received)) time_item.setToolTip(l10n.formatTimestamp(received))
@ -1428,7 +1437,7 @@ class MyForm(settingsmixin.SMainWindow):
self, title, subtitle, category, label=None, icon=None): self, title, subtitle, category, label=None, icon=None):
self.playSound(category, label) self.playSound(category, label)
self._notifier( self._notifier(
unicode(title), unicode(subtitle), category, label, icon) str(title), str(subtitle), category, label, icon)
# tree # tree
def treeWidgetKeyPressEvent(self, event): def treeWidgetKeyPressEvent(self, event):
@ -1857,9 +1866,9 @@ class MyForm(settingsmixin.SMainWindow):
def rerenderAddressBook(self): def rerenderAddressBook(self):
def addRow (address, label, type): def addRow (address, label, type):
self.ui.tableWidgetAddressBook.insertRow(0) self.ui.tableWidgetAddressBook.insertRow(0)
newItem = Ui_AddressBookWidgetItemLabel(address, unicode(label, 'utf-8'), type) newItem = Ui_AddressBookWidgetItemLabel(address, str(label, 'utf-8'), type)
self.ui.tableWidgetAddressBook.setItem(0, 0, newItem) self.ui.tableWidgetAddressBook.setItem(0, 0, newItem)
newItem = Ui_AddressBookWidgetItemAddress(address, unicode(label, 'utf-8'), type) newItem = Ui_AddressBookWidgetItemAddress(address, str(label, 'utf-8'), type)
self.ui.tableWidgetAddressBook.setItem(0, 1, newItem) self.ui.tableWidgetAddressBook.setItem(0, 1, newItem)
oldRows = {} oldRows = {}
@ -1893,13 +1902,13 @@ class MyForm(settingsmixin.SMainWindow):
completerList = [] completerList = []
for address in sorted(oldRows, key = lambda x: oldRows[x][2], reverse = True): for address in sorted(oldRows, key = lambda x: oldRows[x][2], reverse = True):
if address in newRows: if address in newRows:
completerList.append(unicode(newRows[address][0], encoding="UTF-8") + " <" + address + ">") completerList.append(str(newRows[address][0], encoding="UTF-8") + " <" + address + ">")
newRows.pop(address) newRows.pop(address)
else: else:
self.ui.tableWidgetAddressBook.removeRow(oldRows[address][2]) self.ui.tableWidgetAddressBook.removeRow(oldRows[address][2])
for address in newRows: for address in newRows:
addRow(address, newRows[address][0], newRows[address][1]) addRow(address, newRows[address][0], newRows[address][1])
completerList.append(unicode(newRows[address][0], encoding="UTF-8") + " <" + address + ">") completerList.append(str(newRows[address][0], encoding="UTF-8") + " <" + address + ">")
# sort # sort
self.ui.tableWidgetAddressBook.sortByColumn( self.ui.tableWidgetAddressBook.sortByColumn(
@ -2011,7 +2020,7 @@ class MyForm(settingsmixin.SMainWindow):
toAddress) toAddress)
if status != 'success': if status != 'success':
try: try:
toAddress = unicode(toAddress, 'utf-8', 'ignore') toAddress = str(toAddress, 'utf-8', 'ignore')
except: except:
pass pass
logger.error('Error: Could not decode recipient address ' + toAddress + ':' + status) logger.error('Error: Could not decode recipient address ' + toAddress + ':' + status)
@ -2236,7 +2245,7 @@ class MyForm(settingsmixin.SMainWindow):
addressInKeysFile, 'enabled') # I realize that this is poor programming practice but I don't care. It's easier for others to read. addressInKeysFile, 'enabled') # I realize that this is poor programming practice but I don't care. It's easier for others to read.
isMaillinglist = BMConfigParser().safeGetBoolean(addressInKeysFile, 'mailinglist') isMaillinglist = BMConfigParser().safeGetBoolean(addressInKeysFile, 'mailinglist')
if isEnabled and not isMaillinglist: if isEnabled and not isMaillinglist:
label = unicode(BMConfigParser().get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip() label = str(BMConfigParser().get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip()
if label == "": if label == "":
label = addressInKeysFile label = addressInKeysFile
self.ui.comboBoxSendFrom.addItem(avatarize(addressInKeysFile), label, addressInKeysFile) self.ui.comboBoxSendFrom.addItem(avatarize(addressInKeysFile), label, addressInKeysFile)
@ -2260,7 +2269,7 @@ class MyForm(settingsmixin.SMainWindow):
addressInKeysFile, 'enabled') # I realize that this is poor programming practice but I don't care. It's easier for others to read. addressInKeysFile, 'enabled') # I realize that this is poor programming practice but I don't care. It's easier for others to read.
isChan = BMConfigParser().safeGetBoolean(addressInKeysFile, 'chan') isChan = BMConfigParser().safeGetBoolean(addressInKeysFile, 'chan')
if isEnabled and not isChan: if isEnabled and not isChan:
label = unicode(BMConfigParser().get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip() label = str(BMConfigParser().get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip()
if label == "": if label == "":
label = addressInKeysFile label = addressInKeysFile
self.ui.comboBoxSendFromBroadcast.addItem(avatarize(addressInKeysFile), label, addressInKeysFile) self.ui.comboBoxSendFromBroadcast.addItem(avatarize(addressInKeysFile), label, addressInKeysFile)
@ -2299,7 +2308,7 @@ class MyForm(settingsmixin.SMainWindow):
continue continue
self.addMessageListItemSent(sent, toAddress, fromAddress, subject, "msgqueued", ackdata, time.time()) self.addMessageListItemSent(sent, toAddress, fromAddress, subject, "msgqueued", ackdata, time.time())
self.getAccountTextedit(acct).setPlainText(unicode(message, 'utf-8', 'replace')) self.getAccountTextedit(acct).setPlainText(str(message, 'utf-8', 'replace'))
sent.setCurrentCell(0, 0) sent.setCurrentCell(0, 0)
def displayNewInboxMessage(self, inventoryHash, toAddress, fromAddress, subject, message): def displayNewInboxMessage(self, inventoryHash, toAddress, fromAddress, subject, message):
@ -2332,7 +2341,7 @@ class MyForm(settingsmixin.SMainWindow):
self.notifierShow( self.notifierShow(
_translate("MainWindow", "New Message"), _translate("MainWindow", "New Message"),
_translate("MainWindow", "From %1").arg( _translate("MainWindow", "From %1").arg(
unicode(acct.fromLabel, 'utf-8')), str(acct.fromLabel, 'utf-8')),
sound.SOUND_UNKNOWN sound.SOUND_UNKNOWN
) )
if self.getCurrentAccount() is not None and ((self.getCurrentFolder(treeWidget) != "inbox" and self.getCurrentFolder(treeWidget) is not None) or self.getCurrentAccount(treeWidget) != acct.address): if self.getCurrentAccount() is not None and ((self.getCurrentFolder(treeWidget) != "inbox" and self.getCurrentFolder(treeWidget) is not None) or self.getCurrentAccount(treeWidget) != acct.address):
@ -2880,8 +2889,8 @@ class MyForm(settingsmixin.SMainWindow):
if curWorkerQueue > 0: if curWorkerQueue > 0:
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "Waiting for PoW to finish... %1%" "MainWindow", "Waiting for PoW to finish... %1%"
).arg(50 * (maxWorkerQueue - curWorkerQueue) / ).arg(old_div(50 * (maxWorkerQueue - curWorkerQueue),
maxWorkerQueue)) maxWorkerQueue)))
time.sleep(0.5) time.sleep(0.5)
QtCore.QCoreApplication.processEvents( QtCore.QCoreApplication.processEvents(
QtCore.QEventLoop.AllEvents, 1000 QtCore.QEventLoop.AllEvents, 1000
@ -2909,7 +2918,7 @@ class MyForm(settingsmixin.SMainWindow):
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "MainWindow",
"Waiting for objects to be sent... %1%" "Waiting for objects to be sent... %1%"
).arg(int(50 + 20 * (pendingUpload() / maxPendingUpload)))) ).arg(int(50 + 20 * (old_div(pendingUpload(), maxPendingUpload)))))
time.sleep(0.5) time.sleep(0.5)
QtCore.QCoreApplication.processEvents( QtCore.QCoreApplication.processEvents(
QtCore.QEventLoop.AllEvents, 1000 QtCore.QEventLoop.AllEvents, 1000
@ -2929,7 +2938,7 @@ class MyForm(settingsmixin.SMainWindow):
QtCore.QEventLoop.AllEvents, 1000 QtCore.QEventLoop.AllEvents, 1000
) )
self.saveSettings() self.saveSettings()
for attr, obj in self.ui.__dict__.iteritems(): for attr, obj in self.ui.__dict__.items():
if hasattr(obj, "__class__") \ if hasattr(obj, "__class__") \
and isinstance(obj, settingsmixin.SettingsMixin): and isinstance(obj, settingsmixin.SettingsMixin):
saveMethod = getattr(obj, "saveSettings", None) saveMethod = getattr(obj, "saveSettings", None)
@ -2979,7 +2988,7 @@ class MyForm(settingsmixin.SMainWindow):
lines = messageText.split('\n') lines = messageText.split('\n')
totalLines = len(lines) totalLines = len(lines)
for i in xrange(totalLines): for i in range(totalLines):
if 'Message ostensibly from ' in lines[i]: if 'Message ostensibly from ' in lines[i]:
lines[i] = '<p style="font-size: 12px; color: grey;">%s</span></p>' % ( lines[i] = '<p style="font-size: 12px; color: grey;">%s</span></p>' % (
lines[i]) lines[i])
@ -2990,7 +2999,7 @@ class MyForm(settingsmixin.SMainWindow):
lines[i] = '<br><br>' lines[i] = '<br><br>'
content = ' '.join(lines) # To keep the whitespace between lines content = ' '.join(lines) # To keep the whitespace between lines
content = shared.fixPotentiallyInvalidUTF8Data(content) content = shared.fixPotentiallyInvalidUTF8Data(content)
content = unicode(content, 'utf-8)') content = str(content, 'utf-8)')
textEdit.setHtml(QtCore.QString(content)) textEdit.setHtml(QtCore.QString(content))
def on_action_InboxMarkUnread(self): def on_action_InboxMarkUnread(self):
@ -3173,7 +3182,7 @@ class MyForm(settingsmixin.SMainWindow):
self.setSendFromComboBox(toAddressAtCurrentInboxRow) self.setSendFromComboBox(toAddressAtCurrentInboxRow)
quotedText = self.quoted_text( quotedText = self.quoted_text(
unicode(messageAtCurrentInboxRow, 'utf-8', 'replace')) str(messageAtCurrentInboxRow, 'utf-8', 'replace'))
widget['message'].setPlainText(quotedText) widget['message'].setPlainText(quotedText)
if acct.subject[0:3] in ['Re:', 'RE:']: if acct.subject[0:3] in ['Re:', 'RE:']:
widget['subject'].setText( widget['subject'].setText(
@ -3417,7 +3426,7 @@ class MyForm(settingsmixin.SMainWindow):
return self.updateStatusBar(_translate( return self.updateStatusBar(_translate(
"MainWindow", "No addresses selected.")) "MainWindow", "No addresses selected."))
addresses_string = unicode( addresses_string = str(
self.ui.lineEditTo.text().toUtf8(), 'utf-8') self.ui.lineEditTo.text().toUtf8(), 'utf-8')
for item in selected_items: for item in selected_items:
address_string = item.accountString() address_string = item.accountString()
@ -3805,7 +3814,7 @@ class MyForm(settingsmixin.SMainWindow):
text = str(tableWidget.item(currentRow, currentColumn).label) text = str(tableWidget.item(currentRow, currentColumn).label)
else: else:
text = tableWidget.item(currentRow, currentColumn).data(QtCore.Qt.UserRole) text = tableWidget.item(currentRow, currentColumn).data(QtCore.Qt.UserRole)
text = unicode(str(text), 'utf-8', 'ignore') text = str(str(text), 'utf-8', 'ignore')
clipboard = QtGui.QApplication.clipboard() clipboard = QtGui.QApplication.clipboard()
clipboard.setText(text) clipboard.setText(text)
@ -3901,11 +3910,11 @@ class MyForm(settingsmixin.SMainWindow):
self.setAddressSound(widget.item(widget.currentRow(), 0).text()) self.setAddressSound(widget.item(widget.currentRow(), 0).text())
def setAddressSound(self, addr): def setAddressSound(self, addr):
filters = [unicode(_translate( filters = [str(_translate(
"MainWindow", "Sound files (%s)" % "MainWindow", "Sound files (%s)" %
' '.join(['*%s%s' % (os.extsep, ext) for ext in sound.extensions]) ' '.join(['*%s%s' % (os.extsep, ext) for ext in sound.extensions])
))] ))]
sourcefile = unicode(QtGui.QFileDialog.getOpenFileName( sourcefile = str(QtGui.QFileDialog.getOpenFileName(
self, _translate("MainWindow", "Set notification sound..."), self, _translate("MainWindow", "Set notification sound..."),
filter=';;'.join(filters) filter=';;'.join(filters)
)) ))
@ -3914,7 +3923,7 @@ class MyForm(settingsmixin.SMainWindow):
return return
destdir = os.path.join(state.appdata, 'sounds') destdir = os.path.join(state.appdata, 'sounds')
destfile = unicode(addr) + os.path.splitext(sourcefile)[-1] destfile = str(addr) + os.path.splitext(sourcefile)[-1]
destination = os.path.join(destdir, destfile) destination = os.path.join(destdir, destfile)
if sourcefile == destination: if sourcefile == destination:
@ -4121,7 +4130,7 @@ class MyForm(settingsmixin.SMainWindow):
if item.type == AccountMixin.ALL: if item.type == AccountMixin.ALL:
return return
newLabel = unicode(item.text(0), 'utf-8', 'ignore') newLabel = str(item.text(0), 'utf-8', 'ignore')
oldLabel = item.defaultLabel() oldLabel = item.defaultLabel()
# unchanged, do not do anything either # unchanged, do not do anything either
@ -4192,7 +4201,7 @@ class MyForm(settingsmixin.SMainWindow):
self.rerenderMessagelistToLabels() self.rerenderMessagelistToLabels()
completerList = self.ui.lineEditTo.completer().model().stringList() completerList = self.ui.lineEditTo.completer().model().stringList()
for i in range(len(completerList)): for i in range(len(completerList)):
if unicode(completerList[i]).endswith(" <" + item.address + ">"): if str(completerList[i]).endswith(" <" + item.address + ">"):
completerList[i] = item.label + " <" + item.address + ">" completerList[i] = item.label + " <" + item.address + ">"
self.ui.lineEditTo.completer().model().setStringList(completerList) self.ui.lineEditTo.completer().model().setStringList(completerList)
@ -4246,7 +4255,7 @@ class MyForm(settingsmixin.SMainWindow):
QtCore.QCoreApplication.setOrganizationDomain("bitmessage.org") QtCore.QCoreApplication.setOrganizationDomain("bitmessage.org")
QtCore.QCoreApplication.setApplicationName("pybitmessageqt") QtCore.QCoreApplication.setApplicationName("pybitmessageqt")
self.loadSettings() self.loadSettings()
for attr, obj in self.ui.__dict__.iteritems(): for attr, obj in self.ui.__dict__.items():
if hasattr(obj, "__class__") and \ if hasattr(obj, "__class__") and \
isinstance(obj, settingsmixin.SettingsMixin): isinstance(obj, settingsmixin.SettingsMixin):
loadMethod = getattr(obj, "loadSettings", None) loadMethod = getattr(obj, "loadSettings", None)

View File

@ -8,7 +8,16 @@ Account related functions.
""" """
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from past.builtins import cmp
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
from builtins import object
import inspect import inspect
import re import re
import sys import sys
@ -31,12 +40,12 @@ def getSortedAccounts():
configSections = BMConfigParser().addresses() configSections = BMConfigParser().addresses()
configSections.sort( configSections.sort(
cmp=lambda x, y: cmp( cmp=lambda x, y: cmp(
unicode( str(
BMConfigParser().get( BMConfigParser().get(
x, x,
'label'), 'label'),
'utf-8').lower(), 'utf-8').lower(),
unicode( str(
BMConfigParser().get( BMConfigParser().get(
y, y,
'label'), 'label'),
@ -169,7 +178,7 @@ class BMAccount(object):
self.toAddress = toAddress self.toAddress = toAddress
self.fromAddress = fromAddress self.fromAddress = fromAddress
if isinstance(subject, unicode): if isinstance(subject, str):
self.subject = str(subject) self.subject = str(subject)
else: else:
self.subject = subject self.subject = subject

View File

@ -4,8 +4,16 @@ src/bitmessageqt/address_dialogs.py
""" """
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
# pylint: disable=attribute-defined-outside-init # pylint: disable=attribute-defined-outside-init
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
from builtins import object
import hashlib import hashlib
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
@ -263,7 +271,7 @@ class SpecialAddressBehaviorDialog(QtGui.QDialog, RetranslateMixin):
except: except:
mailingListName = '' mailingListName = ''
self.lineEditMailingListName.setText( self.lineEditMailingListName.setText(
unicode(mailingListName, 'utf-8') str(mailingListName, 'utf-8')
) )
QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self)) QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self))

View File

@ -1,6 +1,14 @@
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
from builtins import object
from PyQt4 import QtGui from PyQt4 import QtGui
from Queue import Empty from queue import Empty
from addresses import decodeAddress, addBMIfNotPresent from addresses import decodeAddress, addBMIfNotPresent
from .account import getSortedAccounts from .account import getSortedAccounts
@ -8,7 +16,7 @@ from queues import apiAddressGeneratorReturnQueue, addressGeneratorQueue
from tr import _translate from tr import _translate
from .utils import str_chan from .utils import str_chan
class AddressPassPhraseValidatorMixin(): class AddressPassPhraseValidatorMixin(object):
def setParams(self, passPhraseObject=None, addressObject=None, feedBackObject=None, buttonBox=None, addressMandatory=True): def setParams(self, passPhraseObject=None, addressObject=None, feedBackObject=None, buttonBox=None, addressMandatory=True):
self.addressObject = addressObject self.addressObject = addressObject
self.passPhraseObject = passPhraseObject self.passPhraseObject = passPhraseObject

View File

@ -7,6 +7,13 @@
# #
# WARNING! All changes made in this file will be lost! # WARNING! All changes made in this file will be lost!
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from PyQt4 import QtCore from PyQt4 import QtCore
qt_resource_data = "\ qt_resource_data = "\

View File

@ -8,6 +8,14 @@
# WARNING! All changes made in this file will be lost! # WARNING! All changes made in this file will be lost!
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import *
from builtins import object
from past.utils import old_div
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from .foldertree import AddressBookCompleter from .foldertree import AddressBookCompleter
@ -709,7 +717,7 @@ class Ui_MainWindow(object):
self.pushButtonTTL.setText(_translate("MainWindow", "TTL:", None)) self.pushButtonTTL.setText(_translate("MainWindow", "TTL:", None))
hours = 48 hours = 48
try: try:
hours = int(BMConfigParser().getint('bitmessagesettings', 'ttl')/60/60) hours = int(old_div(BMConfigParser().getint('bitmessagesettings', 'ttl'),60/60))
except: except:
pass pass
self.labelHumanFriendlyTTLDescription.setText(_translate("MainWindow", "%n hour(s)", None, QtCore.QCoreApplication.CodecForTr, hours)) self.labelHumanFriendlyTTLDescription.setText(_translate("MainWindow", "%n hour(s)", None, QtCore.QCoreApplication.CodecForTr, hours))

View File

@ -1,4 +1,11 @@
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from . import widgets from . import widgets
@ -74,7 +81,7 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
if queryreturn == []: if queryreturn == []:
self.tableWidgetBlacklist.setSortingEnabled(False) self.tableWidgetBlacklist.setSortingEnabled(False)
self.tableWidgetBlacklist.insertRow(0) self.tableWidgetBlacklist.insertRow(0)
newItem = QtGui.QTableWidgetItem(unicode( newItem = QtGui.QTableWidgetItem(str(
self.NewBlacklistDialogInstance.lineEditLabel.text().toUtf8(), 'utf-8')) self.NewBlacklistDialogInstance.lineEditLabel.text().toUtf8(), 'utf-8'))
newItem.setIcon(avatarize(address)) newItem.setIcon(avatarize(address))
self.tableWidgetBlacklist.setItem(0, 0, newItem) self.tableWidgetBlacklist.setItem(0, 0, newItem)
@ -173,7 +180,7 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
for row in queryreturn: for row in queryreturn:
label, address, enabled = row label, address, enabled = row
self.tableWidgetBlacklist.insertRow(0) self.tableWidgetBlacklist.insertRow(0)
newItem = QtGui.QTableWidgetItem(unicode(label, 'utf-8')) newItem = QtGui.QTableWidgetItem(str(label, 'utf-8'))
if not enabled: if not enabled:
newItem.setTextColor(QtGui.QColor(128, 128, 128)) newItem.setTextColor(QtGui.QColor(128, 128, 128))
newItem.setIcon(avatarize(address)) newItem.setIcon(avatarize(address))

View File

@ -3,7 +3,14 @@ src/bitmessageqt/dialogs.py
=========================== ===========================
""" """
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
from PyQt4 import QtGui from PyQt4 import QtGui
from version import softwareVersion from version import softwareVersion

View File

@ -3,8 +3,17 @@ src/bitmessageqt/foldertree.py
============================== ==============================
""" """
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
# pylint: disable=too-many-arguments,bad-super-call,attribute-defined-outside-init # pylint: disable=too-many-arguments,bad-super-call,attribute-defined-outside-init
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
from builtins import *
from builtins import object
from cgi import escape from cgi import escape
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
@ -123,7 +132,7 @@ class AccountMixin(object):
AccountMixin.NORMAL, AccountMixin.NORMAL,
AccountMixin.CHAN, AccountMixin.MAILINGLIST): AccountMixin.CHAN, AccountMixin.MAILINGLIST):
try: try:
retval = unicode( retval = str(
BMConfigParser().get(self.address, 'label'), 'utf-8') BMConfigParser().get(self.address, 'label'), 'utf-8')
except Exception: except Exception:
queryreturn = sqlQuery( queryreturn = sqlQuery(
@ -135,12 +144,12 @@ class AccountMixin(object):
if queryreturn != []: if queryreturn != []:
for row in queryreturn: for row in queryreturn:
retval, = row retval, = row
retval = unicode(retval, 'utf-8') retval = str(retval, 'utf-8')
elif self.address is None or self.type == AccountMixin.ALL: elif self.address is None or self.type == AccountMixin.ALL:
return unicode( return str(
str(_translate("MainWindow", "All accounts")), 'utf-8') str(_translate("MainWindow", "All accounts")), 'utf-8')
return retval or unicode(self.address, 'utf-8') return retval or str(self.address, 'utf-8')
class BMTreeWidgetItem(QtGui.QTreeWidgetItem, AccountMixin): class BMTreeWidgetItem(QtGui.QTreeWidgetItem, AccountMixin):
@ -231,15 +240,15 @@ class Ui_AddressWidget(BMTreeWidgetItem, SettingsMixin):
def _getLabel(self): def _getLabel(self):
if self.address is None: if self.address is None:
return unicode(_translate( return str(_translate(
"MainWindow", "All accounts").toUtf8(), 'utf-8', 'ignore') "MainWindow", "All accounts").toUtf8(), 'utf-8', 'ignore')
else: else:
try: try:
return unicode( return str(
BMConfigParser().get(self.address, 'label'), BMConfigParser().get(self.address, 'label'),
'utf-8', 'ignore') 'utf-8', 'ignore')
except: except:
return unicode(self.address, 'utf-8') return str(self.address, 'utf-8')
def _getAddressBracket(self, unreadCount=False): def _getAddressBracket(self, unreadCount=False):
ret = "" if self.isExpanded() \ ret = "" if self.isExpanded() \
@ -310,8 +319,8 @@ class Ui_SubscriptionWidget(Ui_AddressWidget):
if queryreturn != []: if queryreturn != []:
for row in queryreturn: for row in queryreturn:
retval, = row retval, = row
return unicode(retval, 'utf-8', 'ignore') return str(retval, 'utf-8', 'ignore')
return unicode(self.address, 'utf-8') return str(self.address, 'utf-8')
def setType(self): def setType(self):
"""Set account type""" """Set account type"""
@ -325,7 +334,7 @@ class Ui_SubscriptionWidget(Ui_AddressWidget):
label = str( label = str(
value.toString().toUtf8()).decode('utf-8', 'ignore') value.toString().toUtf8()).decode('utf-8', 'ignore')
else: else:
label = unicode(value, 'utf-8', 'ignore') label = str(value, 'utf-8', 'ignore')
sqlExecute( sqlExecute(
'''UPDATE subscriptions SET label=? WHERE address=?''', '''UPDATE subscriptions SET label=? WHERE address=?''',
label, self.address) label, self.address)
@ -408,7 +417,7 @@ class MessageList_AddressWidget(BMAddressWidget):
AccountMixin.NORMAL, AccountMixin.NORMAL,
AccountMixin.CHAN, AccountMixin.MAILINGLIST): AccountMixin.CHAN, AccountMixin.MAILINGLIST):
try: try:
newLabel = unicode( newLabel = str(
BMConfigParser().get(self.address, 'label'), BMConfigParser().get(self.address, 'label'),
'utf-8', 'ignore') 'utf-8', 'ignore')
except: except:
@ -419,7 +428,7 @@ class MessageList_AddressWidget(BMAddressWidget):
'''select label from subscriptions where address=?''', self.address) '''select label from subscriptions where address=?''', self.address)
if queryreturn: if queryreturn:
for row in queryreturn: for row in queryreturn:
newLabel = unicode(row[0], 'utf-8', 'ignore') newLabel = str(row[0], 'utf-8', 'ignore')
self.label = newLabel self.label = newLabel
@ -460,7 +469,7 @@ class MessageList_SubjectWidget(BMTableWidgetItem):
if role == QtCore.Qt.UserRole: if role == QtCore.Qt.UserRole:
return self.subject return self.subject
if role == QtCore.Qt.ToolTipRole: if role == QtCore.Qt.ToolTipRole:
return escape(unicode(self.subject, 'utf-8')) return escape(str(self.subject, 'utf-8'))
return super(MessageList_SubjectWidget, self).data(role) return super(MessageList_SubjectWidget, self).data(role)
# label (or address) alphabetically, disabled at the end # label (or address) alphabetically, disabled at the end
@ -558,14 +567,14 @@ class AddressBookCompleter(QtGui.QCompleter):
def splitPath(self, path): def splitPath(self, path):
"""Split on semicolon""" """Split on semicolon"""
text = unicode(path.toUtf8(), 'utf-8') text = str(path.toUtf8(), 'utf-8')
return [text[:self.widget().cursorPosition()].split(';')[-1].strip()] return [text[:self.widget().cursorPosition()].split(';')[-1].strip()]
def pathFromIndex(self, index): def pathFromIndex(self, index):
"""Perform autocompletion (reimplemented QCompleter method)""" """Perform autocompletion (reimplemented QCompleter method)"""
autoString = unicode( autoString = str(
index.data(QtCore.Qt.EditRole).toString().toUtf8(), 'utf-8') index.data(QtCore.Qt.EditRole).toString().toUtf8(), 'utf-8')
text = unicode(self.widget().text().toUtf8(), 'utf-8') text = str(self.widget().text().toUtf8(), 'utf-8')
# If cursor position was saved, restore it, else save it # If cursor position was saved, restore it, else save it
if self.cursorPos != -1: if self.cursorPos != -1:

View File

@ -1,3 +1,11 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
from builtins import *
import glob import glob
import os import os
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui

View File

@ -1,3 +1,12 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
from past.utils import old_div
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
class MessageCompose(QtGui.QTextEdit): class MessageCompose(QtGui.QTextEdit):
@ -13,7 +22,7 @@ class MessageCompose(QtGui.QTextEdit):
self.zoomIn(1) self.zoomIn(1)
else: else:
self.zoomOut(1) self.zoomOut(1)
zoom = self.currentFont().pointSize() * 100 / self.defaultFontPointSize zoom = old_div(self.currentFont().pointSize() * 100, self.defaultFontPointSize)
QtGui.QApplication.activeWindow().statusBar().showMessage(QtGui.QApplication.translate("MainWindow", "Zoom level %1%").arg(str(zoom))) QtGui.QApplication.activeWindow().statusBar().showMessage(QtGui.QApplication.translate("MainWindow", "Zoom level %1%").arg(str(zoom)))
else: else:
# in QTextEdit, super does not zoom, only scroll # in QTextEdit, super does not zoom, only scroll

View File

@ -4,7 +4,15 @@ src/bitmessageqt/messageview.py
""" """
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
from past.utils import old_div
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from .safehtmlparser import SafeHTMLParser from .safehtmlparser import SafeHTMLParser
@ -52,7 +60,7 @@ class MessageView(QtGui.QTextBrowser):
super(MessageView, self).wheelEvent(event) super(MessageView, self).wheelEvent(event)
if (QtGui.QApplication.queryKeyboardModifiers() & if (QtGui.QApplication.queryKeyboardModifiers() &
QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier and event.orientation() == QtCore.Qt.Vertical: QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier and event.orientation() == QtCore.Qt.Vertical:
zoom = self.currentFont().pointSize() * 100 / self.defaultFontPointSize zoom = old_div(self.currentFont().pointSize() * 100, self.defaultFontPointSize)
QtGui.QApplication.activeWindow().statusBar().showMessage( QtGui.QApplication.activeWindow().statusBar().showMessage(
QtGui.QApplication.translate("MainWindow", "Zoom level %1%").arg(str(zoom))) QtGui.QApplication.translate("MainWindow", "Zoom level %1%").arg(str(zoom)))
@ -89,7 +97,7 @@ class MessageView(QtGui.QTextBrowser):
QtGui.QApplication.translate( QtGui.QApplication.translate(
"MessageView", "MessageView",
"The link \"%1\" will open in a browser. It may be a security risk, it could de-anonymise you" "The link \"%1\" will open in a browser. It may be a security risk, it could de-anonymise you"
" or download malicious data. Are you sure?").arg(unicode(link.toString())), " or download malicious data. Are you sure?").arg(str(link.toString())),
QtGui.QMessageBox.Yes, QtGui.QMessageBox.Yes,
QtGui.QMessageBox.No) QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes: if reply == QtGui.QMessageBox.Yes:
@ -131,7 +139,7 @@ class MessageView(QtGui.QTextBrowser):
self.mode = MessageView.MODE_PLAIN self.mode = MessageView.MODE_PLAIN
out = self.html.raw out = self.html.raw
if self.html.has_html: if self.html.has_html:
out = "<div align=\"center\" style=\"text-decoration: underline;\"><b>" + unicode( out = "<div align=\"center\" style=\"text-decoration: underline;\"><b>" + str(
QtGui.QApplication.translate( QtGui.QApplication.translate(
"MessageView", "HTML detected, click here to display")) + "</b></div><br/>" + out "MessageView", "HTML detected, click here to display")) + "</b></div><br/>" + out
self.out = out self.out = out
@ -143,7 +151,7 @@ class MessageView(QtGui.QTextBrowser):
"""Render message as HTML""" """Render message as HTML"""
self.mode = MessageView.MODE_HTML self.mode = MessageView.MODE_HTML
out = self.html.sanitised out = self.html.sanitised
out = "<div align=\"center\" style=\"text-decoration: underline;\"><b>" + unicode( out = "<div align=\"center\" style=\"text-decoration: underline;\"><b>" + str(
QtGui.QApplication.translate("MessageView", "Click here to disable HTML")) + "</b></div><br/>" + out QtGui.QApplication.translate("MessageView", "Click here to disable HTML")) + "</b></div><br/>" + out
self.out = out self.out = out
self.outpos = 0 self.outpos = 0

View File

@ -1,4 +1,11 @@
#!/usr/bin/env python2.7 #!/usr/bin/env python2.7
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
class MigrationWizardIntroPage(QtGui.QWizardPage): class MigrationWizardIntroPage(QtGui.QWizardPage):

View File

@ -4,7 +4,17 @@ src/bitmessageqt/networkstatus.py
""" """
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import map
from builtins import range
from builtins import *
from past.utils import old_div
import time import time
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
@ -235,7 +245,7 @@ class NetworkStatus(QtGui.QWidget, RetranslateMixin):
def runEveryTwoSeconds(self): def runEveryTwoSeconds(self):
"""Updates counters, runs every 2 seconds if the timer is running""" """Updates counters, runs every 2 seconds if the timer is running"""
self.labelLookupsPerSecond.setText(_translate("networkstatus", "Inventory lookups per second: %1").arg( self.labelLookupsPerSecond.setText(_translate("networkstatus", "Inventory lookups per second: %1").arg(
str(Inventory().numberOfInventoryLookupsPerformed / 2))) str(old_div(Inventory().numberOfInventoryLookupsPerformed, 2))))
Inventory().numberOfInventoryLookupsPerformed = 0 Inventory().numberOfInventoryLookupsPerformed = 0
self.updateNumberOfBytes() self.updateNumberOfBytes()
self.updateNumberOfObjectsToBeSynced() self.updateNumberOfObjectsToBeSynced()

View File

@ -1,5 +1,12 @@
#!/usr/bin/env python2.7 #!/usr/bin/env python2.7
from __future__ import print_function from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
from builtins import *
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
class NewAddressWizardIntroPage(QtGui.QWizardPage): class NewAddressWizardIntroPage(QtGui.QWizardPage):

View File

@ -4,7 +4,14 @@ src/bitmessageqt/newchandialog.py
""" """
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from . import widgets from . import widgets
@ -67,7 +74,7 @@ class NewChanDialog(QtGui.QDialog, RetranslateMixin):
addressGeneratorReturnValue = apiAddressGeneratorReturnQueue.get(True) addressGeneratorReturnValue = apiAddressGeneratorReturnQueue.get(True)
if addressGeneratorReturnValue and addressGeneratorReturnValue[0] != 'chan name does not match address': if addressGeneratorReturnValue and addressGeneratorReturnValue[0] != 'chan name does not match address':
UISignalQueue.put(('updateStatusBar', _translate( UISignalQueue.put(('updateStatusBar', _translate(
"newchandialog", "Successfully created / joined chan %1").arg(unicode(self.chanPassPhrase.text())))) "newchandialog", "Successfully created / joined chan %1").arg(str(self.chanPassPhrase.text()))))
self.parent.ui.tabWidget.setCurrentIndex( self.parent.ui.tabWidget.setCurrentIndex(
self.parent.ui.tabWidget.indexOf(self.parent.ui.chans) self.parent.ui.tabWidget.indexOf(self.parent.ui.chans)
) )

View File

@ -1,4 +1,12 @@
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import range
from builtins import *
from builtins import object
from os import path from os import path
from PyQt4 import QtGui from PyQt4 import QtGui
from debug import logger from debug import logger
@ -8,7 +16,7 @@ class RetranslateMixin(object):
def retranslateUi(self): def retranslateUi(self):
defaults = QtGui.QWidget() defaults = QtGui.QWidget()
widgets.load(self.__class__.__name__.lower() + '.ui', defaults) widgets.load(self.__class__.__name__.lower() + '.ui', defaults)
for attr, value in defaults.__dict__.iteritems(): for attr, value in defaults.__dict__.items():
setTextMethod = getattr(value, "setText", None) setTextMethod = getattr(value, "setText", None)
if callable(setTextMethod): if callable(setTextMethod):
getattr(self, attr).setText(getattr(defaults, attr).text()) getattr(self, attr).setText(getattr(defaults, attr).text())

View File

@ -1,8 +1,16 @@
from HTMLParser import HTMLParser from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
from html.parser import HTMLParser
import inspect import inspect
import re import re
from urllib import quote, quote_plus from urllib.parse import quote, quote_plus
from urlparse import urlparse from urllib.parse import urlparse
class SafeHTMLParser(HTMLParser): class SafeHTMLParser(HTMLParser):
# from html5lib.sanitiser # from html5lib.sanitiser
@ -99,9 +107,9 @@ class SafeHTMLParser(HTMLParser):
def feed(self, data): def feed(self, data):
try: try:
data = unicode(data, 'utf-8') data = str(data, 'utf-8')
except UnicodeDecodeError: except UnicodeDecodeError:
data = unicode(data, 'utf-8', errors='replace') data = str(data, 'utf-8', errors='replace')
HTMLParser.feed(self, data) HTMLParser.feed(self, data)
tmp = SafeHTMLParser.replace_pre(data) tmp = SafeHTMLParser.replace_pre(data)
tmp = SafeHTMLParser.uriregex1.sub( tmp = SafeHTMLParser.uriregex1.sub(

View File

@ -11,7 +11,15 @@ Created: Thu Dec 25 23:21:20 2014
WARNING! All changes made in this file will be lost! WARNING! All changes made in this file will be lost!
""" """
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from builtins import object
from sys import platform from sys import platform
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui

View File

@ -4,7 +4,16 @@ src/settingsmixin.py
==================== ====================
""" """
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
from builtins import object
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui

View File

@ -1,6 +1,13 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# sound type constants # sound type constants
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
SOUND_NONE = 0 SOUND_NONE = 0
SOUND_KNOWN = 1 SOUND_KNOWN = 1
SOUND_UNKNOWN = 2 SOUND_UNKNOWN = 2

View File

@ -1,5 +1,12 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from Queue import Queue from queue import Queue
from time import time from time import time
class BMStatusBar(QtGui.QStatusBar): class BMStatusBar(QtGui.QStatusBar):

View File

@ -1,4 +1,11 @@
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
import ctypes import ctypes
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
import ssl import ssl

View File

@ -1,4 +1,12 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
from PyQt4.QtCore import QThread, SIGNAL from PyQt4.QtCore import QThread, SIGNAL
import sys import sys

View File

@ -1,3 +1,10 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from PyQt4 import QtGui from PyQt4 import QtGui
import hashlib import hashlib
import os import os

View File

@ -1,3 +1,10 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from PyQt4 import uic from PyQt4 import uic
import os.path import os.path
import paths import paths

View File

@ -1,7 +1,14 @@
""" """
.. todo:: hello world .. todo:: hello world
""" """
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import hashlib import hashlib
# We need to check hashlib for RIPEMD-160, as it won't be available # We need to check hashlib for RIPEMD-160, as it won't be available

View File

@ -1,4 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import os import os
path = os.path.dirname(__file__) path = os.path.dirname(__file__)

View File

@ -1,5 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.lang import Builder from kivy.lang import Builder
from kivy.properties import StringProperty, ListProperty, OptionProperty from kivy.properties import StringProperty, ListProperty, OptionProperty
from kivy.utils import get_color_from_hex from kivy.utils import get_color_from_hex

View File

@ -1,4 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.lang import Builder from kivy.lang import Builder
from kivy.properties import BoundedNumericProperty, ReferenceListProperty from kivy.properties import BoundedNumericProperty, ReferenceListProperty
from kivy.uix.widget import Widget from kivy.uix.widget import Widget

View File

@ -39,6 +39,13 @@ For :class:`MDListBottomSheet`:
API API
--- ---
''' '''
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.clock import Clock from kivy.clock import Clock
from kivy.lang import Builder from kivy.lang import Builder
from kivy.metrics import dp from kivy.metrics import dp

View File

@ -9,6 +9,13 @@ Buttons
TO-DO: DOCUMENT MODULE TO-DO: DOCUMENT MODULE
''' '''
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.clock import Clock from kivy.clock import Clock
from kivy.lang import Builder from kivy.lang import Builder
from kivy.metrics import dp from kivy.metrics import dp

View File

@ -1,4 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.lang import Builder from kivy.lang import Builder
from kivy.properties import BoundedNumericProperty, ReferenceListProperty, ListProperty,BooleanProperty from kivy.properties import BoundedNumericProperty, ReferenceListProperty, ListProperty,BooleanProperty
from kivy.uix.boxlayout import BoxLayout from kivy.uix.boxlayout import BoxLayout

View File

@ -1,3 +1,10 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
colors = { colors = {
'Pink': { 'Pink': {
'50': 'fce4ec', '50': 'fce4ec',

View File

@ -1,5 +1,13 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import print_function from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
from builtins import *
from kivy.lang import Builder from kivy.lang import Builder
from kivy.uix.modalview import ModalView from kivy.uix.modalview import ModalView
from kivymd.label import MDLabel from kivymd.label import MDLabel

View File

@ -1,5 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.lang import Builder from kivy.lang import Builder
from kivy.properties import StringProperty, ObjectProperty, ListProperty from kivy.properties import StringProperty, ObjectProperty, ListProperty
from kivy.metrics import dp from kivy.metrics import dp

View File

@ -1,5 +1,15 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
from builtins import object
from past.utils import old_div
from kivy.app import App from kivy.app import App
from kivy.lang import Builder from kivy.lang import Builder
from kivy.properties import (ListProperty, ObjectProperty, NumericProperty) from kivy.properties import (ListProperty, ObjectProperty, NumericProperty)
@ -75,7 +85,7 @@ class ElevationBehavior(object):
def _update_shadow(self, *args): def _update_shadow(self, *args):
if self.elevation > 0: if self.elevation > 0:
ratio = self.width / (self.height if self.height != 0 else 1) ratio = old_div(self.width, (self.height if self.height != 0 else 1))
if ratio > -2 and ratio < 2: if ratio > -2 and ratio < 2:
self._shadow = App.get_running_app().theme_cls.quad_shadow self._shadow = App.get_running_app().theme_cls.quad_shadow
width = soft_width = self.width * 1.9 width = soft_width = self.width * 1.9
@ -106,19 +116,19 @@ class ElevationBehavior(object):
# soft_width = self.width + dp(ratio) + dp(self.elevation) * .9 # soft_width = self.width + dp(ratio) + dp(self.elevation) * .9
# height = soft_height = self.height * 1.9 # height = soft_height = self.height * 1.9
x = self.center_x - width / 2 x = self.center_x - old_div(width, 2)
soft_x = self.center_x - soft_width / 2 soft_x = self.center_x - old_div(soft_width, 2)
self._soft_shadow_size = (soft_width, soft_height) self._soft_shadow_size = (soft_width, soft_height)
self._hard_shadow_size = (width, height) self._hard_shadow_size = (width, height)
y = self.center_y - soft_height / 2 - dp( y = self.center_y - old_div(soft_height, 2) - dp(
.1 * 1.5 ** self.elevation) .1 * 1.5 ** self.elevation)
self._soft_shadow_pos = (soft_x, y) self._soft_shadow_pos = (soft_x, y)
self._soft_shadow_a = 0.1 * 1.1 ** self.elevation self._soft_shadow_a = 0.1 * 1.1 ** self.elevation
self._soft_shadow_texture = self._shadow.textures[ self._soft_shadow_texture = self._shadow.textures[
str(int(round(self.elevation - 1)))] str(int(round(self.elevation - 1)))]
y = self.center_y - height / 2 - dp(.5 * 1.18 ** self.elevation) y = self.center_y - old_div(height, 2) - dp(.5 * 1.18 ** self.elevation)
self._hard_shadow_pos = (x, y) self._hard_shadow_pos = (x, y)
self._hard_shadow_a = .4 * .9 ** self.elevation self._hard_shadow_a = .4 * .9 ** self.elevation
self._hard_shadow_texture = self._shadow.textures[ self._hard_shadow_texture = self._shadow.textures[
@ -165,18 +175,18 @@ class RoundElevationBehavior(object):
width = self.width * 2 width = self.width * 2
height = self.height * 2 height = self.height * 2
x = self.center_x - width / 2 x = self.center_x - old_div(width, 2)
self._soft_shadow_size = (width, height) self._soft_shadow_size = (width, height)
self._hard_shadow_size = (width, height) self._hard_shadow_size = (width, height)
y = self.center_y - height / 2 - dp(.1 * 1.5 ** self.elevation) y = self.center_y - old_div(height, 2) - dp(.1 * 1.5 ** self.elevation)
self._soft_shadow_pos = (x, y) self._soft_shadow_pos = (x, y)
self._soft_shadow_a = 0.1 * 1.1 ** self.elevation self._soft_shadow_a = 0.1 * 1.1 ** self.elevation
self._soft_shadow_texture = self._shadow.textures[ self._soft_shadow_texture = self._shadow.textures[
str(int(round(self.elevation)))] str(int(round(self.elevation)))]
y = self.center_y - height / 2 - dp(.5 * 1.18 ** self.elevation) y = self.center_y - old_div(height, 2) - dp(.5 * 1.18 ** self.elevation)
self._hard_shadow_pos = (x, y) self._hard_shadow_pos = (x, y)
self._hard_shadow_a = .4 * .9 ** self.elevation self._hard_shadow_a = .4 * .9 ** self.elevation
self._hard_shadow_texture = self._shadow.textures[ self._hard_shadow_texture = self._shadow.textures[

View File

@ -1,4 +1,12 @@
# coding=utf-8 # coding=utf-8
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from builtins import object
from kivy.lang import Builder from kivy.lang import Builder
from kivy.properties import StringProperty, BooleanProperty, ObjectProperty, \ from kivy.properties import StringProperty, BooleanProperty, ObjectProperty, \
NumericProperty, ListProperty, OptionProperty NumericProperty, ListProperty, OptionProperty
@ -154,14 +162,14 @@ class SmartTileWithLabel(SmartTile):
"""Determines the text for the box footer/header""" """Determines the text for the box footer/header"""
class IBoxOverlay(): class IBoxOverlay(object):
"""An interface to specify widgets that belong to to the image overlay """An interface to specify widgets that belong to to the image overlay
in the :class:`SmartTile` widget when added as a child. in the :class:`SmartTile` widget when added as a child.
""" """
pass pass
class IOverlay(): class IOverlay(object):
"""An interface to specify widgets that belong to to the image overlay """An interface to specify widgets that belong to to the image overlay
in the :class:`SmartTile` widget when added as a child. in the :class:`SmartTile` widget when added as a child.
""" """

View File

@ -8,6 +8,13 @@
# LAST UPDATED: version 2.2.0 of Material Design Iconic Font # LAST UPDATED: version 2.2.0 of Material Design Iconic Font
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
md_icons = { md_icons = {
'3d-rotation': u'', '3d-rotation': u'',

View File

@ -1,4 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.lang import Builder from kivy.lang import Builder
from kivy.metrics import sp from kivy.metrics import sp
from kivy.properties import OptionProperty, DictProperty, ListProperty from kivy.properties import OptionProperty, DictProperty, ListProperty

View File

@ -139,7 +139,15 @@ Python example:
API API
--- ---
''' '''
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from builtins import object
from kivy.lang import Builder from kivy.lang import Builder
from kivy.metrics import dp from kivy.metrics import dp
from kivy.properties import ObjectProperty, StringProperty, NumericProperty, \ from kivy.properties import ObjectProperty, StringProperty, NumericProperty, \
@ -338,7 +346,7 @@ class BaseListItem(ThemableBehavior, RectangularRippleBehavior,
_num_lines = 2 _num_lines = 2
class ILeftBody: class ILeftBody(object):
'''Pseudo-interface for widgets that go in the left container for '''Pseudo-interface for widgets that go in the left container for
ListItems that support it. ListItems that support it.
@ -347,14 +355,14 @@ class ILeftBody:
pass pass
class ILeftBodyTouch: class ILeftBodyTouch(object):
'''Same as :class:`~ILeftBody`, but allows the widget to receive touch '''Same as :class:`~ILeftBody`, but allows the widget to receive touch
events instead of triggering the ListItem's ripple effect events instead of triggering the ListItem's ripple effect
''' '''
pass pass
class IRightBody: class IRightBody(object):
'''Pseudo-interface for widgets that go in the right container for '''Pseudo-interface for widgets that go in the right container for
ListItems that support it. ListItems that support it.
@ -363,14 +371,14 @@ class IRightBody:
pass pass
class IRightBodyTouch: class IRightBodyTouch(object):
'''Same as :class:`~IRightBody`, but allows the widget to receive touch '''Same as :class:`~IRightBody`, but allows the widget to receive touch
events instead of triggering the ListItem's ripple effect events instead of triggering the ListItem's ripple effect
''' '''
pass pass
class ContainerSupport: class ContainerSupport(object):
'''Overrides add_widget in a ListItem to include support for I*Body '''Overrides add_widget in a ListItem to include support for I*Body
widgets when the appropiate containers are present. widgets when the appropiate containers are present.
''' '''

View File

@ -1,4 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy import platform from kivy import platform
from kivy.core.window import Window from kivy.core.window import Window
from kivy.metrics import dp from kivy.metrics import dp

View File

@ -1,4 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from past.utils import old_div
from kivy.animation import Animation from kivy.animation import Animation
from kivy.clock import Clock from kivy.clock import Clock
from kivy.core.window import Window from kivy.core.window import Window
@ -109,7 +117,7 @@ class MDDropdownMenu(ThemableBehavior, BoxLayout):
if target_width > Window.width: if target_width > Window.width:
# ...reduce our multiplier to max allowed. # ...reduce our multiplier to max allowed.
target_width = int( target_width = int(
Window.width / m_res.STANDARD_INCREMENT) * m_res.STANDARD_INCREMENT old_div(Window.width, m_res.STANDARD_INCREMENT)) * m_res.STANDARD_INCREMENT
target_height = sum([dp(48) for i in self.items]) target_height = sum([dp(48) for i in self.items])
# If we're over max_height... # If we're over max_height...

View File

@ -1,4 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.animation import Animation from kivy.animation import Animation
from kivy.lang import Builder from kivy.lang import Builder
from kivy.properties import StringProperty, ObjectProperty from kivy.properties import StringProperty, ObjectProperty

View File

@ -1,5 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.lang import Builder from kivy.lang import Builder
from kivy.properties import ListProperty, OptionProperty, BooleanProperty from kivy.properties import ListProperty, OptionProperty, BooleanProperty
from kivy.utils import get_color_from_hex from kivy.utils import get_color_from_hex

View File

@ -1,4 +1,13 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from past.utils import old_div
from builtins import object
from kivy.properties import ListProperty, NumericProperty, StringProperty, \ from kivy.properties import ListProperty, NumericProperty, StringProperty, \
BooleanProperty BooleanProperty
from kivy.animation import Animation from kivy.animation import Animation
@ -146,10 +155,10 @@ class CircularRippleBehavior(CommonRipple):
StencilPush() StencilPush()
self.stencil = Ellipse(size=(self.width * self.ripple_scale, self.stencil = Ellipse(size=(self.width * self.ripple_scale,
self.height * self.ripple_scale), self.height * self.ripple_scale),
pos=(self.center_x - ( pos=(self.center_x - old_div((
self.width * self.ripple_scale) / 2, self.width * self.ripple_scale), 2),
self.center_y - ( self.center_y - old_div((
self.height * self.ripple_scale) / 2)) self.height * self.ripple_scale), 2)))
StencilUse() StencilUse()
self.col_instruction = Color(rgba=self.ripple_color) self.col_instruction = Color(rgba=self.ripple_color)
self.ellipse = Ellipse(size=(self.ripple_rad, self.ripple_rad), self.ellipse = Ellipse(size=(self.ripple_rad, self.ripple_rad),

View File

@ -1,5 +1,13 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from past.utils import old_div
from kivy.lang import Builder from kivy.lang import Builder
from kivy.properties import StringProperty, ListProperty, NumericProperty from kivy.properties import StringProperty, ListProperty, NumericProperty
from kivy.uix.behaviors import ToggleButtonBehavior from kivy.uix.behaviors import ToggleButtonBehavior
@ -124,8 +132,8 @@ class Thumb(RoundElevationBehavior, CircularRippleBehavior, ButtonBehavior,
self.ellipse.pos = (self.center_x - self.ripple_rad / 2., self.ellipse.pos = (self.center_x - self.ripple_rad / 2.,
self.center_y - self.ripple_rad / 2.) self.center_y - self.ripple_rad / 2.)
self.stencil.pos = ( self.stencil.pos = (
self.center_x - (self.width * self.ripple_scale) / 2, self.center_x - old_div((self.width * self.ripple_scale), 2),
self.center_y - (self.height * self.ripple_scale) / 2) self.center_y - old_div((self.height * self.ripple_scale), 2))
class MDSwitch(ThemableBehavior, ButtonBehavior, FloatLayout): class MDSwitch(ThemableBehavior, ButtonBehavior, FloatLayout):

View File

@ -1,5 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.lang import Builder from kivy.lang import Builder
from kivy.properties import StringProperty, ListProperty, NumericProperty,AliasProperty, BooleanProperty from kivy.properties import StringProperty, ListProperty, NumericProperty,AliasProperty, BooleanProperty
from kivy.utils import get_color_from_hex from kivy.utils import get_color_from_hex

View File

@ -1,4 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.animation import Animation from kivy.animation import Animation
from kivy.clock import Clock from kivy.clock import Clock
from kivy.core.window import Window from kivy.core.window import Window

View File

@ -1,4 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from collections import deque from collections import deque
from kivy.animation import Animation from kivy.animation import Animation
from kivy.clock import Clock from kivy.clock import Clock

View File

@ -1,5 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.lang import Builder from kivy.lang import Builder
from kivy.uix.widget import Widget from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ListProperty, BooleanProperty from kivy.properties import NumericProperty, ListProperty, BooleanProperty

View File

@ -1,3 +1,7 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
# Created on Jul 8, 2016 # Created on Jul 8, 2016
# #
# The default kivy tab implementation seems like a stupid design to me. The # The default kivy tab implementation seems like a stupid design to me. The
@ -5,6 +9,10 @@
# #
# @author: jrm # @author: jrm
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
from kivy.properties import StringProperty, DictProperty, ListProperty, \ from kivy.properties import StringProperty, DictProperty, ListProperty, \
ObjectProperty, OptionProperty, BoundedNumericProperty ObjectProperty, OptionProperty, BoundedNumericProperty
from kivy.uix.screenmanager import Screen from kivy.uix.screenmanager import Screen

View File

@ -1,5 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.lang import Builder from kivy.lang import Builder
from kivy.uix.textinput import TextInput from kivy.uix.textinput import TextInput
from kivy.properties import ObjectProperty, NumericProperty, StringProperty, \ from kivy.properties import ObjectProperty, NumericProperty, StringProperty, \

View File

@ -1,5 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.lang import Builder from kivy.lang import Builder
from kivy.uix.modalview import ModalView from kivy.uix.modalview import ModalView
from kivy.uix.floatlayout import FloatLayout from kivy.uix.floatlayout import FloatLayout

View File

@ -1,4 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from builtins import object
from kivy.app import App from kivy.app import App
from kivy.core.text import LabelBase from kivy.core.text import LabelBase
from kivy.core.window import Window from kivy.core.window import Window

View File

@ -1,5 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.lang import Builder from kivy.lang import Builder
from kivy.uix.modalview import ModalView from kivy.uix.modalview import ModalView
from kivy.uix.floatlayout import FloatLayout from kivy.uix.floatlayout import FloatLayout

View File

@ -1,4 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.clock import Clock from kivy.clock import Clock
from kivy.lang import Builder from kivy.lang import Builder
from kivy.metrics import dp from kivy.metrics import dp

View File

@ -1,3 +1,11 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from builtins import object
from importlib import import_module from importlib import import_module
from os import path, listdir from os import path, listdir
from string import lower from string import lower

View File

@ -1,3 +1,11 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
from debug import logger from debug import logger
from messagetypes import MsgBase from messagetypes import MsgBase
@ -9,13 +17,13 @@ class Message(MsgBase):
def decode(self, data): def decode(self, data):
# UTF-8 and variable type validator # UTF-8 and variable type validator
if type(data["subject"]) is str: if type(data["subject"]) is str:
self.subject = unicode(data["subject"], 'utf-8', 'replace') self.subject = str(data["subject"], 'utf-8', 'replace')
else: else:
self.subject = unicode(str(data["subject"]), 'utf-8', 'replace') self.subject = str(str(data["subject"]), 'utf-8', 'replace')
if type(data["body"]) is str: if type(data["body"]) is str:
self.body = unicode(data["body"], 'utf-8', 'replace') self.body = str(data["body"], 'utf-8', 'replace')
else: else:
self.body = unicode(str(data["body"]), 'utf-8', 'replace') self.body = str(str(data["body"]), 'utf-8', 'replace')
def encode(self, data): def encode(self, data):
super(Message, self).encode() super(Message, self).encode()

View File

@ -1,3 +1,10 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from debug import logger from debug import logger
from messagetypes import MsgBase from messagetypes import MsgBase

View File

@ -1,4 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from kivy.animation import Animation from kivy.animation import Animation
from kivy.lang import Builder from kivy.lang import Builder
from kivy.properties import StringProperty, ObjectProperty from kivy.properties import StringProperty, ObjectProperty

View File

@ -1,4 +1,12 @@
import Queue from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
from builtins import *
import queue
import threading import threading
import addresses import addresses
@ -23,7 +31,7 @@ class AddrThread(threading.Thread, StoppableThread):
chunk.append((data[0], data[1])) chunk.append((data[0], data[1]))
if len(data) > 2: if len(data) > 2:
source = BMConnectionPool().getConnectionByAddr(data[2]) source = BMConnectionPool().getConnectionByAddr(data[2])
except Queue.Empty: except queue.Empty:
break break
except KeyError: except KeyError:
continue continue

View File

@ -2,8 +2,16 @@
src/network/advanceddispatcher.py src/network/advanceddispatcher.py
================================= =================================
""" """
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
# pylint: disable=attribute-defined-outside-init # pylint: disable=attribute-defined-outside-init
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
import socket import socket
import threading import threading
import time import time

View File

@ -1,3 +1,10 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import threading import threading
import time import time
@ -26,7 +33,7 @@ class AnnounceThread(threading.Thread, StoppableThread):
self.stop.wait(10) self.stop.wait(10)
def announceSelf(self): def announceSelf(self):
for connection in BMConnectionPool().udpSockets.values(): for connection in list(BMConnectionPool().udpSockets.values()):
if not connection.announcing: if not connection.announcing:
continue continue
for stream in state.streamsInWhichIAmParticipating: for stream in state.streamsInWhichIAmParticipating:

View File

@ -51,7 +51,15 @@ many of the difficult problems for you, making the task of building
sophisticated high-performance network servers and clients a snap. sophisticated high-performance network servers and clients a snap.
""" """
from __future__ import print_function from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
from builtins import object
import os import os
import select import select
import socket import socket
@ -366,7 +374,7 @@ def epoll_poller(timeout=0.0, map=None):
except AttributeError: except AttributeError:
epoll_poller.pollster = select.epoll() epoll_poller.pollster = select.epoll()
if map: if map:
for fd, obj in map.items(): for fd, obj in list(map.items()):
flags = newflags = 0 flags = newflags = 0
if obj.readable(): if obj.readable():
flags |= select.POLLIN | select.POLLPRI flags |= select.POLLIN | select.POLLPRI
@ -424,7 +432,7 @@ def kqueue_poller(timeout=0.0, map=None):
if map: if map:
updates = [] updates = []
selectables = 0 selectables = 0
for fd, obj in map.items(): for fd, obj in list(map.items()):
kq_filter = 0 kq_filter = 0
if obj.readable(): if obj.readable():
kq_filter |= 1 kq_filter |= 1
@ -521,7 +529,7 @@ def loop(timeout=30.0, use_poll=False, map=None, count=None, poller=None):
count = count - 1 count = count - 1
class dispatcher: class dispatcher(object):
"""Dispatcher for socket objects""" """Dispatcher for socket objects"""
# pylint: disable=too-many-public-methods,too-many-instance-attributes,old-style-class # pylint: disable=too-many-public-methods,too-many-instance-attributes,old-style-class
@ -999,7 +1007,7 @@ def close_all(map=None, ignore_all=False):
if os.name == 'posix': if os.name == 'posix':
import fcntl import fcntl
class file_wrapper: class file_wrapper(object):
""" """
Here we override just enough to make a file look like a socket for the purposes of asyncore. Here we override just enough to make a file look like a socket for the purposes of asyncore.

View File

@ -1,3 +1,11 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
from builtins import *
import random # nosec import random # nosec
import knownnodes import knownnodes
@ -10,7 +18,7 @@ from queues import Queue, portCheckerQueue
def getDiscoveredPeer(): def getDiscoveredPeer():
try: try:
peer = random.choice(state.discoveredPeers.keys()) peer = random.choice(list(state.discoveredPeers.keys()))
except (IndexError, KeyError): except (IndexError, KeyError):
raise ValueError raise ValueError
try: try:
@ -36,7 +44,7 @@ def chooseConnection(stream):
# discovered peers are already filtered by allowed streams # discovered peers are already filtered by allowed streams
return getDiscoveredPeer() return getDiscoveredPeer()
for _ in range(50): for _ in range(50):
peer = random.choice(knownnodes.knownNodes[stream].keys()) peer = random.choice(list(knownnodes.knownNodes[stream].keys()))
try: try:
rating = knownnodes.knownNodes[stream][peer]['rating'] rating = knownnodes.knownNodes[stream][peer]['rating']
except TypeError: except TypeError:

View File

@ -1,4 +1,11 @@
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import *
from past.utils import old_div
import threading import threading
import time import time
@ -28,7 +35,7 @@ class DownloadThread(threading.Thread, StoppableThread):
def cleanPending(self): def cleanPending(self):
deadline = time.time() - DownloadThread.requestExpires deadline = time.time() - DownloadThread.requestExpires
try: try:
toDelete = [k for k, v in missingObjects.iteritems() if v < deadline] toDelete = [k for k, v in missingObjects.items() if v < deadline]
except RuntimeError: except RuntimeError:
pass pass
else: else:
@ -40,10 +47,10 @@ class DownloadThread(threading.Thread, StoppableThread):
while not self._stopped: while not self._stopped:
requested = 0 requested = 0
# Choose downloading peers randomly # Choose downloading peers randomly
connections = [x for x in BMConnectionPool().inboundConnections.values() + BMConnectionPool().outboundConnections.values() if x.fullyEstablished] connections = [x for x in list(BMConnectionPool().inboundConnections.values()) + list(BMConnectionPool().outboundConnections.values()) if x.fullyEstablished]
helper_random.randomshuffle(connections) helper_random.randomshuffle(connections)
try: try:
requestChunk = max(int(min(DownloadThread.maxRequestChunk, len(missingObjects)) / len(connections)), 1) requestChunk = max(int(old_div(min(DownloadThread.maxRequestChunk, len(missingObjects)), len(connections))), 1)
except ZeroDivisionError: except ZeroDivisionError:
requestChunk = 1 requestChunk = 1
for i in connections: for i in connections:

View File

@ -1,4 +1,7 @@
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
@ -10,6 +13,14 @@ from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import map
from builtins import str
from builtins import range
from builtins import *
from past.utils import old_div
from builtins import object
import time import time
import protocol import protocol
@ -232,7 +243,7 @@ class ObjectTracker(object):
# release memory # release memory
deadline = time.time() - ObjectTracker.trackingExpires deadline = time.time() - ObjectTracker.trackingExpires
with self.objectsNewToThemLock: with self.objectsNewToThemLock:
self.objectsNewToThem = {k: v for k, v in self.objectsNewToThem.iteritems() if v >= deadline} self.objectsNewToThem = {k: v for k, v in self.objectsNewToThem.items() if v >= deadline}
self.lastCleaned = time.time() self.lastCleaned = time.time()
def hasObj(self, hashid): def hasObj(self, hashid):
@ -254,7 +265,7 @@ class ObjectTracker(object):
self.objectsNewToMe[hashId] = True self.objectsNewToMe[hashId] = True
def handleReceivedObject(self, streamNumber, hashid): def handleReceivedObject(self, streamNumber, hashid):
for i in BMConnectionPool().inboundConnections.values() + BMConnectionPool().outboundConnections.values(): for i in list(BMConnectionPool().inboundConnections.values()) + list(BMConnectionPool().outboundConnections.values()):
if not i.fullyEstablished: if not i.fullyEstablished:
continue continue
try: try:
@ -940,8 +951,8 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
def stopDownloadingObject(hashId, forwardAnyway=False): def stopDownloadingObject(hashId, forwardAnyway=False):
"""Stop downloading an object""" """Stop downloading an object"""
for connection in ( for connection in (
BMConnectionPool().inboundConnections.values() + list(BMConnectionPool().inboundConnections.values()) +
BMConnectionPool().outboundConnections.values() list(BMConnectionPool().outboundConnections.values())
): ):
try: try:
del connection.objectsNewToMe[hashId] del connection.objectsNewToMe[hashId]
@ -1038,7 +1049,7 @@ Stem = namedtuple('Stem', ['child', 'stream', 'timeout'])
@Singleton @Singleton
class Dandelion(): class Dandelion(object):
"""Dandelion class for tracking stem/fluff stages.""" """Dandelion class for tracking stem/fluff stages."""
def __init__(self): def __init__(self):
# currently assignable child stems # currently assignable child stems
@ -1110,12 +1121,12 @@ class Dandelion():
with self.lock: with self.lock:
if len(self.stem) < MAX_STEMS: if len(self.stem) < MAX_STEMS:
self.stem.append(connection) self.stem.append(connection)
for k in (k for k, v in self.nodeMap.iteritems() if v is None): for k in (k for k, v in self.nodeMap.items() if v is None):
self.nodeMap[k] = connection self.nodeMap[k] = connection
for k, v in { for k, v in {
k: v for k, v in self.hashMap.iteritems() k: v for k, v in self.hashMap.items()
if v.child is None if v.child is None
}.iteritems(): }.items():
self.hashMap[k] = Stem( self.hashMap[k] = Stem(
connection, v.stream, self.poissonTimeout()) connection, v.stream, self.poissonTimeout())
invQueue.put((v.stream, k, v.child)) invQueue.put((v.stream, k, v.child))
@ -1131,13 +1142,13 @@ class Dandelion():
self.stem.remove(connection) self.stem.remove(connection)
# active mappings to pointing to the removed node # active mappings to pointing to the removed node
for k in ( for k in (
k for k, v in self.nodeMap.iteritems() if v == connection k for k, v in self.nodeMap.items() if v == connection
): ):
self.nodeMap[k] = None self.nodeMap[k] = None
for k, v in { for k, v in {
k: v for k, v in self.hashMap.iteritems() k: v for k, v in self.hashMap.items()
if v.child == connection if v.child == connection
}.iteritems(): }.items():
self.hashMap[k] = Stem( self.hashMap[k] = Stem(
None, v.stream, self.poissonTimeout()) None, v.stream, self.poissonTimeout())
@ -1148,7 +1159,7 @@ class Dandelion():
""" """
try: try:
# pick a random from available stems # pick a random from available stems
stem = choice(range(len(self.stem))) stem = choice(list(range(len(self.stem))))
if self.stem[stem] == parent: if self.stem[stem] == parent:
# one stem available and it's the parent # one stem available and it's the parent
if len(self.stem) == 1: if len(self.stem) == 1:
@ -1178,7 +1189,7 @@ class Dandelion():
with self.lock: with self.lock:
deadline = time.time() deadline = time.time()
toDelete = [ toDelete = [
[v.stream, k, v.child] for k, v in self.hashMap.iteritems() [v.stream, k, v.child] for k, v in self.hashMap.items()
if v.timeout < deadline if v.timeout < deadline
] ]
@ -1193,12 +1204,12 @@ class Dandelion():
try: try:
# random two connections # random two connections
self.stem = sample( self.stem = sample(
BMConnectionPool( list(BMConnectionPool(
).outboundConnections.values(), MAX_STEMS) ).outboundConnections.values()), MAX_STEMS)
# not enough stems available # not enough stems available
except ValueError: except ValueError:
self.stem = BMConnectionPool( self.stem = list(BMConnectionPool(
).outboundConnections.values() ).outboundConnections.values())
self.nodeMap = {} self.nodeMap = {}
# hashMap stays to cater for pending stems # hashMap stays to cater for pending stems
self.refresh = time.time() + REASSIGN_INTERVAL self.refresh = time.time() + REASSIGN_INTERVAL
@ -1281,8 +1292,8 @@ class BMConnectionPool(object):
def isAlreadyConnected(self, nodeid): def isAlreadyConnected(self, nodeid):
"""Check if we're already connected to this peer""" """Check if we're already connected to this peer"""
for i in ( for i in (
self.inboundConnections.values() + list(self.inboundConnections.values()) +
self.outboundConnections.values() list(self.outboundConnections.values())
): ):
try: try:
if nodeid == i.nodeid: if nodeid == i.nodeid:
@ -1414,7 +1425,7 @@ class BMConnectionPool(object):
except ValueError: except ValueError:
Proxy.onion_proxy = None Proxy.onion_proxy = None
established = sum( established = sum(
1 for c in self.outboundConnections.values() 1 for c in list(self.outboundConnections.values())
if (c.connected and c.fullyEstablished)) if (c.connected and c.fullyEstablished))
pending = len(self.outboundConnections) - established pending = len(self.outboundConnections) - established
if established < BMConfigParser().safeGetInt( if established < BMConfigParser().safeGetInt(
@ -1454,8 +1465,8 @@ class BMConnectionPool(object):
self.lastSpawned = time.time() self.lastSpawned = time.time()
else: else:
for i in ( for i in (
self.inboundConnections.values() + list(self.inboundConnections.values()) +
self.outboundConnections.values() list(self.outboundConnections.values())
): ):
# FIXME: rating will be increased after next connection # FIXME: rating will be increased after next connection
i.handle_close() i.handle_close()
@ -1484,12 +1495,12 @@ class BMConnectionPool(object):
logger.info('Starting UDP socket(s).') logger.info('Starting UDP socket(s).')
else: else:
if self.listeningSockets: if self.listeningSockets:
for i in self.listeningSockets.values(): for i in list(self.listeningSockets.values()):
i.close_reason = "Stopping listening" i.close_reason = "Stopping listening"
i.accepting = i.connecting = i.connected = False i.accepting = i.connecting = i.connected = False
logger.info('Stopped listening for incoming connections.') logger.info('Stopped listening for incoming connections.')
if self.udpSockets: if self.udpSockets:
for i in self.udpSockets.values(): for i in list(self.udpSockets.values()):
i.close_reason = "Stopping UDP socket" i.close_reason = "Stopping UDP socket"
i.accepting = i.connecting = i.connected = False i.accepting = i.connecting = i.connected = False
logger.info('Stopped udp sockets.') logger.info('Stopped udp sockets.')
@ -1501,8 +1512,8 @@ class BMConnectionPool(object):
reaper = [] reaper = []
for i in ( for i in (
self.inboundConnections.values() + list(self.inboundConnections.values()) +
self.outboundConnections.values() list(self.outboundConnections.values())
): ):
minTx = time.time() - 20 minTx = time.time() - 20
if i.fullyEstablished: if i.fullyEstablished:
@ -1515,10 +1526,10 @@ class BMConnectionPool(object):
time.time() - i.lastTx) time.time() - i.lastTx)
i.set_state("close") i.set_state("close")
for i in ( for i in (
self.inboundConnections.values() + list(self.inboundConnections.values()) +
self.outboundConnections.values() + list(self.outboundConnections.values()) +
self.listeningSockets.values() + list(self.listeningSockets.values()) +
self.udpSockets.values() list(self.udpSockets.values())
): ):
if not (i.accepting or i.connecting or i.connected): if not (i.accepting or i.connecting or i.connected):
reaper.append(i) reaper.append(i)
@ -1695,7 +1706,7 @@ class TCPConnection(BMProto, TLSDispatcher):
# only if more recent than 3 hours # only if more recent than 3 hours
# and having positive or neutral rating # and having positive or neutral rating
filtered = [ filtered = [
(k, v) for k, v in nodes.iteritems() (k, v) for k, v in nodes.items()
if v["lastseen"] > int(time.time()) - if v["lastseen"] > int(time.time()) -
shared.maximumAgeOfNodesThatIAdvertiseToOthers and shared.maximumAgeOfNodesThatIAdvertiseToOthers and
v["rating"] >= 0 and len(k.host) <= 22 v["rating"] >= 0 and len(k.host) <= 22
@ -1703,7 +1714,7 @@ class TCPConnection(BMProto, TLSDispatcher):
# sent 250 only if the remote isn't interested in it # sent 250 only if the remote isn't interested in it
elemCount = min( elemCount = min(
len(filtered), len(filtered),
maxAddrCount / 2 if n else maxAddrCount) old_div(maxAddrCount, 2) if n else maxAddrCount)
addrs[s] = helper_random.randomsample(filtered, elemCount) addrs[s] = helper_random.randomsample(filtered, elemCount)
for substream in addrs: for substream in addrs:
for peer, params in addrs[substream]: for peer, params in addrs[substream]:
@ -1741,7 +1752,7 @@ class TCPConnection(BMProto, TLSDispatcher):
payload = b'' payload = b''
# Now let us start appending all of these hashes together. They will be # Now let us start appending all of these hashes together. They will be
# sent out in a big inv message to our new peer. # sent out in a big inv message to our new peer.
for obj_hash, _ in bigInvList.items(): for obj_hash, _ in list(bigInvList.items()):
payload += obj_hash payload += obj_hash
objectCount += 1 objectCount += 1

View File

@ -1,4 +1,12 @@
from __future__ import print_function from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
from builtins import *
from past.utils import old_div
import asyncore import asyncore
import socket import socket
import time import time
@ -45,6 +53,6 @@ if __name__ == "__main__":
for i in range(parallel - len(asyncore.socket_map)): for i in range(parallel - len(asyncore.socket_map)):
HTTPClient('127.0.0.1', '/') HTTPClient('127.0.0.1', '/')
print("Active connections: %i" % (len(asyncore.socket_map))) print("Active connections: %i" % (len(asyncore.socket_map)))
asyncore.loop(count=len(asyncore.socket_map)/2) asyncore.loop(count=old_div(len(asyncore.socket_map),2))
if requestCount % 100 == 0: if requestCount % 100 == 0:
print("Processed %i total messages" % (requestCount)) print("Processed %i total messages" % (requestCount))

View File

@ -1,5 +1,10 @@
from __future__ import print_function from __future__ import print_function
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import *
import socket import socket
from .advanceddispatcher import AdvancedDispatcher from .advanceddispatcher import AdvancedDispatcher

View File

@ -1,4 +1,10 @@
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import *
import asyncore import asyncore
import socket import socket

View File

@ -1,4 +1,10 @@
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import *
import asyncore import asyncore
from .http import HTTPClient from .http import HTTPClient

View File

@ -1,4 +1,12 @@
import Queue from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
from builtins import *
import queue
from random import randint, shuffle from random import randint, shuffle
import threading import threading
from time import time from time import time
@ -18,8 +26,8 @@ def handleExpiredDandelion(expired):
if not expired: if not expired:
return return
for i in \ for i in \
BMConnectionPool().inboundConnections.values() + \ list(BMConnectionPool().inboundConnections.values()) + \
BMConnectionPool().outboundConnections.values(): list(BMConnectionPool().outboundConnections.values()):
if not i.fullyEstablished: if not i.fullyEstablished:
continue continue
for x in expired: for x in expired:
@ -41,8 +49,8 @@ class InvThread(threading.Thread, StoppableThread):
def handleLocallyGenerated(self, stream, hashId): def handleLocallyGenerated(self, stream, hashId):
Dandelion().addHash(hashId, stream=stream) Dandelion().addHash(hashId, stream=stream)
for connection in \ for connection in \
BMConnectionPool().inboundConnections.values() + \ list(BMConnectionPool().inboundConnections.values()) + \
BMConnectionPool().outboundConnections.values(): list(BMConnectionPool().outboundConnections.values()):
if state.dandelion and connection != Dandelion().objectChildStem(hashId): if state.dandelion and connection != Dandelion().objectChildStem(hashId):
continue continue
connection.objectsNewToThem[hashId] = time() connection.objectsNewToThem[hashId] = time()
@ -59,12 +67,12 @@ class InvThread(threading.Thread, StoppableThread):
# locally generated # locally generated
if len(data) == 2 or data[2] is None: if len(data) == 2 or data[2] is None:
self.handleLocallyGenerated(data[0], data[1]) self.handleLocallyGenerated(data[0], data[1])
except Queue.Empty: except queue.Empty:
break break
if chunk: if chunk:
for connection in BMConnectionPool().inboundConnections.values() + \ for connection in list(BMConnectionPool().inboundConnections.values()) + \
BMConnectionPool().outboundConnections.values(): list(BMConnectionPool().outboundConnections.values()):
fluffs = [] fluffs = []
stems = [] stems = []
for inv in chunk: for inv in chunk:

View File

@ -1,3 +1,10 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import threading import threading
import network.asyncore_pollchoose as asyncore import network.asyncore_pollchoose as asyncore
@ -25,17 +32,17 @@ class BMNetworkThread(threading.Thread, StoppableThread):
def stopThread(self): def stopThread(self):
super(BMNetworkThread, self).stopThread() super(BMNetworkThread, self).stopThread()
for i in BMConnectionPool().listeningSockets.values(): for i in list(BMConnectionPool().listeningSockets.values()):
try: try:
i.close() i.close()
except: except:
pass pass
for i in BMConnectionPool().outboundConnections.values(): for i in list(BMConnectionPool().outboundConnections.values()):
try: try:
i.close() i.close()
except: except:
pass pass
for i in BMConnectionPool().inboundConnections.values(): for i in list(BMConnectionPool().inboundConnections.values()):
try: try:
i.close() i.close()
except: except:

View File

@ -1,3 +1,10 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import collections import collections
Node = collections.namedtuple('Node', ['services', 'host', 'port']) Node = collections.namedtuple('Node', ['services', 'host', 'port'])

View File

@ -1,4 +1,10 @@
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import *
import socket import socket
import time import time

View File

@ -1,5 +1,13 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
import errno import errno
import Queue import queue
import socket import socket
import sys import sys
import threading import threading
@ -27,7 +35,7 @@ class ReceiveQueueThread(threading.Thread, StoppableThread):
while not self._stopped and state.shutdown == 0: while not self._stopped and state.shutdown == 0:
try: try:
dest = receiveDataQueue.get(block=True, timeout=1) dest = receiveDataQueue.get(block=True, timeout=1)
except Queue.Empty: except queue.Empty:
continue continue
if self._stopped or state.shutdown: if self._stopped or state.shutdown:

View File

@ -1,5 +1,11 @@
from __future__ import print_function from __future__ import print_function
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import chr
from builtins import *
import socket import socket
import struct import struct

View File

@ -5,8 +5,15 @@ src/network/socks5.py
""" """
from __future__ import print_function from __future__ import print_function
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
# pylint: disable=attribute-defined-outside-init # pylint: disable=attribute-defined-outside-init
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import chr
from builtins import *
import socket import socket
import struct import struct

View File

@ -1,4 +1,11 @@
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import *
from past.utils import old_div
import time import time
from . import asyncore_pollchoose as asyncore from . import asyncore_pollchoose as asyncore
@ -13,8 +20,8 @@ currentSentSpeed = 0
def connectedHostsList(): def connectedHostsList():
retval = [] retval = []
for i in BMConnectionPool().inboundConnections.values() + \ for i in list(BMConnectionPool().inboundConnections.values()) + \
BMConnectionPool().outboundConnections.values(): list(BMConnectionPool().outboundConnections.values()):
if not i.fullyEstablished: if not i.fullyEstablished:
continue continue
try: try:
@ -31,7 +38,7 @@ def uploadSpeed():
currentTimestamp = time.time() currentTimestamp = time.time()
if int(lastSentTimestamp) < int(currentTimestamp): if int(lastSentTimestamp) < int(currentTimestamp):
currentSentBytes = asyncore.sentBytes currentSentBytes = asyncore.sentBytes
currentSentSpeed = int((currentSentBytes - lastSentBytes) / (currentTimestamp - lastSentTimestamp)) currentSentSpeed = int(old_div((currentSentBytes - lastSentBytes), (currentTimestamp - lastSentTimestamp)))
lastSentBytes = currentSentBytes lastSentBytes = currentSentBytes
lastSentTimestamp = currentTimestamp lastSentTimestamp = currentTimestamp
return currentSentSpeed return currentSentSpeed
@ -44,8 +51,8 @@ def downloadSpeed():
currentTimestamp = time.time() currentTimestamp = time.time()
if int(lastReceivedTimestamp) < int(currentTimestamp): if int(lastReceivedTimestamp) < int(currentTimestamp):
currentReceivedBytes = asyncore.receivedBytes currentReceivedBytes = asyncore.receivedBytes
currentReceivedSpeed = int((currentReceivedBytes - lastReceivedBytes) / currentReceivedSpeed = int(old_div((currentReceivedBytes - lastReceivedBytes),
(currentTimestamp - lastReceivedTimestamp)) (currentTimestamp - lastReceivedTimestamp)))
lastReceivedBytes = currentReceivedBytes lastReceivedBytes = currentReceivedBytes
lastReceivedTimestamp = currentTimestamp lastReceivedTimestamp = currentTimestamp
return currentReceivedSpeed return currentReceivedSpeed

View File

@ -1,7 +1,15 @@
""" """
SSL/TLS negotiation. SSL/TLS negotiation.
""" """
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
import os import os
import socket import socket
import ssl import ssl

View File

@ -1,4 +1,11 @@
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
import time import time
import socket import socket

View File

@ -1,7 +1,14 @@
""" """
src/network/uploadthread.py src/network/uploadthread.py
""" """
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
# pylint: disable=unsubscriptable-object # pylint: disable=unsubscriptable-object
from future import standard_library
standard_library.install_aliases()
from builtins import *
import threading import threading
import time import time
@ -28,8 +35,8 @@ class UploadThread(threading.Thread, StoppableThread):
while not self._stopped: while not self._stopped:
uploaded = 0 uploaded = 0
# Choose downloading peers randomly # Choose downloading peers randomly
connections = [x for x in BMConnectionPool().inboundConnections.values() + connections = [x for x in list(BMConnectionPool().inboundConnections.values()) +
BMConnectionPool().outboundConnections.values() if x.fullyEstablished] list(BMConnectionPool().outboundConnections.values()) if x.fullyEstablished]
helper_random.randomshuffle(connections) helper_random.randomshuffle(connections)
for i in connections: for i in connections:
now = time.time() now = time.time()

View File

@ -1,5 +1,15 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import zip
from builtins import str
from builtins import *
from builtins import object
import gi import gi
gi.require_version('MessagingMenu', '1.0') # noqa:E402 gi.require_version('MessagingMenu', '1.0') # noqa:E402
from gi.repository import MessagingMenu from gi.repository import MessagingMenu
@ -19,9 +29,9 @@ class IndicatorLibmessaging(object):
return return
self._menu = { self._menu = {
'send': unicode(_translate('MainWindow', 'Send')), 'send': str(_translate('MainWindow', 'Send')),
'messages': unicode(_translate('MainWindow', 'Messages')), 'messages': str(_translate('MainWindow', 'Messages')),
'subscriptions': unicode(_translate('MainWindow', 'Subscriptions')) 'subscriptions': str(_translate('MainWindow', 'Subscriptions'))
} }
self.new_message_item = self.new_broadcast_item = None self.new_message_item = self.new_broadcast_item = None

View File

@ -2,8 +2,15 @@
""" """
A menu plugin showing QR-Code for bitmessage address in modal dialog. A menu plugin showing QR-Code for bitmessage address in modal dialog.
""" """
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import urllib from future import standard_library
standard_library.install_aliases()
from builtins import *
import urllib.request, urllib.parse, urllib.error
import qrcode import qrcode
from PyQt4 import QtGui, QtCore from PyQt4 import QtGui, QtCore
@ -91,7 +98,7 @@ def connect_plugin(form):
return return
dialog.render( dialog.render(
'bitmessage:%s' % account.address + ( 'bitmessage:%s' % account.address + (
'?' + urllib.urlencode({'label': label.encode('utf-8')}) '?' + urllib.parse.urlencode({'label': label.encode('utf-8')})
if label != account.address else '') if label != account.address else '')
) )
dialog.exec_() dialog.exec_()

View File

@ -1,5 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import gi import gi
gi.require_version('Notify', '0.7') gi.require_version('Notify', '0.7')
from gi.repository import Notify from gi.repository import Notify

View File

@ -1,5 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import pkg_resources import pkg_resources

View File

@ -1,5 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from pybitmessage.bitmessageqt import sound from pybitmessage.bitmessageqt import sound
import pycanberra import pycanberra

View File

@ -1,5 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import gi import gi
gi.require_version('Gst', '1.0') gi.require_version('Gst', '1.0')
from gi.repository import Gst # noqa: E402 from gi.repository import Gst # noqa: E402

View File

@ -1,6 +1,13 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
try: try:
import winsound import winsound

View File

@ -1,7 +1,14 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
# Copyright (C) 2010 # Copyright (C) 2010
# Author: Yann GUIBET # Author: Yann GUIBET
# Contact: <yannguibet@gmail.com> # Contact: <yannguibet@gmail.com>
from future import standard_library
standard_library.install_aliases()
from builtins import *
__version__ = '1.3' __version__ = '1.3'
__all__ = [ __all__ = [

View File

@ -1,5 +1,15 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
# pylint: disable=missing-docstring,too-many-function-args # pylint: disable=missing-docstring,too-many-function-args
from future import standard_library
standard_library.install_aliases()
from builtins import chr
from builtins import range
from builtins import *
from past.utils import old_div
import hashlib import hashlib
import re import re
@ -14,7 +24,7 @@ def inv(a, n):
lm, hm = 1, 0 lm, hm = 1, 0
low, high = a % n, n low, high = a % n, n
while low > 1: while low > 1:
r = high / low r = old_div(high, low)
nm, new = hm - lm * r, high - low * r nm, new = hm - lm * r, high - low * r
lm, low, hm, high = nm, new, lm, low lm, low, hm, high = nm, new, lm, low
return lm % n return lm % n
@ -92,9 +102,9 @@ def base10_multiply(a, n):
if n == 1: if n == 1:
return a return a
if (n % 2) == 0: if (n % 2) == 0:
return base10_double(base10_multiply(a, n / 2)) return base10_double(base10_multiply(a, old_div(n, 2)))
if (n % 2) == 1: if (n % 2) == 1:
return base10_add(base10_double(base10_multiply(a, n / 2)), a) return base10_add(base10_double(base10_multiply(a, old_div(n, 2))), a)
return None return None

View File

@ -4,10 +4,18 @@
# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com> # Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>
# See LICENSE for details. # See LICENSE for details.
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from builtins import object
from pyelliptic.openssl import OpenSSL from pyelliptic.openssl import OpenSSL
class Cipher: class Cipher(object):
""" """
Symmetric encryption Symmetric encryption
@ -40,7 +48,7 @@ class Cipher:
""" """
static method, returns all ciphers available static method, returns all ciphers available
""" """
return OpenSSL.cipher_algo.keys() return list(OpenSSL.cipher_algo.keys())
@staticmethod @staticmethod
def get_blocksize(ciphername): def get_blocksize(ciphername):

View File

@ -4,11 +4,19 @@
src/pyelliptic/ecc.py src/pyelliptic/ecc.py
===================== =====================
""" """
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
# pylint: disable=protected-access # pylint: disable=protected-access
# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com> # Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>
# See LICENSE for details. # See LICENSE for details.
from future import standard_library
standard_library.install_aliases()
from builtins import *
from builtins import object
from hashlib import sha512 from hashlib import sha512
from struct import pack, unpack from struct import pack, unpack
@ -94,7 +102,7 @@ class ECC(object):
""" """
static method, returns the list of all the curves available static method, returns the list of all the curves available
""" """
return OpenSSL.curves.keys() return list(OpenSSL.curves.keys())
def get_curve(self): def get_curve(self):
"""Encryption object from curve name""" """Encryption object from curve name"""

View File

@ -4,6 +4,14 @@
# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com> # Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>
# See LICENSE for details. # See LICENSE for details.
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import zip
from builtins import *
from pyelliptic.openssl import OpenSSL from pyelliptic.openssl import OpenSSL

View File

@ -6,13 +6,23 @@
# #
# Software slightly changed by Jonathan Warren <bitmessage at-symbol jonwarren.org> # Software slightly changed by Jonathan Warren <bitmessage at-symbol jonwarren.org>
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import *
from past.utils import old_div
from builtins import object
import sys import sys
import ctypes import ctypes
OpenSSL = None OpenSSL = None
class CipherName: class CipherName(object):
def __init__(self, name, pointer, blocksize): def __init__(self, name, pointer, blocksize):
self._name = name self._name = name
self._pointer = pointer self._pointer = pointer
@ -62,7 +72,7 @@ def get_version(library):
return (version, hexversion, cflags) return (version, hexversion, cflags)
class _OpenSSL: class _OpenSSL(object):
""" """
Wrapper for OpenSSL using ctypes Wrapper for OpenSSL using ctypes
""" """
@ -434,7 +444,7 @@ class _OpenSSL:
""" """
returns the length of a BN (OpenSSl API) returns the length of a BN (OpenSSl API)
""" """
return int((self.BN_num_bits(x) + 7) / 8) return int(old_div((self.BN_num_bits(x) + 7), 8))
def get_cipher(self, name): def get_cipher(self, name):
""" """

View File

@ -40,7 +40,16 @@ Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/)
mainly to merge bug fixes found in Sourceforge mainly to merge bug fixes found in Sourceforge
""" """
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import chr
from builtins import *
import socket import socket
import struct import struct
import sys import sys

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