Commit 256ac99d authored by Arnaud Fontaine's avatar Arnaud Fontaine

2to3: Make Products code compatible with both python2 and python3.

python-modernize -w -f dict_six product/
parent d12a23fe
...@@ -101,7 +101,7 @@ class ActiveProcess(Base): ...@@ -101,7 +101,7 @@ class ActiveProcess(Base):
# use a random id in order to store result in a way with # use a random id in order to store result in a way with
# fewer conflict errors # fewer conflict errors
random_id = randrange(0, 10000 * (self.result_len.value + 1)) random_id = randrange(0, 10000 * (self.result_len.value + 1))
while result_list.has_key(random_id): while random_id in result_list:
random_id += 1 random_id += 1
result_list[random_id] = result result_list[random_id] = result
self.result_len.change(1) self.result_len.change(1)
...@@ -132,7 +132,7 @@ class ActiveProcess(Base): ...@@ -132,7 +132,7 @@ class ActiveProcess(Base):
# moment, although this is inefficient and the caller never needs a # moment, although this is inefficient and the caller never needs a
# copy (currently). Same for IOBTree.itervalues(). # copy (currently). Same for IOBTree.itervalues().
if type(result_list) is not ConflictFreeLog: # BBB: result_list is IOBTree if type(result_list) is not ConflictFreeLog: # BBB: result_list is IOBTree
return result_list.values() return list(result_list.values())
return list(result_list) return list(result_list)
security.declareProtected(CMFCorePermissions.ManagePortal, 'getResultDict') security.declareProtected(CMFCorePermissions.ManagePortal, 'getResultDict')
......
...@@ -31,7 +31,6 @@ from hashlib import sha1 ...@@ -31,7 +31,6 @@ from hashlib import sha1
from DateTime import DateTime from DateTime import DateTime
from zLOG import LOG, WARNING, ERROR from zLOG import LOG, WARNING, ERROR
from ZODB.POSException import ConflictError from ZODB.POSException import ConflictError
from cStringIO import StringIO
# Time global parameters # Time global parameters
MAX_PROCESSING_TIME = 900 # in seconds MAX_PROCESSING_TIME = 900 # in seconds
......
...@@ -48,6 +48,7 @@ from .Queue import Queue, VALIDATION_ERROR_DELAY ...@@ -48,6 +48,7 @@ from .Queue import Queue, VALIDATION_ERROR_DELAY
from Products.CMFActivity.Errors import ActivityFlushError from Products.CMFActivity.Errors import ActivityFlushError
from Products.ERP5Type import Timeout from Products.ERP5Type import Timeout
from Products.ERP5Type.Timeout import TimeoutReachedError, Deadline from Products.ERP5Type.Timeout import TimeoutReachedError, Deadline
import six
# Stop validating more messages when this limit is reached # Stop validating more messages when this limit is reached
MAX_VALIDATED_LIMIT = 1000 MAX_VALIDATED_LIMIT = 1000
...@@ -363,7 +364,7 @@ CREATE TABLE %s ( ...@@ -363,7 +364,7 @@ CREATE TABLE %s (
# value should be ignored, instead of trying to render them # value should be ignored, instead of trying to render them
# (with comparisons with NULL). # (with comparisons with NULL).
q = db.string_literal q = db.string_literal
sql = '\n AND '.join(sqltest_dict[k](v, q) for k, v in kw.iteritems()) sql = '\n AND '.join(sqltest_dict[k](v, q) for k, v in six.iteritems(kw))
sql = "SELECT * FROM %s%s\nORDER BY priority, date, uid%s" % ( sql = "SELECT * FROM %s%s\nORDER BY priority, date, uid%s" % (
self.sql_table, self.sql_table,
sql and '\nWHERE ' + sql, sql and '\nWHERE ' + sql,
...@@ -386,11 +387,11 @@ CREATE TABLE %s ( ...@@ -386,11 +387,11 @@ CREATE TABLE %s (
def countMessageSQL(self, quote, **kw): def countMessageSQL(self, quote, **kw):
return "SELECT count(*) FROM %s WHERE processing_node > %d AND %s" % ( return "SELECT count(*) FROM %s WHERE processing_node > %d AND %s" % (
self.sql_table, DEPENDENCY_IGNORED_ERROR_STATE, " AND ".join( self.sql_table, DEPENDENCY_IGNORED_ERROR_STATE, " AND ".join(
sqltest_dict[k](v, quote) for (k, v) in kw.iteritems() if v sqltest_dict[k](v, quote) for (k, v) in six.iteritems(kw) if v
) or "1") ) or "1")
def hasActivitySQL(self, quote, only_valid=False, only_invalid=False, **kw): def hasActivitySQL(self, quote, only_valid=False, only_invalid=False, **kw):
where = [sqltest_dict[k](v, quote) for (k, v) in kw.iteritems() if v] where = [sqltest_dict[k](v, quote) for (k, v) in six.iteritems(kw) if v]
if only_valid: if only_valid:
where.append('processing_node > %d' % INVOKE_ERROR_STATE) where.append('processing_node > %d' % INVOKE_ERROR_STATE)
if only_invalid: if only_invalid:
...@@ -469,7 +470,7 @@ CREATE TABLE %s ( ...@@ -469,7 +470,7 @@ CREATE TABLE %s (
for ( for (
dependency_name, dependency_name,
dependency_value, dependency_value,
) in message.activity_kw.iteritems(): ) in six.iteritems(message.activity_kw):
try: try:
column_list, _, _ = dependency_tester_dict[dependency_name] column_list, _, _ = dependency_tester_dict[dependency_name]
except KeyError: except KeyError:
...@@ -542,13 +543,13 @@ CREATE TABLE %s ( ...@@ -542,13 +543,13 @@ CREATE TABLE %s (
dependency_name, dependency_name,
dependency_value_dict, dependency_value_dict,
) in sorted( ) in sorted(
dependency_dict.iteritems(), six.iteritems(dependency_dict),
# Test first the condition with the most values. # Test first the condition with the most values.
# XXX: after_path=('foo', 'bar') counts as 2 points for after_path # XXX: after_path=('foo', 'bar') counts as 2 points for after_path
# despite being a single activity. Is there a fairer (while cheap) way ? # despite being a single activity. Is there a fairer (while cheap) way ?
key=lambda dependency_dict_item: sum( key=lambda dependency_dict_item: sum(
len(message_set) len(message_set)
for message_set in dependency_dict_item[1].itervalues() for message_set in six.itervalues(dependency_dict_item[1])
), ),
reverse=True, reverse=True,
): ):
...@@ -561,7 +562,7 @@ CREATE TABLE %s ( ...@@ -561,7 +562,7 @@ CREATE TABLE %s (
for ( for (
message_dependency_name, message_dependency_name,
message_dependency_value_list, message_dependency_value_list,
) in message_dependency_dict[blocked_message].iteritems(): ) in six.iteritems(message_dependency_dict[blocked_message]):
message_dependency_value_dict = dependency_dict[message_dependency_name] message_dependency_value_dict = dependency_dict[message_dependency_name]
if not message_dependency_value_dict: if not message_dependency_value_dict:
# This dependency was already dropped or evaluated, nothing to # This dependency was already dropped or evaluated, nothing to
...@@ -653,7 +654,7 @@ CREATE TABLE %s ( ...@@ -653,7 +654,7 @@ CREATE TABLE %s (
else: else:
serialization_tag_dict.setdefault(serialization_tag, serialization_tag_dict.setdefault(serialization_tag,
[]).append(message) []).append(message)
for message_list in serialization_tag_dict.itervalues(): for message_list in six.itervalues(serialization_tag_dict):
# Sort list of messages to validate the message with highest score # Sort list of messages to validate the message with highest score
message_list.sort(key=sort_message_key) message_list.sort(key=sort_message_key)
distributable_uid_set.add(message_list[0].uid) distributable_uid_set.add(message_list[0].uid)
...@@ -858,7 +859,7 @@ CREATE TABLE %s ( ...@@ -858,7 +859,7 @@ CREATE TABLE %s (
self._log(WARNING, 'Exception while reserving messages.') self._log(WARNING, 'Exception while reserving messages.')
if uid_to_duplicate_uid_list_dict: if uid_to_duplicate_uid_list_dict:
to_free_uid_list = uid_to_duplicate_uid_list_dict.keys() to_free_uid_list = uid_to_duplicate_uid_list_dict.keys()
for uid_list in uid_to_duplicate_uid_list_dict.itervalues(): for uid_list in six.itervalues(uid_to_duplicate_uid_list_dict):
to_free_uid_list += uid_list to_free_uid_list += uid_list
try: try:
self.assignMessageList(db, 0, to_free_uid_list) self.assignMessageList(db, 0, to_free_uid_list)
......
...@@ -37,6 +37,7 @@ from .SQLBase import ( ...@@ -37,6 +37,7 @@ from .SQLBase import (
) )
from Products.CMFActivity.ActivityTool import Message from Products.CMFActivity.ActivityTool import Message
from .SQLDict import SQLDict from .SQLDict import SQLDict
from six.moves import xrange
class SQLJoblib(SQLDict): class SQLJoblib(SQLDict):
""" """
...@@ -94,8 +95,8 @@ CREATE TABLE %s ( ...@@ -94,8 +95,8 @@ CREATE TABLE %s (
db.query("SET @uid := %s" % getrandbits(UID_SAFE_BITSIZE)) db.query("SET @uid := %s" % getrandbits(UID_SAFE_BITSIZE))
try: try:
db.query(self._insert_template % (self.sql_table, values)) db.query(self._insert_template % (self.sql_table, values))
except MySQLdb.IntegrityError, (code, _): except MySQLdb.IntegrityError as e:
if code != DUP_ENTRY: if e.args[0] != DUP_ENTRY:
raise raise
reset_uid = True reset_uid = True
else: else:
......
...@@ -28,6 +28,7 @@ from zLOG import LOG, ERROR ...@@ -28,6 +28,7 @@ from zLOG import LOG, ERROR
from collections import defaultdict from collections import defaultdict
import transaction import transaction
import six
class ActivityBuffer(TM): class ActivityBuffer(TM):
activity_tool = None activity_tool = None
...@@ -59,7 +60,7 @@ class ActivityBuffer(TM): ...@@ -59,7 +60,7 @@ class ActivityBuffer(TM):
try: try:
activity_tool = self.activity_tool activity_tool = self.activity_tool
# Try to push all messages # Try to push all messages
for activity, message_list in self.message_list_dict.iteritems(): for activity, message_list in six.iteritems(self.message_list_dict):
activity.prepareQueueMessageList(activity_tool, message_list) activity.prepareQueueMessageList(activity_tool, message_list)
self.message_list_dict.clear() self.message_list_dict.clear()
self.activity_tool = None self.activity_tool = None
......
This diff is collapsed.
...@@ -22,6 +22,7 @@ ...@@ -22,6 +22,7 @@
# #
############################################################################## ##############################################################################
from __future__ import print_function
SBALANCE_VERSION = '4.0' SBALANCE_VERSION = '4.0'
import sys import sys
...@@ -90,17 +91,17 @@ class Balancer: ...@@ -90,17 +91,17 @@ class Balancer:
try: try:
# Make a thread for expiration of old sticky entries. # Make a thread for expiration of old sticky entries.
if self.debug: if self.debug:
print "Starting an expiring daemon thread" print("Starting an expiring daemon thread")
t = threading.Thread(target=Balancer.expire, args=(self,)) t = threading.Thread(target=Balancer.expire, args=(self,))
t.setDaemon(1) t.setDaemon(1)
t.start() t.start()
if self.debug: if self.debug:
print "Beginning the main loop to accept clients" print("Beginning the main loop to accept clients")
while 1: while 1:
conn, addr = self.socket.accept() conn, addr = self.socket.accept()
if self.debug: if self.debug:
print "New connection from %s" % str(addr) print("New connection from %s" % str(addr))
t = threading.Thread(target=Balancer.handleClient, args=(self, conn, addr)) t = threading.Thread(target=Balancer.handleClient, args=(self, conn, addr))
t.start() t.start()
finally: finally:
...@@ -119,7 +120,7 @@ class Balancer: ...@@ -119,7 +120,7 @@ class Balancer:
expired_server_list = [] expired_server_list = []
for key,value in self.sticked_server_dict.items(): for key,value in self.sticked_server_dict.items():
if self.debug: if self.debug:
print 'cur_time = %f, value.atime = %f' % (cur_time, value.atime) print('cur_time = %f, value.atime = %f' % (cur_time, value.atime))
if cur_time > value.atime + 60 * 10: if cur_time > value.atime + 60 * 10:
expired_server_list.append(key) expired_server_list.append(key)
else: else:
...@@ -127,14 +128,14 @@ class Balancer: ...@@ -127,14 +128,14 @@ class Balancer:
count_dict[value.addr] += 1 count_dict[value.addr] += 1
for key in expired_server_list: for key in expired_server_list:
if self.debug: if self.debug:
print "Expiring %s" % str(key) print("Expiring %s" % str(key))
del self.sticked_server_dict[key] # Expire this entry. del self.sticked_server_dict[key] # Expire this entry.
# Find the max and the min. # Find the max and the min.
if self.debug: if self.debug:
print 'count_dict = %s, sticked_server_dict = %s, disabled_server_dict = %s' % (str(count_dict), str(self.sticked_server_dict), str(self.disabled_server_dict)) print('count_dict = %s, sticked_server_dict = %s, disabled_server_dict = %s' % (str(count_dict), str(self.sticked_server_dict), str(self.disabled_server_dict)))
max = -1 max = -1
min = len(self.sticked_server_dict) + 1 min = len(self.sticked_server_dict) + 1
for addr,count in count_dict.items(): for addr,count in list(count_dict.items()):
if count > max: if count > max:
max = count max = count
max_addr = addr max_addr = addr
...@@ -144,22 +145,22 @@ class Balancer: ...@@ -144,22 +145,22 @@ class Balancer:
# If the max is significantly greater than the min, move some clients. # If the max is significantly greater than the min, move some clients.
if max > min + 1: if max > min + 1:
num = max - min - 1 num = max - min - 1
for key,value in self.sticked_server_dict.items(): for key,value in list(self.sticked_server_dict.items()):
if value.addr == max_addr: if value.addr == max_addr:
if self.debug: if self.debug:
print "Moving %s from %s to %s" % (str(key), str(max_addr), str(min_addr)) print("Moving %s from %s to %s" % (str(key), str(max_addr), str(min_addr)))
value.addr = min_addr value.addr = min_addr
num -= 1 num -= 1
if num <= 0: if num <= 0:
break break
# Enable old entries in disabled servers. # Enable old entries in disabled servers.
enabled_server_list = [] enabled_server_list = []
for addr,ctime in self.disabled_server_dict.items(): for addr,ctime in list(self.disabled_server_dict.items()):
if cur_time > ctime + 60 * 3: if cur_time > ctime + 60 * 3:
enabled_server_list.append(addr) enabled_server_list.append(addr)
for addr in enabled_server_list: for addr in enabled_server_list:
if self.debug: if self.debug:
print 'Enabling %s again' % addr print('Enabling %s again' % addr)
del self.disabled_server_dict[addr] del self.disabled_server_dict[addr]
finally: finally:
self.lock.release() self.lock.release()
...@@ -241,7 +242,7 @@ class Balancer: ...@@ -241,7 +242,7 @@ class Balancer:
try: try:
self.lock.acquire() self.lock.acquire()
if self.debug: if self.debug:
print 'Disabling %s' % addr print('Disabling %s' % addr)
cur_time = time.time() cur_time = time.time()
self.disabled_server_dict[addr] = cur_time self.disabled_server_dict[addr] = cur_time
finally: finally:
...@@ -260,7 +261,7 @@ class Balancer: ...@@ -260,7 +261,7 @@ class Balancer:
if index == start_index: if index == start_index:
# No way. # No way.
if self.debug: if self.debug:
print 'No available server found.' print('No available server found.')
return return
# Register this client if possible. # Register this client if possible.
...@@ -268,7 +269,7 @@ class Balancer: ...@@ -268,7 +269,7 @@ class Balancer:
try: try:
self.lock.acquire() self.lock.acquire()
if self.debug: if self.debug:
print 'Registering %s with %s' % (signature, addr) print('Registering %s with %s' % (signature, addr))
cur_time = time.time() cur_time = time.time()
if signature in self.sticked_server_dict: if signature in self.sticked_server_dict:
info = self.sticked_server_dict[signature] info = self.sticked_server_dict[signature]
...@@ -306,16 +307,16 @@ def main(): ...@@ -306,16 +307,16 @@ def main():
try: try:
opts, args = getopt.getopt(sys.argv[1:], "hvb:t:T:dfps", opts, args = getopt.getopt(sys.argv[1:], "hvb:t:T:dfps",
["help", "version", "bind=", "connect-timeout=", "select-timeout=", "debug", "foreground", "packet-dump", "sticky"]) ["help", "version", "bind=", "connect-timeout=", "select-timeout=", "debug", "foreground", "packet-dump", "sticky"])
except getopt.GetoptError, msg: except getopt.GetoptError as msg:
print msg print(msg)
print "Try ``sbalance --help'' for more information." print("Try ``sbalance --help'' for more information.")
sys.exit(2) sys.exit(2)
for o, a in opts: for o, a in opts:
if o in ("-v", "--version"): if o in ("-v", "--version"):
print "sbalance version %s" % SBALANCE_VERSION print("sbalance version %s" % SBALANCE_VERSION)
sys.exit() sys.exit()
elif o in ("-h", "--help"): elif o in ("-h", "--help"):
print '''Usage: sbalace [OPTION...] PORT HOST:[PORT]... print('''Usage: sbalace [OPTION...] PORT HOST:[PORT]...
Balance TCP/IP loads with distributed servers. Balance TCP/IP loads with distributed servers.
-h, --help display this message and exit -h, --help display this message and exit
...@@ -331,7 +332,7 @@ Balance TCP/IP loads with distributed servers. ...@@ -331,7 +332,7 @@ Balance TCP/IP loads with distributed servers.
PORT is the port number to listen to. You can specify any number of PORT is the port number to listen to. You can specify any number of
pairs of a host and a port. pairs of a host and a port.
Report bugs to <yo@nexedi.com>.''' Report bugs to <yo@nexedi.com>.''')
sys.exit() sys.exit()
elif o in ("-b", "--bind"): elif o in ("-b", "--bind"):
kwd['bind'] = a kwd['bind'] = a
...@@ -349,8 +350,8 @@ Report bugs to <yo@nexedi.com>.''' ...@@ -349,8 +350,8 @@ Report bugs to <yo@nexedi.com>.'''
pass pass
if len(args) < 2: if len(args) < 2:
print "Too few arguments." print("Too few arguments.")
print "Try ``sbalance --help'' for more information." print("Try ``sbalance --help'' for more information.")
sys.exit(2) sys.exit(2)
port = int(args[0]) port = int(args[0])
...@@ -364,8 +365,8 @@ Report bugs to <yo@nexedi.com>.''' ...@@ -364,8 +365,8 @@ Report bugs to <yo@nexedi.com>.'''
addr = server addr = server
server_list.append(addr) server_list.append(addr)
if len(server_list) < 1: if len(server_list) < 1:
print "No server is specified." print("No server is specified.")
print "Try ``sbalance --help'' for more information." print("Try ``sbalance --help'' for more information.")
sys.exit(2) sys.exit(2)
b = Balancer(port, server_list, **kwd) b = Balancer(port, server_list, **kwd)
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
# #
############################################################################## ##############################################################################
from past.builtins import cmp
import string import string
from Products.ERP5Type.Globals import InitializeClass, DTMLFile from Products.ERP5Type.Globals import InitializeClass, DTMLFile
...@@ -349,7 +350,7 @@ class Category(Folder): ...@@ -349,7 +350,7 @@ class Category(Folder):
checkPermission = self.portal_membership.checkPermission checkPermission = self.portal_membership.checkPermission
def permissionFilter(obj): def permissionFilter(obj):
return checkPermission(checked_permission, obj) return checkPermission(checked_permission, obj)
value_list = filter(permissionFilter, value_list) value_list = [v for v in value_list if permissionFilter(v)]
return sortValueList(value_list, sort_on, sort_order, **kw) return sortValueList(value_list, sort_on, sort_order, **kw)
...@@ -606,7 +607,7 @@ class Category(Folder): ...@@ -606,7 +607,7 @@ class Category(Folder):
if current_category_list: if current_category_list:
kw['display_none_category'] = False kw['display_none_category'] = False
current_category_item_list = Renderer(base=base, **kw).render( current_category_item_list = Renderer(base=base, **kw).render(
map(self.portal_categories.resolveCategory, current_category_list)) [self.portal_categories.resolveCategory(c) for c in current_category_list])
item_set = {tuple(x) for x in item_list} item_set = {tuple(x) for x in item_list}
additional_item_list = [] additional_item_list = []
for current_category_item in current_category_item_list: for current_category_item in current_category_item_list:
...@@ -903,7 +904,7 @@ class BaseCategory(Category): ...@@ -903,7 +904,7 @@ class BaseCategory(Category):
checkPermission = self.portal_membership.checkPermission checkPermission = self.portal_membership.checkPermission
def permissionFilter(obj): def permissionFilter(obj):
return checkPermission(checked_permission, obj) return checkPermission(checked_permission, obj)
value_list = filter(permissionFilter, value_list) value_list = [v for v in value_list if permissionFilter(v)]
return sortValueList(value_list, sort_on, sort_order, **kw) return sortValueList(value_list, sort_on, sort_order, **kw)
......
...@@ -30,6 +30,8 @@ ...@@ -30,6 +30,8 @@
"""\ """\
ERP portal_categories tool. ERP portal_categories tool.
""" """
import six
from six import string_types as basestring
from collections import deque from collections import deque
import re import re
from BTrees.OOBTree import OOTreeSet from BTrees.OOBTree import OOTreeSet
...@@ -61,13 +63,17 @@ class RelatedIndex(): # persistent.Persistent can be added ...@@ -61,13 +63,17 @@ class RelatedIndex(): # persistent.Persistent can be added
def __repr__(self): def __repr__(self):
try: try:
contents = ', '.join('%s=%r' % (k, list(v)) contents = ', '.join('%s=%r' % (k, list(v))
for (k, v) in self.__dict__.iteritems()) for (k, v) in six.iteritems(self.__dict__))
except Exception: except Exception:
contents = '...' contents = '...'
return '<%s(%s) at 0x%x>' % (self.__class__.__name__, contents, id(self)) return '<%s(%s) at 0x%x>' % (self.__class__.__name__, contents, id(self))
def __nonzero__(self): def __nonzero__(self):
return any(self.__dict__.itervalues()) return any(six.itervalues(self.__dict__))
def __bool__(self):
return any(six.itervalues(self.__dict__))
__nonzero__ = __bool__ # six.PY2
def add(self, base, relative_url): def add(self, base, relative_url):
try: try:
...@@ -1404,7 +1410,7 @@ class CategoryTool(BaseTool): ...@@ -1404,7 +1410,7 @@ class CategoryTool(BaseTool):
except AttributeError: except AttributeError:
related = RelatedIndex() related = RelatedIndex()
include_self = False include_self = False
for base_category, category in local_index_dict.iteritems(): for base_category, category in six.iteritems(local_index_dict):
if not category: if not category:
# Categories are member of themselves. # Categories are member of themselves.
include_self = True include_self = True
...@@ -1463,11 +1469,11 @@ class CategoryTool(BaseTool): ...@@ -1463,11 +1469,11 @@ class CategoryTool(BaseTool):
related = aq_base(ob)._related_index related = aq_base(ob)._related_index
except AttributeError: except AttributeError:
continue continue
for base_category, category in local_index_dict.iteritems(): for base_category, category in six.iteritems(local_index_dict):
category += relative_url category += relative_url
check_local() check_local()
# Filter out objects that are not of requested portal type. # Filter out objects that are not of requested portal type.
result = [ob for ob in result_dict.itervalues() if ob is not None and ( result = [ob for ob in six.itervalues(result_dict) if ob is not None and (
not portal_type or ob.getPortalType() in portal_type)] not portal_type or ob.getPortalType() in portal_type)]
# Finish with base categories that are only indexed in catalog, # Finish with base categories that are only indexed in catalog,
# making sure we don't return duplicate values. # making sure we don't return duplicate values.
...@@ -1508,7 +1514,7 @@ class CategoryTool(BaseTool): ...@@ -1508,7 +1514,7 @@ class CategoryTool(BaseTool):
for permission in checked_permission: for permission in checked_permission:
if checkPermission(permission, ob): if checkPermission(permission, ob):
return True return True
return filter(check, result) return [r for r in result if check(r)]
security.declareProtected( Permissions.AccessContentsInformation, security.declareProtected( Permissions.AccessContentsInformation,
'getRelatedPropertyList' ) 'getRelatedPropertyList' )
......
...@@ -100,4 +100,4 @@ class Filter(Implicit): ...@@ -100,4 +100,4 @@ class Filter(Implicit):
def filter(self, value_list): def filter(self, value_list):
#LOG('Filter filter', 0, 'value_list = %s' % repr(value_list)) #LOG('Filter filter', 0, 'value_list = %s' % repr(value_list))
return filter(lambda v: self.test(v), value_list) return [v for v in value_list if self.test(v)]
...@@ -35,6 +35,7 @@ from Products.CMFCategory.Category import NBSP_UTF8 ...@@ -35,6 +35,7 @@ from Products.CMFCategory.Category import NBSP_UTF8
from Testing.ZopeTestCase.PortalTestCase import PortalTestCase from Testing.ZopeTestCase.PortalTestCase import PortalTestCase
from AccessControl.SecurityManagement import newSecurityManager from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import noSecurityManager from AccessControl.SecurityManagement import noSecurityManager
import six
class TestCMFCategory(ERP5TypeTestCase): class TestCMFCategory(ERP5TypeTestCase):
...@@ -102,7 +103,7 @@ class TestCMFCategory(ERP5TypeTestCase): ...@@ -102,7 +103,7 @@ class TestCMFCategory(ERP5TypeTestCase):
self.validateRules() self.validateRules()
portal_categories = self.getCategoriesTool() portal_categories = self.getCategoriesTool()
for name, kw in self.category_dict.iteritems(): for name, kw in six.iteritems(self.category_dict):
try: try:
bc = portal_categories[name] bc = portal_categories[name]
except KeyError: except KeyError:
...@@ -168,7 +169,7 @@ class TestCMFCategory(ERP5TypeTestCase): ...@@ -168,7 +169,7 @@ class TestCMFCategory(ERP5TypeTestCase):
def beforeTearDown(self): def beforeTearDown(self):
"""Clean up.""" """Clean up."""
# type informations # type informations
for portal_type, categories in self._original_categories.iteritems(): for portal_type, categories in six.iteritems(self._original_categories):
ti = self.getTypesTool().getTypeInfo(portal_type) ti = self.getTypesTool().getTypeInfo(portal_type)
ti.filter_content_types = 1 ti.filter_content_types = 1
ti._setTypeBaseCategoryList(categories) ti._setTypeBaseCategoryList(categories)
......
...@@ -22,11 +22,12 @@ ...@@ -22,11 +22,12 @@
ZServer hook to dump a traceback of the running python threads. ZServer hook to dump a traceback of the running python threads.
""" """
import thread import six
import _thread
from sys import _current_frames from sys import _current_frames
import traceback import traceback
import time import time
from cStringIO import StringIO from io import BytesIO as StringIO
from zLOG import LOG, DEBUG, ERROR from zLOG import LOG, DEBUG, ERROR
from App.config import getConfiguration from App.config import getConfiguration
...@@ -39,7 +40,7 @@ def dump_threads(): ...@@ -39,7 +40,7 @@ def dump_threads():
this_thread_id = thread.get_ident() this_thread_id = thread.get_ident()
now = time.strftime("%Y-%m-%d %H:%M:%S") now = time.strftime("%Y-%m-%d %H:%M:%S")
res = ["Threads traceback dump at %s\n" % now] res = ["Threads traceback dump at %s\n" % now]
for thread_id, frame in _current_frames().iteritems(): for thread_id, frame in six.iteritems(_current_frames()):
if thread_id == this_thread_id: if thread_id == this_thread_id:
continue continue
...@@ -68,7 +69,7 @@ def dump_threads(): ...@@ -68,7 +69,7 @@ def dump_threads():
from Products.ZMySQLDA.db import DB from Products.ZMySQLDA.db import DB
while f is not None: while f is not None:
code = f.f_code code = f.f_code
if code is DB._query.func_code: if code is DB._query.__code__:
mysql_info = "\nMySQL query:\n%s\n" % f.f_locals['query'] mysql_info = "\nMySQL query:\n%s\n" % f.f_locals['query']
break break
f = f.f_back f = f.f_back
...@@ -82,7 +83,7 @@ def dump_threads(): ...@@ -82,7 +83,7 @@ def dump_threads():
res.append("End of dump\n") res.append("End of dump\n")
result = '\n'.join(res) result = '\n'.join(res)
if isinstance(result, unicode): if isinstance(result, six.text_type):
result = result.encode('utf-8') result = result.encode('utf-8')
return result return result
......
...@@ -58,7 +58,7 @@ class AccountingTransactionBalance(Constraint): ...@@ -58,7 +58,7 @@ class AccountingTransactionBalance(Constraint):
destination_sum[section] = destination_sum.get(section, 0) + \ destination_sum[section] = destination_sum.get(section, 0) + \
(line.getDestinationInventoriatedTotalAssetPrice() or 0) (line.getDestinationInventoriatedTotalAssetPrice() or 0)
for section, total in source_sum.items(): for section, total in list(source_sum.items()):
precision = 2 precision = 2
if section is not None and\ if section is not None and\
section.getPortalType() == 'Organisation': section.getPortalType() == 'Organisation':
...@@ -71,7 +71,7 @@ class AccountingTransactionBalance(Constraint): ...@@ -71,7 +71,7 @@ class AccountingTransactionBalance(Constraint):
mapping=dict(section_title=section.getTranslatedTitle()))) mapping=dict(section_title=section.getTranslatedTitle())))
break break
for section, total in destination_sum.items(): for section, total in list(destination_sum.items()):
precision = 2 precision = 2
if section is not None and\ if section is not None and\
section.getPortalType() == 'Organisation': section.getPortalType() == 'Organisation':
......
...@@ -27,7 +27,9 @@ ...@@ -27,7 +27,9 @@
# #
############################################################################## ##############################################################################
from compiler.consts import CO_VARKEYWORDS from past.builtins import cmp
from six import string_types as basestring
from inspect import CO_VARKEYWORDS
from random import getrandbits from random import getrandbits
from Acquisition import aq_base from Acquisition import aq_base
from DateTime import DateTime from DateTime import DateTime
...@@ -162,7 +164,7 @@ class Alarm(XMLObject, PeriodicityMixin): ...@@ -162,7 +164,7 @@ class Alarm(XMLObject, PeriodicityMixin):
activate_kw['tag'] = '%s_%x' % (self.getRelativeUrl(), getrandbits(32)) activate_kw['tag'] = '%s_%x' % (self.getRelativeUrl(), getrandbits(32))
tag = activate_kw['tag'] tag = activate_kw['tag']
method = getattr(self, method_id) method = getattr(self, method_id)
func_code = method.func_code func_code = method.__code__
try: try:
has_kw = func_code.co_flags & CO_VARKEYWORDS has_kw = func_code.co_flags & CO_VARKEYWORDS
except AttributeError: except AttributeError:
......
This diff is collapsed.
...@@ -129,9 +129,9 @@ class Category(CMFCategory, Predicate, MetaNode, MetaResource): ...@@ -129,9 +129,9 @@ class Category(CMFCategory, Predicate, MetaNode, MetaResource):
cache_key = 'web_site_aq_cache' cache_key = 'web_site_aq_cache'
request = self.REQUEST request = self.REQUEST
# Prevent infinite recursion # Prevent infinite recursion
if not request.has_key(cache_key): if cache_key not in request:
request[cache_key] = {} request[cache_key] = {}
elif request[cache_key].has_key(name): elif name in request[cache_key]:
return request[cache_key][name] return request[cache_key][name]
try: try:
result_list = self.portal_catalog(portal_type="Person", id = name) result_list = self.portal_catalog(portal_type="Person", id = name)
...@@ -139,7 +139,7 @@ class Category(CMFCategory, Predicate, MetaNode, MetaResource): ...@@ -139,7 +139,7 @@ class Category(CMFCategory, Predicate, MetaNode, MetaResource):
return result_list[0].getObject() return result_list[0].getObject()
except: except:
# Cleanup non recursion dict in case of exception # Cleanup non recursion dict in case of exception
if request[cache_key].has_key(name): if name in request[cache_key]:
del request[cache_key][name] del request[cache_key][name]
raise raise
return None return None
......
...@@ -44,6 +44,7 @@ from Products.ERP5.mixin.variated import VariatedMixin ...@@ -44,6 +44,7 @@ from Products.ERP5.mixin.variated import VariatedMixin
from Products.CMFCategory.Renderer import Renderer from Products.CMFCategory.Renderer import Renderer
from zLOG import LOG, WARNING from zLOG import LOG, WARNING
import six
class Resource(XMLObject, XMLMatrix, VariatedMixin): class Resource(XMLObject, XMLMatrix, VariatedMixin):
""" """
...@@ -806,7 +807,7 @@ class Resource(XMLObject, XMLMatrix, VariatedMixin): ...@@ -806,7 +807,7 @@ class Resource(XMLObject, XMLMatrix, VariatedMixin):
try: try:
result = quantity * self._getConversionRatio(from_unit, variation_list)\ result = quantity * self._getConversionRatio(from_unit, variation_list)\
/ self._getConversionRatio(to_unit, variation_list) / self._getConversionRatio(to_unit, variation_list)
except (ArithmeticError, AttributeError, LookupError, TypeError), error: except (ArithmeticError, AttributeError, LookupError, TypeError) as error:
# For compatibility, we only log the error and return None. # For compatibility, we only log the error and return None.
# No exception for the moment. # No exception for the moment.
LOG('Resource.convertQuantity', WARNING, LOG('Resource.convertQuantity', WARNING,
...@@ -945,7 +946,7 @@ class Resource(XMLObject, XMLMatrix, VariatedMixin): ...@@ -945,7 +946,7 @@ class Resource(XMLObject, XMLMatrix, VariatedMixin):
uid = self.getUid() uid = self.getUid()
row_list = [] row_list = []
for unit_uid, value in self._getQuantityUnitDefinitionDict().iteritems(): for unit_uid, value in six.iteritems(self._getQuantityUnitDefinitionDict()):
definition_uid, quantity = value definition_uid, quantity = value
row_list.append(dict(uid=definition_uid, row_list.append(dict(uid=definition_uid,
resource_uid=uid, resource_uid=uid,
...@@ -977,7 +978,7 @@ class Resource(XMLObject, XMLMatrix, VariatedMixin): ...@@ -977,7 +978,7 @@ class Resource(XMLObject, XMLMatrix, VariatedMixin):
metric_type_map[metric_type] = measure metric_type_map[metric_type] = measure
insert_list = [] insert_list = []
for measure in metric_type_map.itervalues(): for measure in six.itervalues(metric_type_map):
if measure is not None: if measure is not None:
insert_list += measure.asCatalogRowList(quantity_unit_definition_dict) insert_list += measure.asCatalogRowList(quantity_unit_definition_dict)
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
# #
############################################################################## ##############################################################################
import six
import zope.interface import zope.interface
from Acquisition import aq_base from Acquisition import aq_base
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
...@@ -96,7 +97,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator): ...@@ -96,7 +97,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator):
portal.IdTool_zSetLastId(id_group, None) portal.IdTool_zSetLastId(id_group, None)
# Commit the changement of new_id # Commit the changement of new_id
portal.IdTool_zCommit() portal.IdTool_zCommit()
except ProgrammingError, error: except ProgrammingError as error:
if error[0] != NO_SUCH_TABLE: if error[0] != NO_SUCH_TABLE:
raise raise
...@@ -132,7 +133,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator): ...@@ -132,7 +133,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator):
for line in self._getValueListFromTable(): for line in self._getValueListFromTable():
id_group = line['id_group'] id_group = line['id_group']
last_id = line['last_id'] last_id = line['last_id']
if self.last_max_id_dict.has_key(id_group) and \ if id_group in self.last_max_id_dict and \
self.last_max_id_dict[id_group].value > last_id: self.last_max_id_dict[id_group].value > last_id:
set_last_id_method(id_group=id_group, set_last_id_method(id_group=id_group,
last_id=self.last_max_id_dict[id_group].value) last_id=self.last_max_id_dict[id_group].value)
...@@ -159,7 +160,10 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator): ...@@ -159,7 +160,10 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator):
""" """
new_id = 1 + self._generateNewId(id_group=id_group, id_count=id_count, new_id = 1 + self._generateNewId(id_group=id_group, id_count=id_count,
default=default, poison=poison) default=default, poison=poison)
return range(new_id - id_count, new_id) if six.PY2:
return range(new_id - id_count, new_id)
else:
return list(range(new_id - id_count, new_id))
security.declareProtected(Permissions.ModifyPortalContent, security.declareProtected(Permissions.ModifyPortalContent,
'initializeGenerator') 'initializeGenerator')
...@@ -177,7 +181,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator): ...@@ -177,7 +181,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator):
portal = self.getPortalObject() portal = self.getPortalObject()
try: try:
portal.IdTool_zGetValueList() portal.IdTool_zGetValueList()
except ProgrammingError, error: except ProgrammingError as error:
if error[0] != NO_SUCH_TABLE: if error[0] != NO_SUCH_TABLE:
raise raise
portal.IdTool_zDropTable() portal.IdTool_zDropTable()
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
# #
############################################################################## ##############################################################################
import six
import zope.interface import zope.interface
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions, interfaces from Products.ERP5Type import Permissions, interfaces
...@@ -85,7 +86,10 @@ class ZODBContinuousIncreasingIdGenerator(IdGenerator): ...@@ -85,7 +86,10 @@ class ZODBContinuousIncreasingIdGenerator(IdGenerator):
""" """
new_id = 1 + self._generateNewId(id_group=id_group, id_count=id_count, new_id = 1 + self._generateNewId(id_group=id_group, id_count=id_count,
default=default, poison=poison) default=default, poison=poison)
return range(new_id - id_count, new_id) if six.PY2:
return range(new_id - id_count, new_id)
else:
return list(range(new_id - id_count, new_id))
security.declareProtected(Permissions.ModifyPortalContent, security.declareProtected(Permissions.ModifyPortalContent,
'initializeGenerator') 'initializeGenerator')
...@@ -106,7 +110,7 @@ class ZODBContinuousIncreasingIdGenerator(IdGenerator): ...@@ -106,7 +110,7 @@ class ZODBContinuousIncreasingIdGenerator(IdGenerator):
for id_group, last_id in portal_ids.dict_ids.items(): for id_group, last_id in portal_ids.dict_ids.items():
if not isinstance(id_group, str): if not isinstance(id_group, str):
id_group = repr(id_group) id_group = repr(id_group)
if self.last_id_dict.has_key(id_group) and \ if id_group in self.last_id_dict and \
self.last_id_dict[id_group] > last_id: self.last_id_dict[id_group] > last_id:
continue continue
self.last_id_dict[id_group] = last_id self.last_id_dict[id_group] = last_id
...@@ -146,7 +150,7 @@ class ZODBContinuousIncreasingIdGenerator(IdGenerator): ...@@ -146,7 +150,7 @@ class ZODBContinuousIncreasingIdGenerator(IdGenerator):
if not isinstance(id_dict, dict): if not isinstance(id_dict, dict):
raise TypeError('the argument given is not a dictionary') raise TypeError('the argument given is not a dictionary')
for value in id_dict.values(): for value in id_dict.values():
if not isinstance(value, (int, long)): if not isinstance(value, six.integer_types):
raise TypeError('the value given in dictionary is not a integer') raise TypeError('the value given in dictionary is not a integer')
self.last_id_dict.update(id_dict) self.last_id_dict.update(id_dict)
......
...@@ -18,8 +18,8 @@ from __future__ import absolute_import ...@@ -18,8 +18,8 @@ from __future__ import absolute_import
from DateTime import DateTime from DateTime import DateTime
from six.moves import map from six.moves import map
import thread, threading
import six import six
import _thread, threading
from weakref import ref as weakref from weakref import ref as weakref
from OFS.Application import Application, AppInitializer from OFS.Application import Application, AppInitializer
from Products.ERP5Type import Globals from Products.ERP5Type import Globals
...@@ -46,7 +46,6 @@ from Products.ERP5Type.dynamic.portal_type_class import synchronizeDynamicModule ...@@ -46,7 +46,6 @@ from Products.ERP5Type.dynamic.portal_type_class import synchronizeDynamicModule
from Products.ERP5Type.mixin.response_header_generator import ResponseHeaderGenerator from Products.ERP5Type.mixin.response_header_generator import ResponseHeaderGenerator
from zLOG import LOG, INFO, WARNING, ERROR from zLOG import LOG, INFO, WARNING, ERROR
from string import join
import os import os
import warnings import warnings
import transaction import transaction
...@@ -371,7 +370,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook ...@@ -371,7 +370,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook
def _registerMissingTools(self): def _registerMissingTools(self):
tool_id_list = ("portal_skins", "portal_types", "portal_membership", tool_id_list = ("portal_skins", "portal_types", "portal_membership",
"portal_url", "portal_workflow") "portal_url", "portal_workflow")
if (None in map(self.get, tool_id_list) or not if (None in [self.get(tool_id) for tool_id in tool_id_list] or not
TransactionalResource.registerOnce(__name__, 'site_manager', self.id)): TransactionalResource.registerOnce(__name__, 'site_manager', self.id)):
return return
self._registerTools(tool_id_list + self._registry_tool_id_list) self._registerTools(tool_id_list + self._registry_tool_id_list)
...@@ -467,7 +466,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook ...@@ -467,7 +466,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook
security.declareProtected(Permissions.AccessContentsInformation, 'skinSuper') security.declareProtected(Permissions.AccessContentsInformation, 'skinSuper')
def skinSuper(self, skin, id): def skinSuper(self, skin, id):
if id[:1] != '_' and id[:3] != 'aq_': if id[:1] != '_' and id[:3] != 'aq_':
skin_info = SKINDATA.get(thread.get_ident()) skin_info = SKINDATA.get(_thread.get_ident())
if skin_info is not None: if skin_info is not None:
_, skin_selection_name, _, _ = skin_info _, skin_selection_name, _, _ = skin_info
skin_value = skinResolve(self, (skin_selection_name, skin), id) skin_value = skinResolve(self, (skin_selection_name, skin), id)
...@@ -679,7 +678,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook ...@@ -679,7 +678,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook
""" """
Returns the absolute path of an object Returns the absolute path of an object
""" """
return join(self.getPhysicalPath(),'/') return '/'.join(self.getPhysicalPath())
security.declareProtected(Permissions.AccessContentsInformation, 'getRelativeUrl') security.declareProtected(Permissions.AccessContentsInformation, 'getRelativeUrl')
def getRelativeUrl(self): def getRelativeUrl(self):
...@@ -704,7 +703,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook ...@@ -704,7 +703,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook
Search the content of a folder by calling Search the content of a folder by calling
the portal_catalog. the portal_catalog.
""" """
if not kw.has_key('parent_uid'): if 'parent_uid' not in kw:
kw['parent_uid'] = self.uid kw['parent_uid'] = self.uid
return self.portal_catalog.searchResults(**kw) return self.portal_catalog.searchResults(**kw)
...@@ -714,7 +713,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook ...@@ -714,7 +713,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook
Count the content of a folder by calling Count the content of a folder by calling
the portal_catalog. the portal_catalog.
""" """
if not kw.has_key('parent_uid'): if 'parent_uid' not in kw:
kw['parent_uid'] = self.uid kw['parent_uid'] = self.uid
return self.portal_catalog.countResults(**kw) return self.portal_catalog.countResults(**kw)
...@@ -737,7 +736,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook ...@@ -737,7 +736,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook
action['disabled'] = 0 action['disabled'] = 0
workflow_title = action.get('workflow_title', None) workflow_title = action.get('workflow_title', None)
if workflow_title is not None: if workflow_title is not None:
if not sorted_workflow_actions.has_key(workflow_title): if workflow_title not in sorted_workflow_actions:
sorted_workflow_actions[workflow_title] = [ sorted_workflow_actions[workflow_title] = [
{'title':workflow_title, {'title':workflow_title,
'disabled':1, 'disabled':1,
...@@ -805,12 +804,12 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook ...@@ -805,12 +804,12 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook
parameter_dict = config.product_config.get(self.getPath(), {}) parameter_dict = config.product_config.get(self.getPath(), {})
if 'promise_path' in parameter_dict: if 'promise_path' in parameter_dict:
promise_path = parameter_dict['promise_path'] promise_path = parameter_dict['promise_path']
import ConfigParser from six.moves import configparser
configuration = ConfigParser.ConfigParser() configuration = configparser.ConfigParser()
configuration.read(promise_path) configuration.read(promise_path)
try: try:
return configuration.get(section, option) return configuration.get(section, option)
except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): except (configparser.NoOptionError, configparser.NoSectionError):
pass pass
return None return None
...@@ -2493,7 +2492,7 @@ def initialize(self): ...@@ -2493,7 +2492,7 @@ def initialize(self):
REQUEST.RESPONSE.unauthorized() REQUEST.RESPONSE.unauthorized()
newSecurityManager(None, user.__of__(uf)) newSecurityManager(None, user.__of__(uf))
manage_addERP5Site(app.__of__(RequestContainer(REQUEST=REQUEST)), manage_addERP5Site(app.__of__(RequestContainer(REQUEST=REQUEST)),
**{k: kw.get(k, v) for k, v in default_kw.iteritems() **{k: kw.get(k, v) for k, v in six.iteritems(default_kw)
if isinstance(v, str)}) if isinstance(v, str)})
transaction.get().note('Created ' + meta_type) transaction.get().note('Created ' + meta_type)
transaction.commit() transaction.commit()
......
from __future__ import print_function
def clearData(self,REQUEST=None): def clearData(self,REQUEST=None):
""" """
this allows to erase every data object this allows to erase every data object
...@@ -5,7 +6,7 @@ def clearData(self,REQUEST=None): ...@@ -5,7 +6,7 @@ def clearData(self,REQUEST=None):
import transaction import transaction
context=self context=self
for folder in context.objectValues(("ERP5 Folder",)): for folder in context.objectValues(("ERP5 Folder",)):
print "#### Deleting inside the folder %s ####" % folder.id print("#### Deleting inside the folder %s ####" % folder.id)
# Getting the list of ids # Getting the list of ids
to_delete_list = folder.objectIds() to_delete_list = folder.objectIds()
while len(to_delete_list) > 0: while len(to_delete_list) > 0:
...@@ -14,4 +15,4 @@ def clearData(self,REQUEST=None): ...@@ -14,4 +15,4 @@ def clearData(self,REQUEST=None):
to_delete_list = folder.objectIds() to_delete_list = folder.objectIds()
transaction.commit() transaction.commit()
print "work done" print("work done")
import difflib import difflib
import six
def diff_recursive(object_a, object_b): def diff_recursive(object_a, object_b):
""" """
...@@ -70,7 +71,7 @@ def diff_objects(object_a, object_b): ...@@ -70,7 +71,7 @@ def diff_objects(object_a, object_b):
for property_dict_id in ('values', 'tales', 'overrides'): for property_dict_id in ('values', 'tales', 'overrides'):
a_property_dict = getattr(field_a, property_dict_id) a_property_dict = getattr(field_a, property_dict_id)
b_property_dict = getattr(field_b, property_dict_id) b_property_dict = getattr(field_b, property_dict_id)
for property_id, a_property_value in a_property_dict.iteritems(): for property_id, a_property_value in six.iteritems(a_property_dict):
b_property_value = b_property_dict[property_id] b_property_value = b_property_dict[property_id]
if a_property_value != b_property_value: if a_property_value != b_property_value:
if isinstance(a_property_value, str) and isinstance(b_property_value, str): if isinstance(a_property_value, str) and isinstance(b_property_value, str):
......
import six
from Products.ERP5Type.Globals import get_request from Products.ERP5Type.Globals import get_request
from Acquisition import aq_base from Acquisition import aq_base
from Products.ERP5Type.Base import Base from Products.ERP5Type.Base import Base
...@@ -31,14 +32,21 @@ def recodeDocumentRecursively(document, dry_run=0): ...@@ -31,14 +32,21 @@ def recodeDocumentRecursively(document, dry_run=0):
if type(value) == type(''): if type(value) == type(''):
if len(value) > 0: if len(value) > 0:
message += 'Recoding %s of %s\n' % (id, document.getRelativeUrl()) message += 'Recoding %s of %s\n' % (id, document.getRelativeUrl())
if not dry_run: setattr(base, id, unicode(value, 'iso-8859-1').encode('utf-8')) if not dry_run:
if six.PY2:
setattr(base, id, unicode(value, 'iso-8859-1').encode('utf-8'))
else:
setattr(base, id, str(value, 'iso-8859-1').encode('utf-8'))
elif type(value) in (type(()), type([])): elif type(value) in (type(()), type([])):
if len(value) > 0: if len(value) > 0:
value_list = list(value) value_list = list(value)
for i in range(len(value_list)): for i in range(len(value_list)):
value = value_list[i] value = value_list[i]
if type(value) == type('') and len(value) > 0: if isinstance(value, six.binary_type) and len(value) > 0:
value_list[i] = unicode(value, 'iso-8859-1').encode('utf-8') if six.PY2:
value_list[i] = unicode(value, 'iso-8859-1').encode('utf-8')
else:
value_list[i] = str(value, 'iso-8859-1').encode('utf-8')
message += 'Recoding %s of %s\n' % (id, document.getRelativeUrl()) message += 'Recoding %s of %s\n' % (id, document.getRelativeUrl())
if not dry_run: setattr(base, id, tuple(value_list)) if not dry_run: setattr(base, id, tuple(value_list))
else: else:
......
...@@ -102,13 +102,13 @@ class InteractionDefinition (SimpleItem): ...@@ -102,13 +102,13 @@ class InteractionDefinition (SimpleItem):
return aq_parent(aq_inner(aq_parent(aq_inner(self)))) return aq_parent(aq_inner(aq_parent(aq_inner(self))))
def getAvailableStateIds(self): def getAvailableStateIds(self):
return self.getWorkflow().states.keys() return list(self.getWorkflow().states.keys())
def getAvailableScriptIds(self): def getAvailableScriptIds(self):
return self.getWorkflow().scripts.keys() return list(self.getWorkflow().scripts.keys())
def getAvailableVarIds(self): def getAvailableVarIds(self):
return self.getWorkflow().variables.keys() return list(self.getWorkflow().variables.keys())
def getTriggerMethodIdList(self): def getTriggerMethodIdList(self):
return self.method_id return self.method_id
...@@ -232,7 +232,7 @@ class InteractionDefinition (SimpleItem): ...@@ -232,7 +232,7 @@ class InteractionDefinition (SimpleItem):
return wf_vars return wf_vars
ret = [] ret = []
for vid in wf_vars: for vid in wf_vars:
if not self.var_exprs.has_key(vid): if vid not in self.var_exprs:
ret.append(vid) ret.append(vid)
return ret return ret
...@@ -256,7 +256,7 @@ class InteractionDefinition (SimpleItem): ...@@ -256,7 +256,7 @@ class InteractionDefinition (SimpleItem):
''' '''
ve = self.var_exprs ve = self.var_exprs
for id in ids: for id in ids:
if ve.has_key(id): if id in ve:
del ve[id] del ve[id]
if REQUEST is not None: if REQUEST is not None:
...@@ -271,7 +271,7 @@ class InteractionDefinition (SimpleItem): ...@@ -271,7 +271,7 @@ class InteractionDefinition (SimpleItem):
ve = self.var_exprs ve = self.var_exprs
if REQUEST is not None: if REQUEST is not None:
for id in ve.keys(): for id in list(ve.keys()):
fname = 'varexpr_%s' % id fname = 'varexpr_%s' % id
val = REQUEST[fname] val = REQUEST[fname]
......
...@@ -40,7 +40,7 @@ from Products.ERP5Type import Permissions ...@@ -40,7 +40,7 @@ from Products.ERP5Type import Permissions
from Products.ERP5 import _dtmldir from Products.ERP5 import _dtmldir
from Products.ERP5.mixin.timer_service import TimerServiceMixin from Products.ERP5.mixin.timer_service import TimerServiceMixin
from DateTime import DateTime from DateTime import DateTime
import urllib from six.moves import urllib
last_tic = time.time() last_tic = time.time()
last_tic_lock = threading.Lock() last_tic_lock = threading.Lock()
...@@ -215,11 +215,11 @@ class AlarmTool(TimerServiceMixin, BaseTool): ...@@ -215,11 +215,11 @@ class AlarmTool(TimerServiceMixin, BaseTool):
REQUEST.RESPONSE.redirect( REQUEST.RESPONSE.redirect(
REQUEST.URL1 + REQUEST.URL1 +
'/manageAlarmNode?manage_tabs_message=' + '/manageAlarmNode?manage_tabs_message=' +
urllib.quote("Distributing Node successfully changed.")) urllib.parse.quote("Distributing Node successfully changed."))
else : else :
if REQUEST is not None: if REQUEST is not None:
REQUEST.RESPONSE.redirect( REQUEST.RESPONSE.redirect(
REQUEST.URL1 + REQUEST.URL1 +
'/manageAlarmNode?manage_tabs_message=' + '/manageAlarmNode?manage_tabs_message=' +
urllib.quote("Malformed Distributing Node.")) urllib.parse.quote("Malformed Distributing Node."))
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
# #
############################################################################## ##############################################################################
import six
import warnings import warnings
import zope.interface import zope.interface
...@@ -62,7 +63,7 @@ class IdTool(BaseTool): ...@@ -62,7 +63,7 @@ class IdTool(BaseTool):
""" """
the newContent is overriden to not use generateNewId the newContent is overriden to not use generateNewId
""" """
if not kw.has_key(id): if id not in kw:
new_id = self._generateNextId() new_id = self._generateNextId()
if new_id is not None: if new_id is not None:
kw['id'] = new_id kw['id'] = new_id
...@@ -228,7 +229,10 @@ class IdTool(BaseTool): ...@@ -228,7 +229,10 @@ class IdTool(BaseTool):
if self.dict_length_ids.get(id_group) is None: if self.dict_length_ids.get(id_group) is None:
self.dict_length_ids[id_group] = Length(new_id) self.dict_length_ids[id_group] = Length(new_id)
self.dict_length_ids[id_group].set(new_id) self.dict_length_ids[id_group].set(new_id)
new_id_list = range(new_id - id_count, new_id) if six.PY2:
new_id_list = range(new_id - id_count, new_id)
else:
new_id_list = list(range(new_id - id_count, new_id))
return new_id_list return new_id_list
security.declareProtected(Permissions.ModifyPortalContent, security.declareProtected(Permissions.ModifyPortalContent,
......
...@@ -28,6 +28,7 @@ ...@@ -28,6 +28,7 @@
############################################################################## ##############################################################################
from webdav.client import Resource from webdav.client import Resource
from past.builtins import cmp
from App.config import getConfiguration from App.config import getConfiguration
import os import os
...@@ -47,14 +48,19 @@ from Products.ERP5.genbt5list import generateInformation ...@@ -47,14 +48,19 @@ from Products.ERP5.genbt5list import generateInformation
from Acquisition import aq_base from Acquisition import aq_base
from tempfile import mkstemp, mkdtemp from tempfile import mkstemp, mkdtemp
from Products.ERP5 import _dtmldir from Products.ERP5 import _dtmldir
from cStringIO import StringIO from six.moves import xrange
from urllib import pathname2url, urlopen, splittype, urlretrieve from six.moves import cStringIO as StringIO
import urllib2 from six.moves.urllib.request import pathname2url, urlopen, urlretrieve
try:
from urllib import splittype
except ImportError: # six.PY3
from urllib.parse import splittype
from six.moves import urllib
import re import re
from xml.dom.minidom import parse from xml.dom.minidom import parse
from xml.parsers.expat import ExpatError from xml.parsers.expat import ExpatError
import struct import struct
import cPickle from six.moves import cPickle as pickle
from base64 import b64encode, b64decode from base64 import b64encode, b64decode
from Products.ERP5Type.Message import translateString from Products.ERP5Type.Message import translateString
from zLOG import LOG, INFO, WARNING from zLOG import LOG, INFO, WARNING
...@@ -513,7 +519,7 @@ class TemplateTool (BaseTool): ...@@ -513,7 +519,7 @@ class TemplateTool (BaseTool):
Migrate business templates to new format where files like .py or .html Migrate business templates to new format where files like .py or .html
are exported seprately than the xml. are exported seprately than the xml.
""" """
repository_list = filter(bool, repository_list) repository_list = [r for r in repository_list if r]
if REQUEST is None: if REQUEST is None:
REQUEST = getattr(self, 'REQUEST', None) REQUEST = getattr(self, 'REQUEST', None)
...@@ -703,7 +709,7 @@ class TemplateTool (BaseTool): ...@@ -703,7 +709,7 @@ class TemplateTool (BaseTool):
Decode the uid of a business template from a repository. Decode the uid of a business template from a repository.
Return a repository and an id. Return a repository and an id.
""" """
return cPickle.loads(b64decode(uid)) return pickle.loads(b64decode(uid))
security.declarePublic( 'encodeRepositoryBusinessTemplateUid' ) security.declarePublic( 'encodeRepositoryBusinessTemplateUid' )
def encodeRepositoryBusinessTemplateUid(self, repository, id): def encodeRepositoryBusinessTemplateUid(self, repository, id):
...@@ -711,7 +717,7 @@ class TemplateTool (BaseTool): ...@@ -711,7 +717,7 @@ class TemplateTool (BaseTool):
encode the repository and the id of a business template. encode the repository and the id of a business template.
Return an uid. Return an uid.
""" """
return b64encode(cPickle.dumps((repository, id))) return b64encode(pickle.dumps((repository, id)))
security.declarePublic('compareVersionStrings') security.declarePublic('compareVersionStrings')
def compareVersionStrings(self, version, comparing_string): def compareVersionStrings(self, version, comparing_string):
...@@ -1380,16 +1386,16 @@ class TemplateTool (BaseTool): ...@@ -1380,16 +1386,16 @@ class TemplateTool (BaseTool):
LOG('ERP5', INFO, "TemplateTool: INSTANCE_HOME_REPOSITORY is %s." \ LOG('ERP5', INFO, "TemplateTool: INSTANCE_HOME_REPOSITORY is %s." \
% url) % url)
try: try:
urllib2.urlopen(url) urllib.request.urlopen(url)
return url return url
except (urllib2.HTTPError, OSError): except (urllib.error.HTTPError, OSError):
# XXX Try again with ".bt5" in case the folder format be used # XXX Try again with ".bt5" in case the folder format be used
# Instead tgz one. # Instead tgz one.
url = "%s.bt5" % url url = "%s.bt5" % url
try: try:
urllib2.urlopen(url) urllib.request.urlopen(url)
return url return url
except (urllib2.HTTPError, OSError): except (urllib.error.HTTPError, OSError):
pass pass
LOG('ERP5', INFO, 'TemplateTool: %s was not found into the url list: ' LOG('ERP5', INFO, 'TemplateTool: %s was not found into the url list: '
'%s.' % (bt5_title, base_url_list)) '%s.' % (bt5_title, base_url_list))
......
...@@ -38,7 +38,7 @@ from zExceptions import BadRequest ...@@ -38,7 +38,7 @@ from zExceptions import BadRequest
from zLOG import LOG, WARNING from zLOG import LOG, WARNING
from DateTime import DateTime from DateTime import DateTime
from Acquisition import aq_base from Acquisition import aq_base
from cStringIO import StringIO from io import BytesIO as StringIO
class TrashTool(BaseTool): class TrashTool(BaseTool):
""" """
......
...@@ -12,7 +12,7 @@ import socket ...@@ -12,7 +12,7 @@ import socket
import sys import sys
from tempfile import TemporaryFile from tempfile import TemporaryFile
import time import time
from urllib import quote, splitport from six.moves.urllib.parse import quote, splitport
from waitress.server import create_server from waitress.server import create_server
import ZConfig import ZConfig
......
...@@ -40,6 +40,7 @@ from erp5.component.interface.IAmount import IAmount ...@@ -40,6 +40,7 @@ from erp5.component.interface.IAmount import IAmount
from zLOG import LOG, ERROR from zLOG import LOG, ERROR
from warnings import warn from warnings import warn
import six
@zope.interface.implementer(IAmount) @zope.interface.implementer(IAmount)
...@@ -93,7 +94,7 @@ class Amount(Base, VariatedMixin): ...@@ -93,7 +94,7 @@ class Amount(Base, VariatedMixin):
and not omit_optional_variation): and not omit_optional_variation):
variation_list.append('industrial_phase') variation_list.append('industrial_phase')
if base_category_list: if base_category_list:
variation_list = filter(base_category_list.__contains__, variation_list) variation_list = [v for v in variation_list if v in base_category_list]
return self.getAcquiredCategoryMembershipList(variation_list, base=1) return self.getAcquiredCategoryMembershipList(variation_list, base=1)
security.declareProtected(Permissions.AccessContentsInformation, security.declareProtected(Permissions.AccessContentsInformation,
...@@ -121,7 +122,7 @@ class Amount(Base, VariatedMixin): ...@@ -121,7 +122,7 @@ class Amount(Base, VariatedMixin):
render_category_list = Renderer(display_id=display_id, **kw).render render_category_list = Renderer(display_id=display_id, **kw).render
kw['display_id'] = 'title' kw['display_id'] = 'title'
for base_category, (object_list, for base_category, (object_list,
category_list) in variation_dict.iteritems(): category_list) in six.iteritems(variation_dict):
if base_category_list and base_category not in base_category_list: if base_category_list and base_category not in base_category_list:
continue continue
variation_category_item_list += render_category_list(category_list) variation_category_item_list += render_category_list(category_list)
......
...@@ -45,6 +45,7 @@ from erp5.component.mixin.ExplainableMixin import ExplainableMixin ...@@ -45,6 +45,7 @@ from erp5.component.mixin.ExplainableMixin import ExplainableMixin
from erp5.component.mixin.RuleMixin import RuleMixin from erp5.component.mixin.RuleMixin import RuleMixin
from erp5.component.interface.IExpandable import IExpandable from erp5.component.interface.IExpandable import IExpandable
from erp5.component.interface.IMovementCollection import IMovementCollection from erp5.component.interface.IMovementCollection import IMovementCollection
import six
@zope.interface.implementer(IExpandable, @zope.interface.implementer(IExpandable,
IMovementCollection) IMovementCollection)
...@@ -230,7 +231,7 @@ class AppliedRule(XMLObject, ExplainableMixin): ...@@ -230,7 +231,7 @@ class AppliedRule(XMLObject, ExplainableMixin):
sm_dict = old_dict.setdefault(line, {}) sm_dict = old_dict.setdefault(line, {})
recurse_list = deque(({get_matching_key(sm): (sm,)},)) recurse_list = deque(({get_matching_key(sm): (sm,)},))
while recurse_list: while recurse_list:
for k, x in recurse_list.popleft().iteritems(): for k, x in six.iteritems(recurse_list.popleft()):
if not k: if not k:
continue continue
if len(x) > 1: if len(x) > 1:
......
...@@ -28,6 +28,7 @@ ...@@ -28,6 +28,7 @@
# #
############################################################################## ##############################################################################
from six import string_types as basestring
from collections import defaultdict from collections import defaultdict
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions, PropertySheet from Products.ERP5Type import Permissions, PropertySheet
...@@ -40,6 +41,7 @@ from erp5.component.interface.IBusinessProcess import IBusinessProcess ...@@ -40,6 +41,7 @@ from erp5.component.interface.IBusinessProcess import IBusinessProcess
from erp5.component.interface.IArrowBase import IArrowBase from erp5.component.interface.IArrowBase import IArrowBase
import zope.interface import zope.interface
import six
_marker = object() _marker = object()
...@@ -868,7 +870,7 @@ class BusinessProcess(Path, XMLObject): ...@@ -868,7 +870,7 @@ class BusinessProcess(Path, XMLObject):
if trade_phase_list: # reduce graph if trade_phase_list: # reduce graph
next_dict = defaultdict(set) next_dict = defaultdict(set)
# build {phase: next_set} (i.e. reverse result) # build {phase: next_set} (i.e. reverse result)
for next_, phase_set in result.iteritems(): for next_, phase_set in six.iteritems(result):
for phase in phase_set: for phase in phase_set:
next_dict[phase].add(next_) next_dict[phase].add(next_)
# for each phase to remove # for each phase to remove
......
...@@ -32,6 +32,7 @@ from Products.ERP5Type.Core.Predicate import Predicate ...@@ -32,6 +32,7 @@ from Products.ERP5Type.Core.Predicate import Predicate
from Products.ERP5Type.XMLObject import XMLObject from Products.ERP5Type.XMLObject import XMLObject
from Products.ERP5Type import Permissions, PropertySheet from Products.ERP5Type import Permissions, PropertySheet
from Products.ERP5Type.Cache import readOnlyTransactionCache from Products.ERP5Type.Cache import readOnlyTransactionCache
import six
class ContributionPredicate(Predicate, XMLObject): class ContributionPredicate(Predicate, XMLObject):
...@@ -73,9 +74,9 @@ class ContributionPredicate(Predicate, XMLObject): ...@@ -73,9 +74,9 @@ class ContributionPredicate(Predicate, XMLObject):
if getattr(aq_base(self), '_identity_criterion', None) is None: if getattr(aq_base(self), '_identity_criterion', None) is None:
self._identity_criterion = {} self._identity_criterion = {}
self._range_criterion = {} self._range_criterion = {}
for property_, value in self._identity_criterion.iteritems(): for property_, value in six.iteritems(self._identity_criterion):
result = result and (context.getProperty(property_) in value) result = result and (context.getProperty(property_) in value)
for property_, (min_, max_) in self._range_criterion.iteritems(): for property_, (min_, max_) in six.iteritems(self._range_criterion):
value = context.getProperty(property_) value = context.getProperty(property_)
if min_ is not None: if min_ is not None:
result = result and (value >= min_) result = result and (value >= min_)
......
...@@ -28,6 +28,7 @@ ...@@ -28,6 +28,7 @@
# #
############################################################################## ##############################################################################
from six import string_types as basestring
import zope.interface import zope.interface
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
......
...@@ -92,7 +92,7 @@ DOCUMENT_CONVERSION_SERVER_RETRY = 0 ...@@ -92,7 +92,7 @@ DOCUMENT_CONVERSION_SERVER_RETRY = 0
global_server_proxy_uri_failure_time = {} global_server_proxy_uri_failure_time = {}
from Products.CMFCore.utils import getToolByName from Products.CMFCore.utils import getToolByName
from functools import partial from functools import partial
from xmlrpclib import Fault, ServerProxy, ProtocolError from six.moves.xmlrpc_client import Fault, ServerProxy, ProtocolError
from socket import error as SocketError from socket import error as SocketError
from DateTime import DateTime from DateTime import DateTime
class DocumentConversionServerProxy(): class DocumentConversionServerProxy():
...@@ -152,18 +152,18 @@ class DocumentConversionServerProxy(): ...@@ -152,18 +152,18 @@ class DocumentConversionServerProxy():
# Cloudooo return result in (200 or 402, dict(), '') format or just based type # Cloudooo return result in (200 or 402, dict(), '') format or just based type
# 402 for error and 200 for ok # 402 for error and 200 for ok
result_set = func(*args, **kw) result_set = func(*args, **kw)
except SocketError, e: except SocketError as e:
message = 'Socket Error: %s' % (repr(e) or 'undefined.') message = 'Socket Error: %s' % (repr(e) or 'undefined.')
socket_error_list.append(message) socket_error_list.append(message)
retry_server_list.append((uri, server_proxy)) retry_server_list.append((uri, server_proxy))
except ProtocolError, e: except ProtocolError as e:
# Network issue # Network issue
message = "%s: %s %s" % (e.url, e.errcode, e.errmsg) message = "%s: %s %s" % (e.url, e.errcode, e.errmsg)
if e.errcode == -1: if e.errcode == -1:
message = "%s: Connection refused" % (e.url) message = "%s: Connection refused" % (e.url)
protocol_error_list.append(message) protocol_error_list.append(message)
retry_server_list.append((uri, server_proxy)) retry_server_list.append((uri, server_proxy))
except Fault, e: except Fault as e:
# Return not supported data types # Return not supported data types
fault_error_list.append(e) fault_error_list.append(e)
else: else:
...@@ -702,7 +702,7 @@ class Document(DocumentExtensibleTraversableMixin, XMLObject, UrlMixin, ...@@ -702,7 +702,7 @@ class Document(DocumentExtensibleTraversableMixin, XMLObject, UrlMixin,
Returns the list of revision numbers of the current document Returns the list of revision numbers of the current document
by by analysing the change log of the current object. by by analysing the change log of the current object.
""" """
return map(str, range(1, 1 + int(self.getRevision()))) return [str(r) for r in range(1, 1 + int(self.getRevision()))]
security.declareProtected(Permissions.ModifyPortalContent, 'mergeRevision') security.declareProtected(Permissions.ModifyPortalContent, 'mergeRevision')
def mergeRevision(self): def mergeRevision(self):
......
...@@ -325,8 +325,8 @@ class ImmobilisableItem(Item, Amount): ...@@ -325,8 +325,8 @@ class ImmobilisableItem(Item, Amount):
'price':{}, 'price':{},
'currency': {}}) 'currency': {}})
kw['immo_cache_dict'] = immo_cache_dict kw['immo_cache_dict'] = immo_cache_dict
if immo_cache_dict['period'].has_key((self.getRelativeUrl(), from_date, to_date) + if (self.getRelativeUrl(), from_date, to_date) +
tuple([(key,kw[key]) for key in kw_key_list])) : tuple([(key,kw[key]) for key in kw_key_list]) in immo_cache_dict['period'] :
return immo_cache_dict['period'][ (self.getRelativeUrl(), from_date, to_date) + return immo_cache_dict['period'][ (self.getRelativeUrl(), from_date, to_date) +
tuple( [(key,kw[key]) for key in kw_key_list]) ] tuple( [(key,kw[key]) for key in kw_key_list]) ]
def setPreviousPeriodParameters(period_list, def setPreviousPeriodParameters(period_list,
...@@ -599,7 +599,7 @@ class ImmobilisableItem(Item, Amount): ...@@ -599,7 +599,7 @@ class ImmobilisableItem(Item, Amount):
# Round dates since immobilisation calculation is made on days # Round dates since immobilisation calculation is made on days
for immo_period in immo_period_list: for immo_period in immo_period_list:
for property_ in ('start_date', 'stop_date', 'initial_date',): for property_ in ('start_date', 'stop_date', 'initial_date',):
if immo_period.has_key(property_): if property_ in immo_period:
immo_period[property_] = roundDate(immo_period[property_]) immo_period[property_] = roundDate(immo_period[property_])
immo_cache_dict['period'][ (self.getRelativeUrl(), from_date, to_date) + immo_cache_dict['period'][ (self.getRelativeUrl(), from_date, to_date) +
tuple([(key,kw[key]) for key in kw_key_list]) ] = immo_period_list tuple([(key,kw[key]) for key in kw_key_list]) ] = immo_period_list
...@@ -644,7 +644,7 @@ class ImmobilisableItem(Item, Amount): ...@@ -644,7 +644,7 @@ class ImmobilisableItem(Item, Amount):
elif len(immo_period_list) > 0 and at_date is None: elif len(immo_period_list) > 0 and at_date is None:
return 1 return 1
immo_period = immo_period_list[-1] immo_period = immo_period_list[-1]
if immo_period.has_key('stop_date'): if 'stop_date' in immo_period:
# It means the latest period is terminated before the current date # It means the latest period is terminated before the current date
return 0 return 0
return 1 return 1
...@@ -667,9 +667,9 @@ class ImmobilisableItem(Item, Amount): ...@@ -667,9 +667,9 @@ class ImmobilisableItem(Item, Amount):
if at_date is None: if at_date is None:
at_date = DateTime() at_date = DateTime()
new_kw = dict(kw) new_kw = dict(kw)
if new_kw.has_key('to_date'): if 'to_date' in new_kw:
del new_kw['to_date'] del new_kw['to_date']
if new_kw.has_key('at_date'): if 'at_date' in new_kw:
del new_kw['at_date'] del new_kw['at_date']
if immo_period_list is None: if immo_period_list is None:
immo_period_list = self.getImmobilisationPeriodList(to_date=at_date, **new_kw) immo_period_list = self.getImmobilisationPeriodList(to_date=at_date, **new_kw)
...@@ -706,9 +706,9 @@ class ImmobilisableItem(Item, Amount): ...@@ -706,9 +706,9 @@ class ImmobilisableItem(Item, Amount):
at_date = DateTime() at_date = DateTime()
new_kw = dict(kw) new_kw = dict(kw)
if new_kw.has_key('to_date'): if 'to_date' in new_kw:
del new_kw['to_date'] del new_kw['to_date']
if new_kw.has_key('at_date'): if 'at_date' in new_kw:
del new_kw['at_date'] del new_kw['at_date']
if immo_period_list is None: if immo_period_list is None:
immo_period_list = self.getImmobilisationPeriodList(to_date=at_date, **new_kw) immo_period_list = self.getImmobilisationPeriodList(to_date=at_date, **new_kw)
...@@ -718,7 +718,7 @@ class ImmobilisableItem(Item, Amount): ...@@ -718,7 +718,7 @@ class ImmobilisableItem(Item, Amount):
immo_period = immo_period_list[-1] immo_period = immo_period_list[-1]
# Second case : the item is not currently immobilised # Second case : the item is not currently immobilised
if immo_period.has_key('stop_date'): if 'stop_date' in immo_period:
return immo_period['stop_durability'] return immo_period['stop_durability']
# Third case : the item is currently immobilised # Third case : the item is currently immobilised
...@@ -778,7 +778,7 @@ class ImmobilisableItem(Item, Amount): ...@@ -778,7 +778,7 @@ class ImmobilisableItem(Item, Amount):
""" """
if at_date is None: if at_date is None:
at_date = DateTime() at_date = DateTime()
kw_key_list = kw.keys() kw_key_list = list(kw.keys())
kw_key_list.sort() kw_key_list.sort()
if kw_key_list.count('immo_cache_dict'): if kw_key_list.count('immo_cache_dict'):
...@@ -790,7 +790,7 @@ class ImmobilisableItem(Item, Amount): ...@@ -790,7 +790,7 @@ class ImmobilisableItem(Item, Amount):
immo_cache_dict_price_key = ((self.getRelativeUrl(), at_date) + immo_cache_dict_price_key = ((self.getRelativeUrl(), at_date) +
tuple([(key,kw[key]) for key in kw_key_list])) tuple([(key,kw[key]) for key in kw_key_list]))
if immo_cache_dict['price'].has_key(immo_cache_dict_price_key) : if immo_cache_dict_price_key in immo_cache_dict['price'] :
returned_price = immo_cache_dict['price'][immo_cache_dict_price_key] returned_price = immo_cache_dict['price'][immo_cache_dict_price_key]
if with_currency: if with_currency:
currency = immo_cache_dict['currency'][immo_cache_dict_price_key] currency = immo_cache_dict['currency'][immo_cache_dict_price_key]
...@@ -827,7 +827,7 @@ class ImmobilisableItem(Item, Amount): ...@@ -827,7 +827,7 @@ class ImmobilisableItem(Item, Amount):
start_durability = self.getRemainingDurability(at_date=start_date, start_durability = self.getRemainingDurability(at_date=start_date,
immo_cache_dict=immo_cache_dict) immo_cache_dict=immo_cache_dict)
# Get the current period stop date, duration and durability # Get the current period stop date, duration and durability
if immo_period.has_key('stop_date'): if 'stop_date' in immo_period:
stop_date = immo_period['stop_date'] stop_date = immo_period['stop_date']
period_stop_date = stop_date period_stop_date = stop_date
else: else:
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
# #
############################################################################## ##############################################################################
from six.moves import xrange
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions, PropertySheet from Products.ERP5Type import Permissions, PropertySheet
from Products.ERP5Type.Accessor.Constant import PropertyGetter as ConstantGetter from Products.ERP5Type.Accessor.Constant import PropertyGetter as ConstantGetter
...@@ -175,7 +176,7 @@ class Inventory(Delivery): ...@@ -175,7 +176,7 @@ class Inventory(Delivery):
current_inventory_key[x] = "" current_inventory_key[x] = ""
current_inventory_key = tuple(current_inventory_key) current_inventory_key = tuple(current_inventory_key)
if inventory_calculation_dict.has_key("second_level"): if "second_level" in inventory_calculation_dict:
# two level of variation # two level of variation
try: try:
current_inventory_by_sub_variation = \ current_inventory_by_sub_variation = \
...@@ -219,7 +220,7 @@ class Inventory(Delivery): ...@@ -219,7 +220,7 @@ class Inventory(Delivery):
key_list.append(method()) key_list.append(method())
inventory_value = current_inventory_dict.get(tuple(key_list), 0) inventory_value = current_inventory_dict.get(tuple(key_list), 0)
second_key_list = [] second_key_list = []
if inventory_calculation_dict.has_key('second_level'): if 'second_level' in inventory_calculation_dict:
if inventory_value == 0: if inventory_value == 0:
inventory_value = {} inventory_value = {}
# two level # two level
...@@ -229,7 +230,7 @@ class Inventory(Delivery): ...@@ -229,7 +230,7 @@ class Inventory(Delivery):
if method is not None: if method is not None:
second_key_list.append(method()) second_key_list.append(method())
second_key_list = tuple(second_key_list) second_key_list = tuple(second_key_list)
if inventory_value.has_key(second_key_list): if second_key_list in inventory_value:
total_quantity = inventory_value.pop(second_key_list) total_quantity = inventory_value.pop(second_key_list)
# Put remaining subvariation in a dict to know which one # Put remaining subvariation in a dict to know which one
# to removed at end # to removed at end
...@@ -264,7 +265,7 @@ class Inventory(Delivery): ...@@ -264,7 +265,7 @@ class Inventory(Delivery):
category_list = self.getCategoryList() category_list = self.getCategoryList()
setter_list = [x['setter'] for x in inventory_calculation_dict['first_level']] setter_list = [x['setter'] for x in inventory_calculation_dict['first_level']]
if inventory_calculation_dict.has_key("second_level"): if "second_level" in inventory_calculation_dict:
setter_list.extend([x['setter'] for x in inventory_calculation_dict['second_level']]) setter_list.extend([x['setter'] for x in inventory_calculation_dict['second_level']])
value_list = list(key_list) + list(second_key_list) value_list = list(key_list) + list(second_key_list)
for x in xrange(len(setter_list)): for x in xrange(len(setter_list)):
...@@ -310,7 +311,7 @@ class Inventory(Delivery): ...@@ -310,7 +311,7 @@ class Inventory(Delivery):
category_list = self.getCategoryList() category_list = self.getCategoryList()
setter_list = [x['setter'] for x in inventory_calculation_dict['first_level']] setter_list = [x['setter'] for x in inventory_calculation_dict['first_level']]
if inventory_calculation_dict.has_key("second_level"): if "second_level" in inventory_calculation_dict:
setter_list.extend([x['setter'] for x in inventory_calculation_dict['second_level']]) setter_list.extend([x['setter'] for x in inventory_calculation_dict['second_level']])
value_list = list(first_level_key) + list(second_level_key) value_list = list(first_level_key) + list(second_level_key)
for x in xrange(len(setter_list)): for x in xrange(len(setter_list)):
......
...@@ -40,6 +40,7 @@ from zLOG import LOG, WARNING ...@@ -40,6 +40,7 @@ from zLOG import LOG, WARNING
from Products.ERP5.mixin.property_recordable import PropertyRecordableMixin from Products.ERP5.mixin.property_recordable import PropertyRecordableMixin
from erp5.component.mixin.ExplainableMixin import ExplainableMixin from erp5.component.mixin.ExplainableMixin import ExplainableMixin
from erp5.component.interface.IExpandable import IExpandable from erp5.component.interface.IExpandable import IExpandable
import six
# XXX Do we need to create groups ? (ie. confirm group include confirmed, getting_ready and ready # XXX Do we need to create groups ? (ie. confirm group include confirmed, getting_ready and ready
...@@ -673,7 +674,7 @@ class SimulationMovement(PropertyRecordableMixin, Movement, ExplainableMixin): ...@@ -673,7 +674,7 @@ class SimulationMovement(PropertyRecordableMixin, Movement, ExplainableMixin):
path_set_to_check): path_set_to_check):
yield d yield d
for id_, t in tree_node.visited_movement_dict.iteritems(): for id_, t in six.iteritems(tree_node.visited_movement_dict):
subdocument, path = t subdocument, path = t
to_check = path_set_to_check to_check = path_set_to_check
# do we need to change/copy the set? # do we need to change/copy the set?
......
...@@ -35,7 +35,7 @@ from erp5.component.document.Document import Document, ConversionError, _MARKER, ...@@ -35,7 +35,7 @@ from erp5.component.document.Document import Document, ConversionError, _MARKER,
from erp5.component.document.File import File from erp5.component.document.File import File
from erp5.component.module.WebDAVSupport import TextContent from erp5.component.module.WebDAVSupport import TextContent
from erp5.component.document.Document import VALID_IMAGE_FORMAT_LIST, VALID_TEXT_FORMAT_LIST from erp5.component.document.Document import VALID_IMAGE_FORMAT_LIST, VALID_TEXT_FORMAT_LIST
import cStringIO import io
from string import Template from string import Template
# Mixin Import # Mixin Import
...@@ -174,7 +174,7 @@ class TextDocument(CachedConvertableMixin, BaseConvertableFileMixin, TextContent ...@@ -174,7 +174,7 @@ class TextDocument(CachedConvertableMixin, BaseConvertableFileMixin, TextContent
# Include extra parameter for image conversions # Include extra parameter for image conversions
temp_image = self.portal_contributions.newContent( temp_image = self.portal_contributions.newContent(
portal_type='Image', portal_type='Image',
file=cStringIO.StringIO(), file=io.StringIO(),
filename=self.getId(), filename=self.getId(),
temp_object=1) temp_object=1)
temp_image._setData(result) temp_image._setData(result)
......
...@@ -27,6 +27,9 @@ ...@@ -27,6 +27,9 @@
# #
############################################################################## ##############################################################################
import six
from past.builtins import cmp
from hashlib import md5 from hashlib import md5
# Some workflow does not make sense in the context of mass transition and are # Some workflow does not make sense in the context of mass transition and are
...@@ -125,7 +128,7 @@ def getDocumentGroupByWorkflowStateList(self, form_id='', **kw): ...@@ -125,7 +128,7 @@ def getDocumentGroupByWorkflowStateList(self, form_id='', **kw):
for (ptype, workflow_id, _), (doc, document_count) in\ for (ptype, workflow_id, _), (doc, document_count) in\
workflow_state_dict.iteritems(): six.iteritems(workflow_state_dict):
workflow = wf_tool._getOb(workflow_id) workflow = wf_tool._getOb(workflow_id)
state_var = workflow.getStateVariable() state_var = workflow.getStateVariable()
translated_workflow_state_title = doc.getProperty( translated_workflow_state_title = doc.getProperty(
......
from six import string_types as basestring
import json import json
from Products.ERP5Type.Utils import checkPythonSourceCode from Products.ERP5Type.Utils import checkPythonSourceCode
......
...@@ -37,6 +37,7 @@ from Products.ERP5Type import Permissions ...@@ -37,6 +37,7 @@ from Products.ERP5Type import Permissions
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
from erp5.component.document.MappedValue import MappedValue from erp5.component.document.MappedValue import MappedValue
from erp5.component.interface.IAmountGenerator import IAmountGenerator from erp5.component.interface.IAmountGenerator import IAmountGenerator
import six
# XXX What should be done when there is no base_application ? # XXX What should be done when there is no base_application ?
# There are 2 options: # There are 2 options:
...@@ -415,7 +416,7 @@ class AmountGeneratorMixin: ...@@ -415,7 +416,7 @@ class AmountGeneratorMixin:
del cell_aggregate[self_key] del cell_aggregate[self_key]
# Allow base_application & base_contribution to be variated. # Allow base_application & base_contribution to be variated.
for property_dict in cell_aggregate.itervalues(): for property_dict in six.itervalues(cell_aggregate):
base_amount_set = property_dict['base_application_set'] base_amount_set = property_dict['base_application_set']
variation_list = tuple(sorted(x for x in base_amount_set variation_list = tuple(sorted(x for x in base_amount_set
if not x.startswith('base_amount/'))) if not x.startswith('base_amount/')))
...@@ -481,7 +482,7 @@ class AmountGeneratorMixin: ...@@ -481,7 +482,7 @@ class AmountGeneratorMixin:
amount._setQuantity(quantity) amount._setQuantity(quantity)
amount._setTitle(self.getTitle()) amount._setTitle(self.getTitle())
amount._setDescription(self.getDescription()) amount._setDescription(self.getDescription())
for x in property_dict.iteritems(): for x in six.iteritems(property_dict):
amount._setProperty(*x) amount._setProperty(*x)
# convert to default management unit if possible # convert to default management unit if possible
amount._setQuantity(amount.getConvertedQuantity()) amount._setQuantity(amount.getConvertedQuantity())
......
...@@ -31,7 +31,7 @@ from AccessControl import ClassSecurityInfo ...@@ -31,7 +31,7 @@ from AccessControl import ClassSecurityInfo
from Products.ERP5Type.Globals import InitializeClass from Products.ERP5Type.Globals import InitializeClass
from Products.ERP5Type import Permissions from Products.ERP5Type import Permissions
from OFS.Image import Pdata from OFS.Image import Pdata
from cStringIO import StringIO from io import StringIO
_MARKER = object() _MARKER = object()
class BaseConvertableFileMixin: class BaseConvertableFileMixin:
......
...@@ -27,6 +27,7 @@ ...@@ -27,6 +27,7 @@
# #
############################################################################## ##############################################################################
import six
from hashlib import md5 from hashlib import md5
from warnings import warn from warnings import warn
import string import string
...@@ -52,7 +53,10 @@ def hashPdataObject(pdata_object): ...@@ -52,7 +53,10 @@ def hashPdataObject(pdata_object):
while pdata_object is not None: while pdata_object is not None:
chunk = pdata_object.aq_base chunk = pdata_object.aq_base
md5_hash.update(chunk.data) md5_hash.update(chunk.data)
pdata_object = chunk.next if six.PY2:
pdata_object = chunk.next
else:
pdata_object = chunk.__next__
chunk._p_deactivate() chunk._p_deactivate()
return md5_hash.hexdigest() return md5_hash.hexdigest()
...@@ -135,7 +139,7 @@ class CachedConvertableMixin: ...@@ -135,7 +139,7 @@ class CachedConvertableMixin:
cached_value = data cached_value = data
conversion_md5 = md5(str(data.data)).hexdigest() conversion_md5 = md5(str(data.data)).hexdigest()
size = len(data.data) size = len(data.data)
elif isinstance(data, (str, unicode,)): elif isinstance(data, six.string_types):
cached_value = data cached_value = data
conversion_md5 = md5(cached_value).hexdigest() conversion_md5 = md5(cached_value).hexdigest()
size = len(cached_value) size = len(cached_value)
......
...@@ -27,11 +27,12 @@ ...@@ -27,11 +27,12 @@
# #
############################################################################## ##############################################################################
import six
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type.Globals import InitializeClass from Products.ERP5Type.Globals import InitializeClass
from Products.ERP5Type import Permissions from Products.ERP5Type import Permissions
from Products.ERP5Type.Utils import normaliseUrl from Products.ERP5Type.Utils import normaliseUrl
from urlparse import urlsplit, urlunsplit from six.moves.urllib.parse import urlsplit, urlunsplit
from lxml import html as etree_html from lxml import html as etree_html
class CrawlableMixin: class CrawlableMixin:
...@@ -110,7 +111,7 @@ class CrawlableMixin: ...@@ -110,7 +111,7 @@ class CrawlableMixin:
# For now take into acount only a and img tags # For now take into acount only a and img tags
if attribute_name not in ('href',): if attribute_name not in ('href',):
continue continue
if isinstance(link, unicode): if isinstance(link, six.text_type):
link = link.encode('utf-8') link = link.encode('utf-8')
href_list.append(link) href_list.append(link)
return href_list return href_list
...@@ -128,7 +129,7 @@ class CrawlableMixin: ...@@ -128,7 +129,7 @@ class CrawlableMixin:
path_part = '/'.join(path_part.split('/')[:-1]) path_part = '/'.join(path_part.split('/')[:-1])
base_url = urlunsplit((splitted_url[0], splitted_url[1], path_part, None, base_url = urlunsplit((splitted_url[0], splitted_url[1], path_part, None,
None)) None))
if isinstance(base_url, unicode): if isinstance(base_url, six.text_type):
base_url = base_url.encode('utf-8') base_url = base_url.encode('utf-8')
return base_url return base_url
...@@ -144,7 +145,7 @@ class CrawlableMixin: ...@@ -144,7 +145,7 @@ class CrawlableMixin:
# in www.example.com or www.3.example.com # in www.example.com or www.3.example.com
# keep only the example.com part # keep only the example.com part
reference_domain = ''.join(reference_domain.split('.')[-2:]) reference_domain = ''.join(reference_domain.split('.')[-2:])
if isinstance(reference_domain, unicode): if isinstance(reference_domain, six.text_type):
reference_domain = reference_domain.encode('utf-8') reference_domain = reference_domain.encode('utf-8')
url_list = [] url_list = []
base_url = self.getContentBaseURL() base_url = self.getContentBaseURL()
...@@ -158,7 +159,7 @@ class CrawlableMixin: ...@@ -158,7 +159,7 @@ class CrawlableMixin:
if not url: if not url:
continue continue
url_domain = urlsplit(url)[1] url_domain = urlsplit(url)[1]
if isinstance(url_domain, unicode): if isinstance(url_domain, six.text_type):
url_domain = url_domain.encode('utf-8') url_domain = url_domain.encode('utf-8')
if url_domain and ''.join(url_domain.split('.')[-2:]) != reference_domain: if url_domain and ''.join(url_domain.split('.')[-2:]) != reference_domain:
continue continue
......
...@@ -36,6 +36,7 @@ from Products.ERP5Type.Utils import convertToUpperCase ...@@ -36,6 +36,7 @@ from Products.ERP5Type.Utils import convertToUpperCase
from erp5.component.mixin.CachedConvertableMixin import CachedConvertableMixin from erp5.component.mixin.CachedConvertableMixin import CachedConvertableMixin
import os import os
import re import re
import six
try: try:
import magic import magic
...@@ -164,7 +165,7 @@ class DiscoverableMixin(CachedConvertableMixin): ...@@ -164,7 +165,7 @@ class DiscoverableMixin(CachedConvertableMixin):
else: else:
result = method() result = method()
if result is not None: if result is not None:
for key, value in result.iteritems(): for key, value in six.iteritems(result):
if value not in (None, ''): if value not in (None, ''):
kw[key]=value kw[key]=value
# Prepare the content edit parameters # Prepare the content edit parameters
......
...@@ -119,7 +119,7 @@ class MailMessageMixin: ...@@ -119,7 +119,7 @@ class MailMessageMixin:
for (name, value) in self._getMessage().items(): for (name, value) in self._getMessage().items():
try: try:
decoded_header = decode_header(value) decoded_header = decode_header(value)
except HeaderParseError, error_message: except HeaderParseError as error_message:
decoded_header = () decoded_header = ()
LOG('MailMessageMixin.getContentInformation', INFO, LOG('MailMessageMixin.getContentInformation', INFO,
'Failed to decode %s header of %s with error: %s' % 'Failed to decode %s header of %s with error: %s' %
......
...@@ -110,7 +110,7 @@ class MovementCollectionUpdaterMixin: ...@@ -110,7 +110,7 @@ class MovementCollectionUpdaterMixin:
# First find out all existing (decision) movements which belong to no group # First find out all existing (decision) movements which belong to no group
no_group_list = [] no_group_list = []
for tester_key in decision_movement_dict.keys(): for tester_key in decision_movement_dict.keys():
if prevision_movement_dict.has_key(tester_key): if tester_key in prevision_movement_dict:
for decision_movement in decision_movement_dict[tester_key]: for decision_movement in decision_movement_dict[tester_key]:
no_match = True no_match = True
for prevision_movement in prevision_movement_dict[tester_key]: for prevision_movement in prevision_movement_dict[tester_key]:
......
...@@ -57,7 +57,7 @@ class UrlMixin: ...@@ -57,7 +57,7 @@ class UrlMixin:
# A quick fix for all objects which did not # A quick fix for all objects which did not
# define protocol such as email addresses # define protocol such as email addresses
ptype = self.getPortalType() ptype = self.getPortalType()
if default_protocol_dict.has_key(ptype): if ptype in default_protocol_dict:
protocol = default_protocol_dict[ptype] protocol = default_protocol_dict[ptype]
else: else:
protocol = 'http' protocol = 'http'
......
...@@ -32,7 +32,7 @@ import warnings ...@@ -32,7 +32,7 @@ import warnings
from AccessControl import ModuleSecurityInfo from AccessControl import ModuleSecurityInfo
from DateTime import DateTime from DateTime import DateTime
from datetime import datetime from datetime import datetime
from string import zfill import six
security = ModuleSecurityInfo(__name__) security = ModuleSecurityInfo(__name__)
security.declarePublic('addToDate', 'getClosestDate', security.declarePublic('addToDate', 'getClosestDate',
...@@ -268,7 +268,7 @@ def getIntervalListBetweenDates(from_date=None, to_date=None, ...@@ -268,7 +268,7 @@ def getIntervalListBetweenDates(from_date=None, to_date=None,
[]).append(to_date.strftime(format_dict[current_key])) []).append(to_date.strftime(format_dict[current_key]))
returned_value_dict = {} returned_value_dict = {}
for key, value in diff_value_dict.iteritems(): for key, value in six.iteritems(diff_value_dict):
if to_inverse: if to_inverse:
value.reverse() value.reverse()
returned_value_dict[key] = value returned_value_dict[key] = value
...@@ -446,7 +446,7 @@ def convertDateToHour(date=None): ...@@ -446,7 +446,7 @@ def convertDateToHour(date=None):
# and this provides the use of toordinal method. # and this provides the use of toordinal method.
formatted_creation_date = datetime(creation_date_dict['year'],creation_date_dict['month'],creation_date_dict['day']) formatted_creation_date = datetime(creation_date_dict['year'],creation_date_dict['month'],creation_date_dict['day'])
# reference date which is the first day of creation date year # reference date which is the first day of creation date year
reference_date = datetime(creation_date_dict['year'], 01, 1) reference_date = datetime(creation_date_dict['year'], 0o1, 1)
# calculate the ordinal date of the creation date and the reference date # calculate the ordinal date of the creation date and the reference date
ordinal_date = datetime.toordinal(formatted_creation_date) ordinal_date = datetime.toordinal(formatted_creation_date)
ordinal_reference_date = datetime.toordinal(reference_date) ordinal_reference_date = datetime.toordinal(reference_date)
...@@ -494,7 +494,7 @@ def atTheEndOfPeriod(date, period): ...@@ -494,7 +494,7 @@ def atTheEndOfPeriod(date, period):
if period == 'year': if period == 'year':
end = addToDate(DateTime('%s/01/01 00:00:00 %s' % (date.year(), date.timezone())), **{period:1}) end = addToDate(DateTime('%s/01/01 00:00:00 %s' % (date.year(), date.timezone())), **{period:1})
elif period == 'month': elif period == 'month':
end = addToDate(DateTime('%s/%s/01 00:00:00 %s' % (date.year(), zfill(date.month(), 2), date.timezone())), **{period:1}) end = addToDate(DateTime('%s/%02d/01 00:00:00 %s' % (date.year(), date.month(), date.timezone())), **{period:1})
elif period == 'day': elif period == 'day':
end = addToDate(date.earliestTime(), hour=36).earliestTime() end = addToDate(date.earliestTime(), hour=36).earliestTime()
elif period == 'week': elif period == 'week':
......
...@@ -95,8 +95,9 @@ class DiffFile(object): ...@@ -95,8 +95,9 @@ class DiffFile(object):
tmp.append(line) tmp.append(line)
self.children.append(CodeBlock(os.linesep.join(tmp))) self.children.append(CodeBlock(os.linesep.join(tmp)))
def __nonzero__(self): def __bool__(self):
return self.binary or bool(self.children) return self.binary or bool(self.children)
__nonzero__ = __bool__ # six.PY2
def __len__(self): def __len__(self):
return len(self.children) return len(self.children)
......
...@@ -239,7 +239,7 @@ class ExplanationCache: ...@@ -239,7 +239,7 @@ class ExplanationCache:
# Build a list of path patterns which apply to current business_link # Build a list of path patterns which apply to current business_link
path_list = iter(self.getSimulationPathPatternList()) path_list = iter(self.getSimulationPathPatternList())
path_dict = {x: path_list.next() for x in path_list} path_dict = {x: next(path_list) for x in path_list}
# path_dict is like this; # path_dict is like this;
# {'/erp5/portal_simulation/3/4': r'/erp5/portal\_simulation/3/4/%'} # {'/erp5/portal_simulation/3/4': r'/erp5/portal\_simulation/3/4/%'}
path_list = [] path_list = []
......
...@@ -31,6 +31,7 @@ from collections import defaultdict, OrderedDict ...@@ -31,6 +31,7 @@ from collections import defaultdict, OrderedDict
import zope.interface import zope.interface
from AccessControl import allow_class from AccessControl import allow_class
from erp5.component.interface.IAmountList import IAmountList from erp5.component.interface.IAmountList import IAmountList
import six
@zope.interface.implementer(IAmountList) @zope.interface.implementer(IAmountList)
class GeneratedAmountList(list): class GeneratedAmountList(list):
...@@ -87,7 +88,7 @@ class GeneratedAmountList(list): ...@@ -87,7 +88,7 @@ class GeneratedAmountList(list):
else: else:
aggregate[1] += amount.getQuantity() aggregate[1] += amount.getQuantity()
from erp5.component.document.RoundingModel import RoundingProxy from erp5.component.document.RoundingModel import RoundingProxy
for amount, quantity in aggregate_dict.itervalues(): for amount, quantity in six.itervalues(aggregate_dict):
# Before we ignore 'quantity==0' amount here for better performance, # Before we ignore 'quantity==0' amount here for better performance,
# but it is not a good idea, especially when the first expand causes # but it is not a good idea, especially when the first expand causes
# non-zero quantity and then quantity becomes zero. # non-zero quantity and then quantity becomes zero.
......
...@@ -112,7 +112,7 @@ def _getPropertyList(document, acquire=True): ...@@ -112,7 +112,7 @@ def _getPropertyList(document, acquire=True):
elif (x.get('storage_id') or property_id) not in document_dict: elif (x.get('storage_id') or property_id) not in document_dict:
continue continue
# we don't want acquired properties without acquisition_mask_value # we don't want acquired properties without acquisition_mask_value
elif x.has_key('acquisition_base_category') and not x.get('acquisition_mask_value', 0): elif 'acquisition_base_category' in x and not x.get('acquisition_mask_value', 0):
continue continue
elif x['type'] in list_types and not property_id.endswith('_list'): elif x['type'] in list_types and not property_id.endswith('_list'):
property_dict[property_id] = getPropertyList(property_id) property_dict[property_id] = getPropertyList(property_id)
......
...@@ -26,9 +26,7 @@ ...@@ -26,9 +26,7 @@
# #
############################################################################## ##############################################################################
from xmlrpclib import ProtocolError from six.moves.xmlrpc_client import ProtocolError, Transport, SafeTransport
from xmlrpclib import Transport
from xmlrpclib import SafeTransport
import socket import socket
class TimeoutTransport(SafeTransport): class TimeoutTransport(SafeTransport):
......
...@@ -23,7 +23,8 @@ from Products.ERP5Type.Globals import InitializeClass ...@@ -23,7 +23,8 @@ from Products.ERP5Type.Globals import InitializeClass
from Products.ERP5Type import Permissions from Products.ERP5Type import Permissions
from Products.CMFCore.PortalContent import ResourceLockedError from Products.CMFCore.PortalContent import ResourceLockedError
from zExceptions import Forbidden from zExceptions import Forbidden
from cStringIO import StringIO from io import StringIO
import six
security = ModuleSecurityInfo(__name__) security = ModuleSecurityInfo(__name__)
...@@ -61,7 +62,7 @@ class TextContent: ...@@ -61,7 +62,7 @@ class TextContent:
title = tree.find("head/title") title = tree.find("head/title")
if title is not None: if title is not None:
headers["title"] = title.text headers["title"] = title.text
return {k: v if len(v) > 1 else v[0] for k, v in headers.iteritems()} return {k: v if len(v) > 1 else v[0] for k, v in six.iteritems(headers)}
## FTP handlers ## FTP handlers
security.declareProtected(Permissions.ModifyPortalContent, 'PUT') security.declareProtected(Permissions.ModifyPortalContent, 'PUT')
......
from urllib import unquote from six.moves.urllib.parse import unquote
return unquote(value).decode('base64').split(':', 1)[0] from base64 import standard_b64decode
return standard_b64decode(unquote(value)).split(b':', 1)[0].decode()
...@@ -9,7 +9,7 @@ if username is not None: ...@@ -9,7 +9,7 @@ if username is not None:
) )
) )
REQUEST = portal.REQUEST REQUEST = portal.REQUEST
if REQUEST.has_key('portal_skin'): if 'portal_skin' in REQUEST:
portal.portal_skins.clearSkinCookie() portal.portal_skins.clearSkinCookie()
REQUEST.RESPONSE.expireCookie('__ac', path='/') REQUEST.RESPONSE.expireCookie('__ac', path='/')
......
from urlparse import urlparse from six.moves.urllib.parse import urlparse
portal = context.getPortalObject() portal = context.getPortalObject()
kw = {} kw = {}
......
...@@ -90,7 +90,7 @@ try: ...@@ -90,7 +90,7 @@ try:
request.set('editable_mode', 1) request.set('editable_mode', 1)
form.validate_all_to_request(request) form.validate_all_to_request(request)
request.set('editable_mode', editable_mode) request.set('editable_mode', editable_mode)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
...@@ -159,7 +159,7 @@ listbox_uid = kw.get('listbox_uid', None) ...@@ -159,7 +159,7 @@ listbox_uid = kw.get('listbox_uid', None)
# In some cases, the listbox exists, is editable, but the selection name # In some cases, the listbox exists, is editable, but the selection name
# has no meaning, for example fast input dialogs. # has no meaning, for example fast input dialogs.
# In such cases, we must not try to update a non-existing selection. # In such cases, we must not try to update a non-existing selection.
if listbox_uid is not None and kw.has_key('list_selection_name'): if listbox_uid is not None and 'list_selection_name' in kw:
uids = kw.get('uids') uids = kw.get('uids')
context.portal_selections.updateSelectionCheckedUidList( context.portal_selections.updateSelectionCheckedUidList(
kw['list_selection_name'], kw['list_selection_name'],
......
...@@ -20,7 +20,7 @@ try: ...@@ -20,7 +20,7 @@ try:
sort_on += [(k, v, t)] sort_on += [(k, v, t)]
i += 1 i += 1
context.portal_selections.setSelectionSortOrder(selection_name, sort_on) context.portal_selections.setSelectionSortOrder(selection_name, sort_on)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
......
...@@ -62,7 +62,7 @@ try: ...@@ -62,7 +62,7 @@ try:
if k != 'None': if k != 'None':
columns += [(k , columns_dict[k])] columns += [(k , columns_dict[k])]
context.portal_selections.setSelectionColumns(selection_name, columns, REQUEST=request) context.portal_selections.setSelectionColumns(selection_name, columns, REQUEST=request)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
......
...@@ -13,10 +13,10 @@ kw = { 'selection_index': selection_index, ...@@ -13,10 +13,10 @@ kw = { 'selection_index': selection_index,
# Default behaviour is not as great but returns something # Default behaviour is not as great but returns something
kw.update(request.form) kw.update(request.form)
if kw.has_key('listbox_uid'): del kw['listbox_uid'] if 'listbox_uid' in kw: del kw['listbox_uid']
if kw.has_key('list_start'): del kw['list_start'] if 'list_start' in kw: del kw['list_start']
if request.form.has_key('dialog_id'): if 'dialog_id' in request.form:
form_id = request.form['dialog_id'] form_id = request.form['dialog_id']
else: else:
form_id = request.form['form_id'] form_id = request.form['form_id']
......
...@@ -37,14 +37,14 @@ edit_order = form.edit_order ...@@ -37,14 +37,14 @@ edit_order = form.edit_order
try: try:
# Validate # Validate
form.validate_all_to_request(request, key_prefix=key_prefix) form.validate_all_to_request(request, key_prefix=key_prefix)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
# Make sure editors are pushed back as values into the REQUEST object # Make sure editors are pushed back as values into the REQUEST object
for field in form.get_fields(): for field in form.get_fields():
field_id = field.id field_id = field.id
if request.has_key(field_id): if field_id in request:
value = request.get(field_id) value = request.get(field_id)
if callable(value): if callable(value):
value(request) value(request)
...@@ -163,11 +163,11 @@ def editMatrixBox(matrixbox_field, matrixbox): ...@@ -163,11 +163,11 @@ def editMatrixBox(matrixbox_field, matrixbox):
cell = matrix_context.newCell(*cell_index_tuple, **k_dict) cell = matrix_context.newCell(*cell_index_tuple, **k_dict)
if cell is not None: if cell is not None:
cell.edit(edit_order=edit_order, **global_property_dict) # First update globals which include the def. of property_list cell.edit(edit_order=edit_order, **global_property_dict) # First update globals which include the def. of property_list
if cell_dict.has_key('variated_property'): if 'variated_property' in cell_dict:
# For Variated Properties # For Variated Properties
variated_property = cell_dict['variated_property'] variated_property = cell_dict['variated_property']
del cell_dict['variated_property'] del cell_dict['variated_property']
if global_property_dict.has_key('mapped_value_property_list'): if 'mapped_value_property_list' in global_property_dict:
# Change the property which is defined by the # Change the property which is defined by the
# first element of mapped_value_property_list # first element of mapped_value_property_list
# XXX May require some changes with Sets # XXX May require some changes with Sets
......
...@@ -11,7 +11,7 @@ old_request = dict(saved_form_data) ...@@ -11,7 +11,7 @@ old_request = dict(saved_form_data)
field = getattr(context, form_id).get_field(field_id) field = getattr(context, form_id).get_field(field_id)
field_key = field.generate_field_key() field_key = field.generate_field_key()
if old_request.has_key('sub_index'): if 'sub_index' in old_request:
if len(uids) > 0: if len(uids) > 0:
# XXX Hardcoded # XXX Hardcoded
sub_field_key = field.generate_subfield_key("%s_%s" % (SUB_FIELD_ID, old_request['sub_index']), key=field_key) sub_field_key = field.generate_subfield_key("%s_%s" % (SUB_FIELD_ID, old_request['sub_index']), key=field_key)
......
...@@ -19,14 +19,14 @@ form = getattr(context,form_id) ...@@ -19,14 +19,14 @@ form = getattr(context,form_id)
try: try:
# Validate # Validate
form.validate_all_to_request(request) form.validate_all_to_request(request)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
# Make sure editors are pushed back as values into the REQUEST object # Make sure editors are pushed back as values into the REQUEST object
for f in form.get_fields(): for f in form.get_fields():
field_id = f.id field_id = f.id
if request.has_key(field_id): if field_id in request:
value = request.get(field_id) value = request.get(field_id)
if callable(value): if callable(value):
value(request) value(request)
...@@ -69,7 +69,7 @@ try: ...@@ -69,7 +69,7 @@ try:
for encapsulated_editor in encapsulated_editor_list: for encapsulated_editor in encapsulated_editor_list:
encapsulated_editor.edit(context) encapsulated_editor.edit(context)
except ActivityPendingError,e: except ActivityPendingError as e:
message = Base_translateString("%s" % e) message = Base_translateString("%s" % e)
ignore_layout = int(ignore_layout) ignore_layout = int(ignore_layout)
......
from Products.ERP5Type.Message import translateString from Products.ERP5Type.Message import translateString
from Products.ERP5Type.Document import newTempBase from Products.ERP5Type.Document import newTempBase
from string import zfill
portal = context.getPortalObject() portal = context.getPortalObject()
request = context.REQUEST request = context.REQUEST
domain_list = [] domain_list = []
...@@ -28,7 +27,7 @@ if depth == 0: ...@@ -28,7 +27,7 @@ if depth == 0:
# 0.125 means 3 hours in DateTime float format # 0.125 means 3 hours in DateTime float format
while current_date < bound_stop: while current_date < bound_stop:
# Create one Temp Object # Create one Temp Object
o = newTempBase(portal, id='year', uid='new_%s' % zfill('year',4)) o = newTempBase(portal, id='year', uid='new_year')
# Setting Axis Dates start and stop # Setting Axis Dates start and stop
o.setProperty('start',current_date) o.setProperty('start',current_date)
o.setProperty('stop', current_date + 0.125) o.setProperty('stop', current_date + 0.125)
......
...@@ -4,7 +4,6 @@ ...@@ -4,7 +4,6 @@
from Products.ERP5Type.Message import Message from Products.ERP5Type.Message import Message
from Products.ERP5Type.Document import newTempBase from Products.ERP5Type.Document import newTempBase
from Products.PythonScripts.standard import url_quote from Products.PythonScripts.standard import url_quote
from string import zfill
portal = context.getPortalObject() portal = context.getPortalObject()
request = context.REQUEST request = context.REQUEST
domain_list = [] domain_list = []
...@@ -19,7 +18,7 @@ zoom_begin = DateTime(bound_start.year(), bound_start.month(), bound_start.day() ...@@ -19,7 +18,7 @@ zoom_begin = DateTime(bound_start.year(), bound_start.month(), bound_start.day()
# Normalize Month. # Normalize Month.
month = zoom_begin.month() + zoom_variation month = zoom_begin.month() + zoom_variation
year = zoom_begin.year() + (month - 1) / 12 year = zoom_begin.year() + (month - 1) // 12
month = month % 12 month = month % 12
if month == 0: if month == 0:
month = 12 month = 12
...@@ -47,7 +46,7 @@ if depth == 0: ...@@ -47,7 +46,7 @@ if depth == 0:
while current_date < axis_stop: while current_date < axis_stop:
# Create one Temp Object # Create one Temp Object
o = newTempBase(portal, id=str(current_date.Day()), o = newTempBase(portal, id=str(current_date.Day()),
uid='new_%s' % zfill('year',4)) uid='new_year')
# Setting Axis Dates start and stop # Setting Axis Dates start and stop
o.setProperty('start',current_date) o.setProperty('start',current_date)
......
...@@ -4,7 +4,6 @@ ...@@ -4,7 +4,6 @@
from Products.ERP5Type.Message import translateString from Products.ERP5Type.Message import translateString
from Products.ERP5Type.Document import newTempBase from Products.ERP5Type.Document import newTempBase
from Products.PythonScripts.standard import url_quote from Products.PythonScripts.standard import url_quote
from string import zfill
portal = context.getPortalObject() portal = context.getPortalObject()
request = context.REQUEST request = context.REQUEST
...@@ -39,7 +38,7 @@ if depth == 0: ...@@ -39,7 +38,7 @@ if depth == 0:
# This case show Seven days # This case show Seven days
while current_date < bound_stop: while current_date < bound_stop:
# Create one Temp Object # Create one Temp Object
o = newTempBase(portal, id='week', uid='new_%s' % zfill('week',4)) o = newTempBase(portal, id='week', uid='new_week')
# Setting Axis Dates start and stop # Setting Axis Dates start and stop
o.setProperty('start',current_date) o.setProperty('start',current_date)
o.setProperty('stop', current_date+1) o.setProperty('stop', current_date+1)
......
...@@ -4,7 +4,6 @@ ...@@ -4,7 +4,6 @@
from Products.ERP5Type.Message import translateString from Products.ERP5Type.Message import translateString
from Products.ERP5Type.Document import newTempBase from Products.ERP5Type.Document import newTempBase
from Products.PythonScripts.standard import url_quote from Products.PythonScripts.standard import url_quote
from string import zfill
portal = context.getPortalObject() portal = context.getPortalObject()
request = context.REQUEST request = context.REQUEST
...@@ -27,7 +26,7 @@ if depth == 0: ...@@ -27,7 +26,7 @@ if depth == 0:
count = 0 count = 0
while count < 12: while count < 12:
# Create one Temp Object # Create one Temp Object
o = newTempBase(portal, id='year', uid='new_%s' % zfill('year',4)) o = newTempBase(portal, id='year', uid='new_year')
# Setting delimiter # Setting delimiter
if current_date.month() in [1, 7]: if current_date.month() in [1, 7]:
o.setProperty('delimiter_type', 1) o.setProperty('delimiter_type', 1)
......
...@@ -189,7 +189,7 @@ for table_name in spreadsheet_list.keys(): ...@@ -189,7 +189,7 @@ for table_name in spreadsheet_list.keys():
# we should try to use other line data to get a safe id. # we should try to use other line data to get a safe id.
if cell_id == '' and property_id.startswith('path_'): if cell_id == '' and property_id.startswith('path_'):
for alt_id_source in ['id', 'title']: for alt_id_source in ['id', 'title']:
if line_data.has_key(alt_id_source): if alt_id_source in line_data:
cell_id = getIDFromString(line_data[alt_id_source]) cell_id = getIDFromString(line_data[alt_id_source])
if cell_id not in ('', None): if cell_id not in ('', None):
break break
......
if context.REQUEST.has_key('workflow_action'): # We are on a workflow transition if 'workflow_action' in context.REQUEST: # We are on a workflow transition
help_relative_url = '%s#%s' % (getattr(getattr(context, form_id), 'form_action'),context.REQUEST['workflow_action']) help_relative_url = '%s#%s' % (getattr(getattr(context, form_id), 'form_action'),context.REQUEST['workflow_action'])
elif action is not None: elif action is not None:
help_relative_url = '%s#%s' % (context.getPortalTypeName(), action) help_relative_url = '%s#%s' % (context.getPortalTypeName(), action)
......
...@@ -13,7 +13,7 @@ for item in item_list: ...@@ -13,7 +13,7 @@ for item in item_list:
item_key = '/'.join(item_split[:split_depth]) item_key = '/'.join(item_split[:split_depth])
base_category = item_split[0] base_category = item_split[0]
# Create a new subfield if necessary # Create a new subfield if necessary
if not sub_field_dict.has_key(item_key): if item_key not in sub_field_dict:
# Create property dict (key are field parameters) # Create property dict (key are field parameters)
sub_field_property_dict = default_sub_field_property_dict.copy() sub_field_property_dict = default_sub_field_property_dict.copy()
sub_field_property_dict['key'] = item_key sub_field_property_dict['key'] = item_key
......
...@@ -23,7 +23,7 @@ for item in item_list: ...@@ -23,7 +23,7 @@ for item in item_list:
item_key = '/'.join(item_split[:split_depth]) item_key = '/'.join(item_split[:split_depth])
base_category = item_split[0] base_category = item_split[0]
# Create a new subfield if necessary # Create a new subfield if necessary
if not sub_field_dict.has_key(item_key): if item_key not in sub_field_dict:
# Create property dict (key are field parameters) # Create property dict (key are field parameters)
sub_field_property_dict = default_sub_field_property_dict.copy() sub_field_property_dict = default_sub_field_property_dict.copy()
sub_field_property_dict['key'] = item_key sub_field_property_dict['key'] = item_key
......
...@@ -33,7 +33,7 @@ section_item_list = getPreferredSectionItemList(portal_type, validation_state) ...@@ -33,7 +33,7 @@ section_item_list = getPreferredSectionItemList(portal_type, validation_state)
if base_category: if base_category:
section_item_list = section_item_list[::] # make a copy not to modify the cache value section_item_list = section_item_list[::] # make a copy not to modify the cache value
current_category = context.getProperty(base_category) current_category = context.getProperty(base_category)
if current_category and current_category not in zip(*section_item_list)[1]: if current_category and current_category not in list(zip(*section_item_list))[1]:
section_item_list.append( section_item_list.append(
(context.getProperty('%s_title' % base_category), (context.getProperty('%s_title' % base_category),
context.getProperty(base_category))) context.getProperty(base_category)))
......
...@@ -23,7 +23,7 @@ for history_name in history_name_list: ...@@ -23,7 +23,7 @@ for history_name in history_name_list:
history_element_title_list = [] history_element_title_list = []
for history_element_title in list_history_item[-1].keys(): for history_element_title in list_history_item[-1].keys():
if history_element_title <> history_name: if history_element_title != history_name:
new_title = history_element_title.replace('_', ' ').title() new_title = history_element_title.replace('_', ' ').title()
history_element_title_list.append(new_title) history_element_title_list.append(new_title)
...@@ -31,7 +31,7 @@ for history_name in history_name_list: ...@@ -31,7 +31,7 @@ for history_name in history_name_list:
for history_item in list_history_item: for history_item in list_history_item:
history_item_info = () history_item_info = ()
for history_element_title in list_history_item[-1].keys(): for history_element_title in list_history_item[-1].keys():
if history_element_title <> history_name: if history_element_title != history_name:
history_item_info += (history_item.get(history_element_title),) history_item_info += (history_item.get(history_element_title),)
history_item_list.append(history_item_info) history_item_list.append(history_item_info)
history_item_list.reverse() history_item_list.reverse()
......
...@@ -14,7 +14,7 @@ for workflow_id in workflow_id_list: ...@@ -14,7 +14,7 @@ for workflow_id in workflow_id_list:
for state in workflow.getStateValueList(): for state in workflow.getStateValueList():
state_reference = state.getReference() state_reference = state.getReference()
if state.getTitle() and state_reference != 'deleted': if state.getTitle() and state_reference != 'deleted':
if not state_dict.has_key(state_reference): if state_reference not in state_dict:
# we hide states without titles # we hide states without titles
item_list.append((state.getTitle(), state_reference)) item_list.append((state.getTitle(), state_reference))
state_dict[state_reference] = None state_dict[state_reference] = None
......
import six
from AccessControl import getSecurityManager from AccessControl import getSecurityManager
from zExceptions import Unauthorized from zExceptions import Unauthorized
from Products.ERP5Type.Document import newTempBase from Products.ERP5Type.Document import newTempBase
...@@ -10,9 +11,9 @@ if not getSecurityManager().getUser().has_permission('View History', context): ...@@ -10,9 +11,9 @@ if not getSecurityManager().getUser().has_permission('View History', context):
def beautifyChange(change_dict): def beautifyChange(change_dict):
change_list = [] change_list = []
for property_name, property_value in sorted(change_dict.items()): for property_name, property_value in sorted(change_dict.items()):
if isinstance(property_value, basestring): if isinstance(property_value, six.binary_type):
try: try:
unicode(property_value, 'utf-8') property_value.decode('utf-8')
except UnicodeDecodeError: except UnicodeDecodeError:
property_value = '(binary)' property_value = '(binary)'
change_list.append('%s:%s' % (property_name, property_value)) change_list.append('%s:%s' % (property_name, property_value))
......
...@@ -14,8 +14,8 @@ if from_cat is not None and to_cat is not None: ...@@ -14,8 +14,8 @@ if from_cat is not None and to_cat is not None:
new_category_list += (cat,) new_category_list += (cat,)
if has_changed == 1: if has_changed == 1:
o.setCategoryList(new_category_list) o.setCategoryList(new_category_list)
print "changed category %s with %s on %s" % (str(from_cat),str(to_cat),str(o.getPath())) print("changed category %s with %s on %s" % (str(from_cat),str(to_cat),str(o.getPath())))
print " " print(" ")
return printed return printed
...@@ -43,7 +43,7 @@ erp5_role_dict = { ...@@ -43,7 +43,7 @@ erp5_role_dict = {
erp5_permission_dict = {} erp5_permission_dict = {}
for role,permission_list in erp5_role_dict.items(): for role,permission_list in erp5_role_dict.items():
for permission in permission_list: for permission in permission_list:
if not erp5_permission_dict.has_key(permission): if permission not in erp5_permission_dict:
erp5_permission_dict[permission] = [] erp5_permission_dict[permission] = []
erp5_permission_dict[permission].append(role) erp5_permission_dict[permission].append(role)
......
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
containing searched words as well highlighting the searched containing searched words as well highlighting the searched
words in the text itself. words in the text itself.
""" """
import six
from erp5.component.document.Document import NotConvertedError from erp5.component.document.Document import NotConvertedError
encoding = 'utf-8' encoding = 'utf-8'
...@@ -27,7 +28,7 @@ if document_text is None: ...@@ -27,7 +28,7 @@ if document_text is None:
try: try:
# if SearchableText is joinned as it is, we use it for better performance. # if SearchableText is joinned as it is, we use it for better performance.
document_text = getattr(context, 'SearchableText', None) document_text = getattr(context, 'SearchableText', None)
if not isinstance(document_text, (str, unicode)): if not isinstance(document_text, six.string_types):
document_text = context.getSearchableText() document_text = context.getSearchableText()
except NotConvertedError: except NotConvertedError:
return context.Base_translateString("This document is not converted yet.") return context.Base_translateString("This document is not converted yet.")
......
from past.builtins import cmp
def generic_sort(a,b): def generic_sort(a,b):
result = 0 result = 0
for k,v in sort_order: for k,v in sort_order:
......
from string import zfill
request = context.REQUEST request = context.REQUEST
if kw.get('update', False): if kw.get('update', False):
...@@ -13,10 +12,10 @@ for k in kw.keys(): ...@@ -13,10 +12,10 @@ for k in kw.keys():
if v is not None: if v is not None:
i = 1 i = 1
for line in v: for line in v:
if line.has_key(listbox_key): if listbox_key in line:
key = '%s' % line[listbox_key] key = '%s' % line[listbox_key]
else: else:
key = str(zfill(i,3)) key = '%03d' % i
listbox[key] = line listbox[key] = line
i+=1 i+=1
request.set(k,listbox) request.set(k,listbox)
......
from six import string_types as basestring
portal = context.getPortalObject() portal = context.getPortalObject()
get = portal.REQUEST.get get = portal.REQUEST.get
selection_name = get('list_selection_name') selection_name = get('list_selection_name')
......
return request.has_key('Base_showUpdateDialog') or value return 'Base_showUpdateDialog' in request or value
...@@ -176,7 +176,7 @@ try: ...@@ -176,7 +176,7 @@ try:
request.set('default_module', my_field.get_value('default_module')) request.set('default_module', my_field.get_value('default_module'))
request.set('portal_type', portal_type[0]) request.set('portal_type', portal_type[0])
return o.Base_viewCreateRelationDialog( REQUEST=request ) return o.Base_viewCreateRelationDialog( REQUEST=request )
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
......
...@@ -11,7 +11,7 @@ if 1: # keep indentation ...@@ -11,7 +11,7 @@ if 1: # keep indentation
**kw) **kw)
except WorkflowException: except WorkflowException:
pass pass
except ValidationFailed, message: except ValidationFailed as message:
if getattr(message, 'msg', None) and same_type(message.msg, []): if getattr(message, 'msg', None) and same_type(message.msg, []):
message = '. '.join('%s' % x for x in message.msg) message = '. '.join('%s' % x for x in message.msg)
if not batch : if not batch :
......
...@@ -114,7 +114,7 @@ for skin_folder_id in skin_id_list: ...@@ -114,7 +114,7 @@ for skin_folder_id in skin_id_list:
form_id = form.getId() form_id = form.getId()
form_path = '%s/%s' % (skin_folder_id, form_id) form_path = '%s/%s' % (skin_folder_id, form_id)
if modified_object_dict.has_key(form_path): if form_path in modified_object_dict:
# The form is a Field Library # The form is a Field Library
if modified_object_dict[form_path] == '4_delete_form': if modified_object_dict[form_path] == '4_delete_form':
# As the form will be deleted, no need to manage its fields # As the form will be deleted, no need to manage its fields
......
...@@ -45,7 +45,7 @@ for cat_info in cat_info_list: ...@@ -45,7 +45,7 @@ for cat_info in cat_info_list:
for cat in cat_list: for cat in cat_list:
path_cell_list = [''] * (max_cat_depth - 1) path_cell_list = [''] * (max_cat_depth - 1)
path_cell_list[len(cat.getRelativeUrl().split('/')) - 2] = '*' path_cell_list[len(cat.getRelativeUrl().split('/')) - 2] = '*'
category_property_list = map(cat.getProperty, editable_property_id_list) category_property_list = list(map(cat.getProperty, editable_property_id_list))
row_list.append({ row_list.append({
'path_cell_list': path_cell_list, 'path_cell_list': path_cell_list,
'category_property_list': category_property_list, 'category_property_list': category_property_list,
......
from Products.ERP5Type.Message import translateString from Products.ERP5Type.Message import translateString
from Products.ERP5Type.Document import newTempBase from Products.ERP5Type.Document import newTempBase
import six
# XXX: allow simulation_mode without detailed_report ? # XXX: allow simulation_mode without detailed_report ?
detailed_report |= simulation_mode detailed_report |= simulation_mode
...@@ -61,7 +62,7 @@ if detailed_report_result: ...@@ -61,7 +62,7 @@ if detailed_report_result:
REQUEST.RESPONSE.setStatus(200, 'OK', lock=True) REQUEST.RESPONSE.setStatus(200, 'OK', lock=True)
raise Exception('Spreadsheet contains errors') raise Exception('Spreadsheet contains errors')
for base_category, category_list in category_list_spreadsheet_dict.iteritems(): for base_category, category_list in six.iteritems(category_list_spreadsheet_dict):
total_category_counter += len(category_list) total_category_counter += len(category_list)
category_path_set = set() category_path_set = set()
for category in category_list: for category in category_list:
...@@ -108,7 +109,7 @@ for base_category, category_list in category_list_spreadsheet_dict.iteritems(): ...@@ -108,7 +109,7 @@ for base_category, category_list in category_list_spreadsheet_dict.iteritems():
category_path_set.add(category_value.getRelativeUrl()) category_path_set.add(category_value.getRelativeUrl())
category_update_dict = {} category_update_dict = {}
for key, value in category.iteritems(): for key, value in six.iteritems(category):
if not create_local_property and key not in category_type_property_id_set: if not create_local_property and key not in category_type_property_id_set:
report( report(
field_type='Update', field_type='Update',
......
...@@ -18,6 +18,7 @@ From document pointed to by 'relative_url': ...@@ -18,6 +18,7 @@ From document pointed to by 'relative_url':
For the portal, 'relative_url' must be false and only module objects are For the portal, 'relative_url' must be false and only module objects are
considered if id_list is None. considered if id_list is None.
""" """
from six.moves import xrange
document = context.getPortalObject() document = context.getPortalObject()
context = document.portal_activities context = document.portal_activities
if relative_url: if relative_url:
......
...@@ -7,6 +7,7 @@ as first element or not (just like category tool API) ...@@ -7,6 +7,7 @@ as first element or not (just like category tool API)
The state titles will be translated unless you pass translate=False The state titles will be translated unless you pass translate=False
''' '''
from six import string_types as basestring
if translate: if translate:
from Products.ERP5Type.Message import translateString from Products.ERP5Type.Message import translateString
else: else:
......
...@@ -18,7 +18,7 @@ inventory_tag = base_tag + 'inventory' ...@@ -18,7 +18,7 @@ inventory_tag = base_tag + 'inventory'
last_inventory_tag = base_tag + 'last_inventory_activity' last_inventory_tag = base_tag + 'last_inventory_activity'
def reindex(document_list, tag, after_tag): def reindex(document_list, tag, after_tag):
for document in document_list: for document in document_list:
print '#### Indexing', document.id, '####' print('#### Indexing', document.id, '####')
document.activate( document.activate(
priority=additional_priority, priority=additional_priority,
tag=tag, tag=tag,
...@@ -37,7 +37,7 @@ def reindex(document_list, tag, after_tag): ...@@ -37,7 +37,7 @@ def reindex(document_list, tag, after_tag):
# security_uid explosion if many users (ex: persons) have local roles on # security_uid explosion if many users (ex: persons) have local roles on
# documents (ex: persons) granting them View permission but the user is not # documents (ex: persons) granting them View permission but the user is not
# indexed before corresponding document is. # indexed before corresponding document is.
print "#### Indexing person_module, stage 1 ####" print("#### Indexing person_module, stage 1 ####")
person_module = getattr(portal, 'person_module', None) person_module = getattr(portal, 'person_module', None)
if person_module is not None: if person_module is not None:
person_module.recurseCallMethod( person_module.recurseCallMethod(
...@@ -51,30 +51,30 @@ if person_module is not None: ...@@ -51,30 +51,30 @@ if person_module is not None:
}, },
max_depth=1, # Do not reindex Person's subobjects max_depth=1, # Do not reindex Person's subobjects
) )
print "#### Indexing translations ####" print("#### Indexing translations ####")
portal.ERP5Site_updateTranslationTable(sql_catalog_id=sql_catalog_id) portal.ERP5Site_updateTranslationTable(sql_catalog_id=sql_catalog_id)
print reindex( print(reindex(
[portal.portal_categories], [portal.portal_categories],
tag=category_tag, tag=category_tag,
after_tag=user_tag, after_tag=user_tag,
), ))
print reindex( print(reindex(
[portal.portal_alarms, portal.portal_activities], [portal.portal_alarms, portal.portal_activities],
tag=document_tag, tag=document_tag,
after_tag=(user_tag, category_tag), after_tag=(user_tag, category_tag),
), ))
print reindex( print(reindex(
[portal.portal_preferences], [portal.portal_preferences],
tag=preference_tag, tag=preference_tag,
after_tag=(user_tag, category_tag), after_tag=(user_tag, category_tag),
), ))
# Simulation is needed to calculate tests (ie. related quantity) # Simulation is needed to calculate tests (ie. related quantity)
print reindex( print(reindex(
[portal.portal_simulation], [portal.portal_simulation],
tag=simulation_tag, tag=simulation_tag,
after_tag=(user_tag, category_tag, document_tag, preference_tag), after_tag=(user_tag, category_tag, document_tag, preference_tag),
), ))
print reindex( print(reindex(
[ [
x for x in portal.objectValues() x for x in portal.objectValues()
if x.getUid != portal.getUid and if x.getUid != portal.getUid and
...@@ -90,7 +90,7 @@ print reindex( ...@@ -90,7 +90,7 @@ print reindex(
], ],
tag=document_tag, tag=document_tag,
after_tag=(user_tag, category_tag, preference_tag), after_tag=(user_tag, category_tag, preference_tag),
), ))
# Then we index ERP5 Python Scripts and ERP5 Form - this is fundamentally broken and will go away, do not depend on it ! # Then we index ERP5 Python Scripts and ERP5 Form - this is fundamentally broken and will go away, do not depend on it !
skin_activate_kw = { skin_activate_kw = {
'tag': document_tag, 'tag': document_tag,
...@@ -100,14 +100,14 @@ skin_activate_kw = { ...@@ -100,14 +100,14 @@ skin_activate_kw = {
for _, obj in portal.portal_skins.ZopeFind(portal.portal_skins, obj_metatypes=('ERP5 Python Script', 'ERP5 Form', 'ERP5 Report'), search_sub=1): for _, obj in portal.portal_skins.ZopeFind(portal.portal_skins, obj_metatypes=('ERP5 Python Script', 'ERP5 Form', 'ERP5 Report'), search_sub=1):
obj.recursiveReindexObject(activate_kw=skin_activate_kw, obj.recursiveReindexObject(activate_kw=skin_activate_kw,
sql_catalog_id=sql_catalog_id) sql_catalog_id=sql_catalog_id)
print reindex( print(reindex(
[ [
x for x in portal.objectValues(("ERP5 Folder", )) x for x in portal.objectValues(("ERP5 Folder", ))
if 'inventory' in x.id if 'inventory' in x.id
], ],
tag=inventory_tag, tag=inventory_tag,
after_tag=(user_tag, category_tag, document_tag, preference_tag), after_tag=(user_tag, category_tag, document_tag, preference_tag),
), ))
portal.portal_activities.activate( portal.portal_activities.activate(
after_tag=(user_tag, category_tag, document_tag, preference_tag, inventory_tag, simulation_tag), after_tag=(user_tag, category_tag, document_tag, preference_tag, inventory_tag, simulation_tag),
......
...@@ -11,7 +11,7 @@ for error in error_list: ...@@ -11,7 +11,7 @@ for error in error_list:
# We count the number of each portal type # We count the number of each portal type
if error[1]=='portal_type': if error[1]=='portal_type':
portal_type = error[3] portal_type = error[3]
if nb_types.has_key(portal_type): if portal_type in nb_types:
nb_types[portal_type] = nb_types[portal_type] + 1 nb_types[portal_type] = nb_types[portal_type] + 1
else: else:
nb_types[portal_type] = 1 nb_types[portal_type] = 1
......
...@@ -24,5 +24,5 @@ for candidate in candidate_list: ...@@ -24,5 +24,5 @@ for candidate in candidate_list:
obj.reindexObject() obj.reindexObject()
reindex_count += 1 reindex_count += 1
print '%s object reindexed, %s object unindexed' % (reindex_count, unindex_count) print('%s object reindexed, %s object unindexed' % (reindex_count, unindex_count))
return printed return printed
from ZTUtils import make_query from ZTUtils import make_query
return make_query((item for item in http_parameter_list.items() if item[1] is not None)) return make_query((item for item in list(http_parameter_list.items()) if item[1] is not None))
...@@ -33,7 +33,7 @@ for portal_type in portal_type_list: ...@@ -33,7 +33,7 @@ for portal_type in portal_type_list:
state_reference = state.getReference() state_reference = state.getReference()
for lang in supported_languages: for lang in supported_languages:
key = (lang, portal_type.getId(), state_var, state_reference) key = (lang, portal_type.getId(), state_var, state_reference)
if not translated_keys.has_key(key): if key not in translated_keys:
translated_message = context.Localizer.erp5_ui.gettext(state_reference, lang=lang).encode('utf-8') translated_message = context.Localizer.erp5_ui.gettext(state_reference, lang=lang).encode('utf-8')
translated_keys[key] = None # mark as translated translated_keys[key] = None # mark as translated
object_list.append(dict(language=lang, message_context=state_var, portal_type=portal_type.getId(), original_message=state_reference, object_list.append(dict(language=lang, message_context=state_var, portal_type=portal_type.getId(), original_message=state_reference,
...@@ -48,7 +48,7 @@ for portal_type in portal_type_list: ...@@ -48,7 +48,7 @@ for portal_type in portal_type_list:
msg_id = state.getTitle() msg_id = state.getTitle()
translated_message = context.Localizer.erp5_ui.gettext(state.getTitle().decode('utf-8'), lang=lang).encode('utf-8') translated_message = context.Localizer.erp5_ui.gettext(state.getTitle().decode('utf-8'), lang=lang).encode('utf-8')
key = (lang, portal_type.getId(), state_var_title, state_reference, msg_id) key = (lang, portal_type.getId(), state_var_title, state_reference, msg_id)
if not translated_keys.has_key(key): if key not in translated_keys:
translated_keys[key] = None # mark as translated translated_keys[key] = None # mark as translated
object_list.append(dict(language=lang, message_context=state_var_title, portal_type=portal_type.getId(), original_message=state_reference, object_list.append(dict(language=lang, message_context=state_var_title, portal_type=portal_type.getId(), original_message=state_reference,
translated_message=translated_message)) translated_message=translated_message))
...@@ -64,12 +64,12 @@ for ptype in context.portal_types.objectValues(): ...@@ -64,12 +64,12 @@ for ptype in context.portal_types.objectValues():
if not portal_type: portal_type = ptype.id if not portal_type: portal_type = ptype.id
for lang in supported_languages: for lang in supported_languages:
key = (lang, 'portal_type', portal_type) key = (lang, 'portal_type', portal_type)
if not translated_keys.has_key(key): if key not in translated_keys:
translated_keys[key] = None # mark as translated translated_keys[key] = None # mark as translated
object_list.append(dict(language=lang, message_context='portal_type', portal_type=portal_type, original_message=portal_type, object_list.append(dict(language=lang, message_context='portal_type', portal_type=portal_type, original_message=portal_type,
translated_message=context.Localizer.erp5_ui.gettext(portal_type, lang=lang).encode('utf-8'))) translated_message=context.Localizer.erp5_ui.gettext(portal_type, lang=lang).encode('utf-8')))
if object_list: if object_list:
catalog_translation_list(object_list) catalog_translation_list(object_list)
print 'Done' print('Done')
return printed return printed
import six
portal = context.getPortalObject() portal = context.getPortalObject()
getWorkflowValueListFor = portal.portal_workflow.getWorkflowValueListFor getWorkflowValueListFor = portal.portal_workflow.getWorkflowValueListFor
translateString = portal.Base_translateString translateString = portal.Base_translateString
...@@ -47,7 +48,7 @@ for line in context.searchFolder(group_by=column_list, select_dict=select_dict, ...@@ -47,7 +48,7 @@ for line in context.searchFolder(group_by=column_list, select_dict=select_dict,
state_count_dict[state] = count + state_count_dict[state] state_count_dict[state] = count + state_count_dict[state]
listbox = [] listbox = []
append = listbox.append append = listbox.append
for (portal_type, workflow), state_count_dict in sorted(type_workflow_state_count_dict_dict.iteritems(), key=lambda x: x[0]): for (portal_type, workflow), state_count_dict in sorted(six.iteritems(type_workflow_state_count_dict_dict), key=lambda x: x[0]):
if sum(state_count_dict.values()): if sum(state_count_dict.values()):
append({ append({
'translated_portal_type': '%s - %s' % (portal_type_translated_title_dict[portal_type], workflow_translated_title_dict[workflow]), 'translated_portal_type': '%s - %s' % (portal_type_translated_title_dict[portal_type], workflow_translated_title_dict[workflow]),
...@@ -55,7 +56,7 @@ for (portal_type, workflow), state_count_dict in sorted(type_workflow_state_coun ...@@ -55,7 +56,7 @@ for (portal_type, workflow), state_count_dict in sorted(type_workflow_state_coun
'count' : '', 'count' : '',
}) })
translated_state_title_dict = workflow_translated_state_title_dict[workflow] translated_state_title_dict = workflow_translated_state_title_dict[workflow]
for state, count in sorted(state_count_dict.iteritems(), key=lambda x: x[0]): for state, count in sorted(six.iteritems(state_count_dict), key=lambda x: x[0]):
if count: if count:
append({ append({
'translated_portal_type': '', 'translated_portal_type': '',
......
from six.moves import xrange
from Products.Formulator.Errors import FormValidationError from Products.Formulator.Errors import FormValidationError
from Products.ERP5Type.Message import translateString from Products.ERP5Type.Message import translateString
portal = context.getPortalObject() portal = context.getPortalObject()
...@@ -18,7 +19,7 @@ for form in (real_form, target_form): ...@@ -18,7 +19,7 @@ for form in (real_form, target_form):
request.set('editable_mode', 1) request.set('editable_mode', 1)
form.validate_all_to_request(request) form.validate_all_to_request(request)
request.set('editable_mode', editable_mode) request.set('editable_mode', editable_mode)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
......
from Products.ERP5Type.Document import newTempBase from Products.ERP5Type.Document import newTempBase
from string import zfill
if listbox_id is None: if listbox_id is None:
listbox_id = 'listbox' listbox_id = 'listbox'
request = context.REQUEST request = context.REQUEST
# It must be possible to initialise the fast input, and to add empty lines after # It must be possible to initialise the fast input, and to add empty lines after
if request.has_key('my_empty_line_number'): if 'my_empty_line_number' in request:
empty_line_number = request['my_empty_line_number'] empty_line_number = request['my_empty_line_number']
...@@ -28,7 +27,7 @@ if hasattr(request, listbox_id): ...@@ -28,7 +27,7 @@ if hasattr(request, listbox_id):
for i in keys_list: for i in keys_list:
o = newTempBase(portal_object, i) o = newTempBase(portal_object, i)
o.setUid('new_%s' % zfill(i,int_len)) o.setUid('new_%s' % str(i).zfill(int_len))
is_empty = 1 is_empty = 1
...@@ -37,7 +36,7 @@ if hasattr(request, listbox_id): ...@@ -37,7 +36,7 @@ if hasattr(request, listbox_id):
# 0 was added because of checkbox field in some fast input # 0 was added because of checkbox field in some fast input
if (value not in ['',None,0]) and (key != listbox_key): if (value not in ['',None,0]) and (key != listbox_key):
is_empty = 0 is_empty = 0
if (request.has_key('field_errors')): if ('field_errors' in request):
is_empty = 0 is_empty = 0
#o.edit(key=listbox[i][key]) #o.edit(key=listbox[i][key])
o.setProperty(key,listbox[i][key]) o.setProperty(key,listbox[i][key])
...@@ -46,11 +45,11 @@ if hasattr(request, listbox_id): ...@@ -46,11 +45,11 @@ if hasattr(request, listbox_id):
l.append(o) l.append(o)
# add empty lines # add empty lines
if not(request.has_key('field_errors')): if not('field_errors' in request):
for i in range(first_empty_line_id,first_empty_line_id+empty_line_number): for i in range(first_empty_line_id,first_empty_line_id+empty_line_number):
o = newTempBase(portal_object, str(i)) o = newTempBase(portal_object, str(i))
o.setUid('new_%s' % zfill(i,int_len)) o.setUid('new_%s' % str(i).zfill(int_len))
# zfill is used here to garantee sort order - XXX - cleaner approach required # zfill is used here to garantee sort order - XXX - cleaner approach required
l.append(o) l.append(o)
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment