Commit 91f2ac01 authored by Jérome Perrin's avatar Jérome Perrin

*: use key instead of cmp to sort

parent 16ff36f1
if not portal_type: if not portal_type:
portal_type = context.getPortalObject().getPortalAccountingMovementTypeList() portal_type = context.getPortalObject().getPortalAccountingMovementTypeList()
sort_dict = { 'income': 0, sort_dict = {
'bank': -3,
'income': 0,
'expense': -2, 'expense': -2,
'receivable': -2, 'receivable': -2,
'payable': 0, 'payable': 0,
'collected_vat': -1, 'collected_vat': -1,
'refundable_vat': -1 } 'refundable_vat': -1,
}
def getAccountingTransactionLineSortKey(line): def getAccountingTransactionLineSortKey(line):
return sort_dict.get(line.getId(), (line.getIntIndex() or line.getIntId() or 0)) return sort_dict.get(line.getId(), (line.getIntIndex() or line.getIntId() or 0))
......
...@@ -68,10 +68,7 @@ for person in person_value_list: ...@@ -68,10 +68,7 @@ for person in person_value_list:
total=person_total, total=person_total,
**result_dict)) **result_dict))
result_list.sort(lambda a,b: cmp( result_list.sort(key=lambda r: (r.person_career_reference or '', r.person_title or ''))
a.person_career_reference or a.person_title,
b.person_career_reference or b.person_title))
request.set('total_time', total_time) request.set('total_time', total_time)
request.set('total_time_per_resource', total_time_per_resource) request.set('total_time_per_resource', total_time_per_resource)
......
...@@ -553,12 +553,12 @@ class BusinessConfiguration(Item): ...@@ -553,12 +553,12 @@ class BusinessConfiguration(Item):
"immediateReindexObject"]) "immediateReindexObject"])
# build # build
configuration_save_list = self.contentValues(portal_type='Configuration Save') configuration_save_list = self.contentValues(portal_type='Configuration Save')
configuration_save_list.sort(lambda x, y: cmp(x.getIntIndex(x.getIntId()), configuration_save_list.sort(key=lambda x: (x.getIntIndex(x.getIntId()) or 0))
y.getIntIndex(y.getIntId())))
for configuration_save in configuration_save_list: for configuration_save in configuration_save_list:
# XXX: check which items are configure-able # XXX: check which items are configure-able
configuration_item_list = configuration_save.contentValues() configuration_item_list = configuration_save.contentValues()
configuration_item_list.sort(lambda x, y: cmp(x.getIntId(), y.getIntId())) configuration_item_list.sort(key=lambda x: (x.getIntId() or 0))
for configurator_item in configuration_item_list: for configurator_item in configuration_item_list:
configurator_item.activate(**kw).fixConsistency( configurator_item.activate(**kw).fixConsistency(
filter={"constraint_type":"configuration"}) filter={"constraint_type":"configuration"})
......
...@@ -16,6 +16,4 @@ for (x,y) in selection_param_list: ...@@ -16,6 +16,4 @@ for (x,y) in selection_param_list:
active_process_list = [(y,x) for (x,y) in active_process_dict.items()] active_process_list = [(y,x) for (x,y) in active_process_dict.items()]
active_process_list.sort(lambda x, y: cmp(x[1],y[1]), reverse=True ) return sorted(active_process_list, key=lambda item: item[1], reverse=True)
return active_process_list
...@@ -58,13 +58,7 @@ for inventory in portal.portal_simulation.getInventoryList( ...@@ -58,13 +58,7 @@ for inventory in portal.portal_simulation.getInventoryList(
request.set('total_price', total_price) request.set('total_price', total_price)
def sort_method(a, b): return sorted(
employee_career_reference_diff = cmp(a.employee_career_reference, object_list,
b.employee_career_reference) key=lambda o: (o.employee_career_reference or '', o.employee_title)
if employee_career_reference_diff: )
return employee_career_reference_diff
return cmp(a.employee_title, b.employee_title)
object_list.sort(sort_method)
return object_list
...@@ -38,10 +38,10 @@ inventory_param_dict = { ...@@ -38,10 +38,10 @@ inventory_param_dict = {
} }
employee_param_dict = inventory_param_dict.copy() employee_param_dict = inventory_param_dict.copy()
employee_param_dict['contribution_share_uid'] = context.portal_categories.contribution_share.employee.getUid() employee_param_dict['contribution_share_uid'] = portal.portal_categories.contribution_share.employee.getUid()
employer_param_dict = inventory_param_dict.copy() employer_param_dict = inventory_param_dict.copy()
employer_param_dict['contribution_share_uid'] = context.portal_categories.contribution_share.employer.getUid() employer_param_dict['contribution_share_uid'] = portal.portal_categories.contribution_share.employer.getUid()
if request.get('mirror_section'): if request.get('mirror_section'):
mirror_section = request['mirror_section'] mirror_section = request['mirror_section']
...@@ -112,21 +112,14 @@ request.set('base_total', base_total) ...@@ -112,21 +112,14 @@ request.set('base_total', base_total)
request.set('total', total) request.set('total', total)
sorted_inventory_list = []
sorted_inventory_list = inventory_list.values()
# sort by salary range, and add intermediate sums if needed # sort by salary range, and add intermediate sums if needed
def sort_method(a, b): sorted_inventory_list = sorted(
salary_range_diff = cmp(a.salary_range, b.salary_range) inventory_list.values(),
if salary_range_diff: key=lambda i: (
return salary_range_diff i.salary_range or '',
employee_career_reference_diff = cmp(a.employee_career_reference, i.employee_career_reference or '',
b.employee_career_reference) i.employee_title or '',
if employee_career_reference_diff: ))
return employee_career_reference_diff
return cmp(a.employee_title, b.employee_title)
sorted_inventory_list.sort(sort_method)
i = 0 i = 0
intermediate_base_total = 0 intermediate_base_total = 0
......
...@@ -120,38 +120,12 @@ for paysheet_line in paysheet_line_list: ...@@ -120,38 +120,12 @@ for paysheet_line in paysheet_line_list:
if 'no_slice' in object_dict: if 'no_slice' in object_dict:
line_list.append(paysheet_line.asContext(**object_dict['no_slice'])) line_list.append(paysheet_line.asContext(**object_dict['no_slice']))
reverse = False
sort_key = lambda l: (l.getIntIndex() or 0)
# sort results
def sortByTitleAscending(x, y):
return cmp(x.getTitle(), y.getTitle())
def sortByTitleDescending(x, y):
return cmp(y.getTitle(), x.getTitle())
def sortByIntIndexAscending(x, y):
return cmp(x.getIntIndex(), y.getIntIndex())
def sortByIntIndexDescending(x, y):
return cmp(y.getIntIndex(), x.getIntIndex())
sortByDefaultSortMethod = sortByIntIndexAscending
if 'sort_on' in kw: if 'sort_on' in kw:
sort_on = kw['sort_on'] sort_on = kw['sort_on']
if sort_on[0][0] == 'title' and sort_on[0][1]=='ascending': reverse = sort_on[0][1]=='descending'
line_list.sort(sortByTitleAscending) if sort_on[0][0] == 'title':
elif sort_on[0][0] == 'title' and sort_on[0][1]=='descending': sort_key = lambda l: (l.getTitle() or '')
line_list.sort(sortByTitleDescending)
elif sort_on[0][0] == 'int_index' and sort_on[0][1]=='ascending':
line_list.sort(sortByIntIndexAscending)
elif sort_on[0][0] == 'int_index' and sort_on[0][1]=='descending':
line_list.sort(sortByIntIndexDescending)
else:
line_list.sort(sortByDefaultSortMethod)
else:
line_list.sort(sortByDefaultSortMethod)
return line_list return sorted(line_list, key=sort_key, reverse=reverse)
...@@ -24,12 +24,6 @@ task_line_list = [] ...@@ -24,12 +24,6 @@ task_line_list = []
for task in task_list: for task in task_list:
task_line_list.extend(task.contentValues(portal_type='Task Line')) task_line_list.extend(task.contentValues(portal_type='Task Line'))
def sortTaskLine(a, b): return sorted(
result = cmp(a.getStartDate(), b.getStartDate()) task_line_list,
if result == 0: key=lambda tl: (tl.hasStartDate(), tl.getStartDate(), tl.getTitle()))
result = cmp(a.getTitle(), b.getTitle())
return result
task_line_list.sort(sortTaskLine)
return task_line_list
...@@ -40,12 +40,6 @@ for task in task_list: ...@@ -40,12 +40,6 @@ for task in task_list:
task_line_list.extend(task.objectValues(portal_type=('Task Line', 'Task Report Line'))) task_line_list.extend(task.objectValues(portal_type=('Task Line', 'Task Report Line')))
def sortTaskLine(a, b): return sorted(
result = cmp(a.getStartDate(), b.getStartDate()) task_line_list,
if result == 0: key=lambda tl: (tl.getStartDate() is not None, tl.getStartDate(), tl.getTitle()))
result = cmp(a.getTitle(), b.getTitle())
return result
task_line_list.sort(sortTaskLine)
return task_line_list
...@@ -57,8 +57,6 @@ if active_process_path: ...@@ -57,8 +57,6 @@ if active_process_path:
else: else:
raise ValueError("No active process found to process report") raise ValueError("No active process found to process report")
def sortProduct(a, b):
return cmp(a['product'], b['product'])
period_counter_dict = {} period_counter_dict = {}
line_list = [] line_list = []
...@@ -132,7 +130,7 @@ if len(client_dict): ...@@ -132,7 +130,7 @@ if len(client_dict):
product_lines_list.append(obj) product_lines_list.append(obj)
# sort product list # sort product list
product_lines_list.sort(sortProduct) product_lines_list.sort(key=lambda p: p['product'])
extend(product_lines_list) extend(product_lines_list)
else: else:
# products # products
...@@ -169,7 +167,8 @@ else: ...@@ -169,7 +167,8 @@ else:
period_counter_dict['total amount'] = line_total_amount period_counter_dict['total amount'] = line_total_amount
append(obj) append(obj)
line_list.sort(sortProduct) line_list.sort(key=lambda p: p['product'])
obj = Object(uid="new_") obj = Object(uid="new_")
obj["client"] = 'Total' obj["client"] = 'Total'
......
...@@ -335,7 +335,11 @@ class Category(Folder): ...@@ -335,7 +335,11 @@ class Category(Folder):
if not isinstance(local_sort_id, (tuple, list)): if not isinstance(local_sort_id, (tuple, list)):
local_sort_id = (local_sort_id, ) local_sort_id = (local_sort_id, )
def sort_key(c): def sort_key(c):
return [c.getProperty(sort_id, 0) for sort_id in local_sort_id] k = []
for sort_id in local_sort_id:
v = c.getProperty(sort_id)
k.extend([v is not None, v])
return k
local_sort_key = sort_key local_sort_key = sort_key
if local_sort_method: if local_sort_method:
warnings.warn( warnings.warn(
...@@ -894,7 +898,11 @@ class BaseCategory(Category): ...@@ -894,7 +898,11 @@ class BaseCategory(Category):
if not isinstance(local_sort_id, (tuple, list)): if not isinstance(local_sort_id, (tuple, list)):
local_sort_id = (local_sort_id, ) local_sort_id = (local_sort_id, )
def sort_key(c): def sort_key(c):
return [c.getProperty(sort_id, 0) for sort_id in local_sort_id] k = []
for sort_id in local_sort_id:
v = c.getProperty(sort_id)
k.extend([v is not None, v])
return k
local_sort_key = sort_key local_sort_key = sort_key
if local_sort_method: if local_sort_method:
warnings.warn( warnings.warn(
......
...@@ -149,7 +149,10 @@ class Renderer(Filter): ...@@ -149,7 +149,10 @@ class Renderer(Filter):
elif self.sort_key is not None: elif self.sort_key is not None:
value_list.sort(key=self.sort_key) value_list.sort(key=self.sort_key)
elif self.sort_id is not None: elif self.sort_id is not None:
value_list.sort(key=lambda x: x.getProperty(self.sort_id)) def sort_key(x):
k = x.getProperty(self.sort_id)
return (k is not None, k)
value_list.sort(key=sort_key)
# If base=1 but base_category is None, it is necessary to guess the base category # If base=1 but base_category is None, it is necessary to guess the base category
# by heuristic. # by heuristic.
......
...@@ -148,14 +148,7 @@ def getDocumentGroupByWorkflowStateList(self, form_id='', **kw): ...@@ -148,14 +148,7 @@ def getDocumentGroupByWorkflowStateList(self, form_id='', **kw):
workflow_state=current_workflow_state, workflow_state=current_workflow_state,
)) ))
# Let us sort this list by translated title of workflow state and workflow return sorted(document_list, key=lambda b: (b.workflow_title, b.translated_workflow_state_title))
def compareState(a, b):
return cmp((a.workflow_title, a.translated_workflow_state_title),
(b.workflow_title, b.translated_workflow_state_title))
document_list.sort(compareState)
# Return result
return document_list
......
from erp5.component.module.Log import log
# this script is no longer needed.
log('Category_getSortedCategoryChildValueList', 'use getCategoryChildValueList method')
value_list = [o for o in context.getCategoryChildValueList() if o.getRelativeUrl() != context.getRelativeUrl()]
sort_id='int_index'
value_list.sort(key=lambda x: x.getProperty(sort_id))
return value_list
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="PythonScript" module="Products.PythonScripts.PythonScript"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>_bind_names</string> </key>
<value>
<object>
<klass>
<global name="_reconstructor" module="copy_reg"/>
</klass>
<tuple>
<global name="NameAssignments" module="Shared.DC.Scripts.Bindings"/>
<global name="object" module="__builtin__"/>
<none/>
</tuple>
<state>
<dictionary>
<item>
<key> <string>_asgns</string> </key>
<value>
<dictionary>
<item>
<key> <string>name_container</string> </key>
<value> <string>container</string> </value>
</item>
<item>
<key> <string>name_context</string> </key>
<value> <string>context</string> </value>
</item>
<item>
<key> <string>name_m_self</string> </key>
<value> <string>script</string> </value>
</item>
<item>
<key> <string>name_subpath</string> </key>
<value> <string>traverse_subpath</string> </value>
</item>
</dictionary>
</value>
</item>
</dictionary>
</state>
</object>
</value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>**kw</string> </value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>Category_getSortedCategoryChildValueList</string> </value>
</item>
</dictionary>
</pickle>
</record>
</ZopeData>
...@@ -27,6 +27,7 @@ ...@@ -27,6 +27,7 @@
# #
############################################################################## ##############################################################################
import functools
from collections import defaultdict from collections import defaultdict
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type.Globals import InitializeClass from Products.ERP5Type.Globals import InitializeClass
...@@ -243,6 +244,9 @@ class DomainTool(BaseTool): ...@@ -243,6 +244,9 @@ class DomainTool(BaseTool):
if sort_key_method is not None: if sort_key_method is not None:
result_list.sort(key=sort_key_method) result_list.sort(key=sort_key_method)
elif sort_method is not None: elif sort_method is not None:
if six.PY3:
result_list.sort(key=functools.cmp_to_key(sort_method))
else:
result_list.sort(cmp=sort_method) result_list.sort(cmp=sort_method)
return result_list return result_list
......
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