From 60ba33eb3160cd4a2e78e1be664e22a1125a507f Mon Sep 17 00:00:00 2001
From: Yann Leboulanger <asterix@lagaule.org>
Date: Wed, 3 Dec 2008 17:38:16 +0000
Subject: [PATCH] [thorstenp] fix possible undefined loop variables

---
 src/chat_control.py              |  8 ++----
 src/common/connection.py         | 48 +++++++++++++++++---------------
 src/common/helpers.py            | 36 ++++++++++--------------
 src/common/xmpp/dispatcher_nb.py | 13 ++++-----
 src/conversation_textview.py     | 13 ++++-----
 src/htmltextview.py              | 14 ++++------
 src/profile_window.py            |  4 +--
 src/roster_window.py             | 14 +++++-----
 src/tooltips.py                  | 10 +++----
 9 files changed, 71 insertions(+), 89 deletions(-)

diff --git a/src/chat_control.py b/src/chat_control.py
index 81ceb09439..43be06a909 100644
--- a/src/chat_control.py
+++ b/src/chat_control.py
@@ -400,14 +400,12 @@ class ChatControlBase(MessageControl):
 
 	def disconnect_style_event(self, widget):
 		# Try to find the event_id
-		found = False
-		for id_ in self.handlers:
+		for id_ in self.handlers.keys():
 			if self.handlers[id_] == widget:
-				found = True
+				widget.disconnect(id_)
+				del self.handlers[id_]
 				break
 		if found:
-			widget.disconnect(id_)
-			del self.handlers[id_]
 
 	def connect_style_event(self, widget, set_fg = False, set_bg = False):
 		self.disconnect_style_event(widget)
diff --git a/src/common/connection.py b/src/common/connection.py
index 94a2da3778..9aa9aa3bc2 100644
--- a/src/common/connection.py
+++ b/src/common/connection.py
@@ -35,6 +35,7 @@
 import os
 import random
 import socket
+import operator
 
 import time
 import locale
@@ -379,29 +380,30 @@ class Connection(ConnectionHandlers):
 				self.dispatch('STANZA_SENT', unicode(data))
 
 	def _select_next_host(self, hosts):
-		'''Chooses best 'real' host basing on the SRV priority and weight data;
-		more info in RFC2782'''
-		hosts_best_prio = []
-		best_prio = 65535
-		sum_weight = 0
-		for h in hosts:
-			if h['prio'] < best_prio:
-				hosts_best_prio = [h]
-				best_prio = h['prio']
-				sum_weight = h['weight']
-			elif h['prio'] == best_prio:
-				hosts_best_prio.append(h)
-				sum_weight += h['weight']
-		if len(hosts_best_prio) == 1:
-			return hosts_best_prio[0]
-		r = random.randint(0, sum_weight)
-		min_w = sum_weight
-		# We return the one for which has the minimum weight and weight >= r
-		for h in hosts_best_prio:
-			if h['weight'] >= r:
-				if h['weight'] <= min_w:
-					min_w = h['weight']
-		return h
+		'''Selects the next host according to RFC2782 p.3 based on it's
+		priority. Chooses between hosts with the same priority randomly,
+		where the probability of being selected is proportional to the weight
+		of the host.'''
+
+		hosts_by_prio = sorted(hosts, key=operator.itemgetter('prio'))
+
+		try:
+			lowest_prio = hosts_by_prio[0]['prio']
+		except IndexError:
+			raise ValueError("No hosts to choose from!")
+
+		hosts_lowest_prio = [h for h in hosts_by_prio if h['prio'] == lowest_prio]
+
+		if len(hosts_lowest_prio) == 1:
+			return hosts_lowest_prio[0]
+		else:
+			rndint = random.randint(0, sum(h['weight'] for h in hosts_lowest_prio))
+			weightsum = 0
+			for host in sorted(hosts_lowest_prio, key=operator.itemgetter(
+			'weight')):
+				weightsum += host['weight']
+				if weightsum >= rndint:
+					return host
 
 	def connect(self, data = None):
 		''' Start a connection to the Jabber server.
diff --git a/src/common/helpers.py b/src/common/helpers.py
index 5f3e8edd38..ba11c11e5d 100644
--- a/src/common/helpers.py
+++ b/src/common/helpers.py
@@ -410,30 +410,22 @@ def get_uf_chatstate(chatstate):
 		return _('has closed the chat window or tab')
 	return ''
 
-def is_in_path(name_of_command, return_abs_path = False):
-	# if return_abs_path is True absolute path will be returned
-	# for name_of_command
-	# on failures False is returned
-	is_in_dir = False
-	found_in_which_dir = None
-	path = os.getenv('PATH').split(os.pathsep)
-	for path_to_directory in path:
+def is_in_path(command, return_abs_path=False):
+	'''Returns True if 'command' is found in one of the directories in the
+		user's path. If 'return_abs_path' is True, returns the absolute path of
+		the first found command instead. Returns False otherwise and on errors.'''
+
+	for directory in os.getenv('PATH').split(os.pathsep):
 		try:
-			contents = os.listdir(path_to_directory)
-		except OSError: # user can have something in PATH that is not a dir
+			if command in os.listdir(directory):
+				if return_abs_path:
+					return os.path.join(directory, command)
+				else:
+					return True
+		except OSError:
+			# If the user has non directories in his path
 			pass
-		else:
-			is_in_dir = name_of_command in contents
-		if is_in_dir:
-			if return_abs_path:
-				found_in_which_dir = path_to_directory
-			break
-
-	if found_in_which_dir:
-		abs_path = os.path.join(path_to_directory, name_of_command)
-		return abs_path
-	else:
-		return is_in_dir
+	return False
 
 def exec_command(command):
 	subprocess.Popen(command, shell = True)
diff --git a/src/common/xmpp/dispatcher_nb.py b/src/common/xmpp/dispatcher_nb.py
index 5c7cc84f5d..c5f0fe90aa 100644
--- a/src/common/xmpp/dispatcher_nb.py
+++ b/src/common/xmpp/dispatcher_nb.py
@@ -227,14 +227,11 @@ class Dispatcher(PlugIn):
 		if typ+ns not in self.handlers[xmlns][name]: 
 			return
 		for pack in self.handlers[xmlns][name][typ+ns]:
-			if handler==pack['func']: 
-				break
-		else: 
-			pack=None
-		try: 
-			self.handlers[xmlns][name][typ+ns].remove(pack)
-		except ValueError: 
-			pass
+			if pack['func'] == handler: 
+				try: 
+					self.handlers[xmlns][name][typ+ns].remove(pack)
+				except ValueError: 
+					pass
 
 	def RegisterDefaultHandler(self,handler):
 		''' Specify the handler that will be used if no NodeProcessed exception were raised.
diff --git a/src/conversation_textview.py b/src/conversation_textview.py
index 6713976381..b3eadd50f2 100644
--- a/src/conversation_textview.py
+++ b/src/conversation_textview.py
@@ -211,7 +211,7 @@ class ConversationTextview:
 
 
 		self.account = account
-		self.change_cursor = None
+		self.change_cursor = False
 		self.last_time_printout = 0
 
 		font = pango.FontDescription(gajim.config.get('conversation_font'))
@@ -618,7 +618,7 @@ class ConversationTextview:
 		if self.change_cursor:
 			self.tv.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(
 				gtk.gdk.Cursor(gtk.gdk.XTERM))
-			self.change_cursor = None
+			self.change_cursor = False
 		tag_table = self.tv.get_buffer().get_tag_table()
 		over_line = False
 		xep0184_warning = False
@@ -627,7 +627,7 @@ class ConversationTextview:
 			tag_table.lookup('xmpp'), tag_table.lookup('sth_at_sth')):
 				self.tv.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(
 					gtk.gdk.Cursor(gtk.gdk.HAND2))
-				self.change_cursor = tag
+				self.change_cursor = True
 			elif tag == tag_table.lookup('focus-out-line'):
 				over_line = True
 			elif tag == tag_table.lookup('xep0184-warning'):
@@ -642,14 +642,13 @@ class ConversationTextview:
 				self.show_line_tooltip)
 			self.tv.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(
 				gtk.gdk.Cursor(gtk.gdk.LEFT_PTR))
-			self.change_cursor = tag
+			self.change_cursor = True
 		if xep0184_warning and not self.xep0184_warning_tooltip.win:
-			self.xep0184_warning_tooltip.timeout = \
-				gobject.timeout_add(500,
+			self.xep0184_warning_tooltip.timeout = gobject.timeout_add(500,
 				self.show_xep0184_warning_tooltip)
 			self.tv.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(
 				gtk.gdk.Cursor(gtk.gdk.LEFT_PTR))
-			self.change_cursor = tag
+			self.change_cursor = True
 
 	def clear(self, tv = None):
 		'''clear text in the textview'''
diff --git a/src/htmltextview.py b/src/htmltextview.py
index cb0fc97a4f..6ea832d457 100644
--- a/src/htmltextview.py
+++ b/src/htmltextview.py
@@ -967,21 +967,17 @@ class HtmlTextView(gtk.TextView):
 		x, y, _ = widget.window.get_pointer()
 		x, y = widget.window_to_buffer_coords(gtk.TEXT_WINDOW_TEXT, x, y)
 		tags = widget.get_iter_at_location(x, y).get_tags()
-		is_over_anchor = False
-		for tag in tags:
-			if getattr(tag, 'is_anchor', False):
-				is_over_anchor = True
-				break
+		anchor_tags = [tag for tag in tags if getattr(tag, 'is_anchor', False)]
 		if self.tooltip.timeout != 0:
 			# Check if we should hide the line tooltip
-			if not is_over_anchor:
+			if not anchor_tags:
 				self.tooltip.hide_tooltip()
-		if not self._changed_cursor and is_over_anchor:
+		if not self._changed_cursor and anchor_tags:
 			window = widget.get_window(gtk.TEXT_WINDOW_TEXT)
 			window.set_cursor(gtk.gdk.Cursor(gtk.gdk.HAND2))
 			self._changed_cursor = True
-			self.tooltip.timeout = gobject.timeout_add(500, self.show_tooltip, tag)
-		elif self._changed_cursor and not is_over_anchor:
+			self.tooltip.timeout = gobject.timeout_add(500, self.show_tooltip, anchor_tags[0])
+		elif self._changed_cursor and not anchor_tags:
 			window = widget.get_window(gtk.TEXT_WINDOW_TEXT)
 			window.set_cursor(gtk.gdk.Cursor(gtk.gdk.XTERM))
 			self._changed_cursor = False
diff --git a/src/profile_window.py b/src/profile_window.py
index f90cc5edbb..e5235dfcf1 100644
--- a/src/profile_window.py
+++ b/src/profile_window.py
@@ -266,10 +266,8 @@ class ProfileWindow:
 			found = False
 			for e in loc[entries[0]]:
 				if entries[1] in e:
-					found = True
+					e[entries[2]] = txt
 					break
-			if found:
-				e[entries[2]] = txt
 			else:
 				loc[entries[0]].append({entries[1]: '', entries[2]: txt})
 			return vcard_
diff --git a/src/roster_window.py b/src/roster_window.py
index 6ef448acd4..f8fa2f66cf 100644
--- a/src/roster_window.py
+++ b/src/roster_window.py
@@ -2512,7 +2512,7 @@ class RosterWindow:
 				_('You must read them before removing this transport.'))
 			return
 		if len(list_) == 1:
-			pritext = _('Transport "%s" will be removed') % contact.jid
+			pritext = _('Transport "%s" will be removed') % list_[0][0].jid
 			sectext = _('You will no longer be able to send and receive messages '
 				'from contacts using this transport.')
 		else:
@@ -2564,12 +2564,12 @@ class RosterWindow:
 					'value' : group, 'child': [u'message', u'iq', u'presence-out']}
 				gajim.connections[account].blocked_list.append(new_rule)
 			for account in accounts:
-				gajim.connections[account].set_privacy_list(
-				'block', gajim.connections[account].blocked_list)
-			if len(gajim.connections[account].blocked_list) == 1:
-				gajim.connections[account].set_active_list('block')
-				gajim.connections[account].set_default_list('block')
-			gajim.connections[account].get_privacy_list('block')
+				connection = gajim.connections[account]
+				connection.set_privacy_list('block', connection.blocked_list)
+				if len(connection.blocked_list) == 1:
+					connection.set_active_list('block')
+					connection.set_default_list('block')
+				connection.get_privacy_list('block')
 
 		self.get_status_message('offline', on_continue)
 
diff --git a/src/tooltips.py b/src/tooltips.py
index c8fe0b51cd..d5f8d113e1 100644
--- a/src/tooltips.py
+++ b/src/tooltips.py
@@ -463,13 +463,13 @@ class RosterTooltip(NotificationAreaTooltip):
 			contact_keys = sorted(contacts_dict.keys())
 			contact_keys.reverse()
 			for priority in contact_keys:
-				for contact in contacts_dict[priority]:
-					status_line = self.get_status_info(contact.resource,
-						contact.priority, contact.show, contact.status)
+				for acontact in contacts_dict[priority]:
+					status_line = self.get_status_info(acontact.resource,
+						acontact.priority, acontact.show, acontact.status)
 					
-					icon_name = self._get_icon_name_for_tooltip(contact)
+					icon_name = self._get_icon_name_for_tooltip(acontact)
 					self.add_status_row(file_path, icon_name, status_line,
-						contact.last_status_time)
+						acontact.last_status_time)
 			properties.append((self.table,	None))
 
 		else: # only one resource
-- 
GitLab