Ejemplo n.º 1
0
    def __init__(self):
        """Initialize the task list."""

        self.tasklist = TaskList()
        self.legend = '\nLegend: Not Due  ' + Fore.CYAN + Style.BRIGHT + 'Upcoming  ' + Fore.BLUE + \
                      Style.BRIGHT + 'Due  ' + Fore.RED + Style.BRIGHT + 'Overdue  ' + Fore.WHITE + Style.BRIGHT + \
                      Back.WHITE + 'Completed' + Fore.RESET + Style.NORMAL + Back.RESET
Ejemplo n.º 2
0
def run(args):
	from manifest import Manifest
	manifest = Manifest(args.manifest)

	from tasklist import TaskList
	tasklist = TaskList()
	tasklist.load('resolve_tasks', manifest)

	from bootstrapinfo import BootstrapInformation
	bootstrap_info = BootstrapInformation(manifest=manifest, debug=args.debug)

	try:
		tasklist.run(info=bootstrap_info, dry_run=args.dry_run)
		log.info('Successfully completed bootstrapping')
	except (Exception, KeyboardInterrupt) as e:
		log.exception(e)
		if args.pause_on_error:
			raw_input("Press Enter to commence rollback")
		log.error('Rolling back')

		rollback_tasklist = TaskList()

		def counter_task(task, counter):
			if task in tasklist.tasks_completed and counter not in tasklist.tasks_completed:
				rollback_tasklist.tasks.add(counter)
		rollback_tasklist.load('resolve_rollback_tasks', manifest, counter_task)

		rollback_tasklist.run(info=bootstrap_info, dry_run=args.dry_run)
		log.info('Successfully completed rollback')
Ejemplo n.º 3
0
  def test_add_tasks_to_tasklist(self):
    tasklist = TaskList(self.tl, "task-inserter")
    tasklist.insert()
    self.failIf(not tasklist.exists())

    tl_id = tasklist.get_id()
    task = Task(self.task, tl_id)
    task.insert()
Ejemplo n.º 4
0
  def test_add_tasks_to_tasklist(self):
    #print ("adding tasks")
    tasklist = TaskList("task-inserter")
    tasklist.create()
    self.failIf(not tasklist.exists())

    tl_id = tasklist.get_id()
    task = Task(self.task, tl_id)
    task.create()
Ejemplo n.º 5
0
def run(opts):
	"""Runs the bootstrapping process

	Args:
		opts (dict): Dictionary of options from the commandline
	"""
	# Load the manifest
	from manifest import Manifest
	manifest = Manifest(opts['MANIFEST'])

	# Get the tasklist
	from tasklist import TaskList
	tasklist = TaskList()
	# 'resolve_tasks' is the name of the function to call on the provider and plugins
	tasklist.load('resolve_tasks', manifest)

	# Create the bootstrap information object that'll be used throughout the bootstrapping process
	from bootstrapinfo import BootstrapInformation
	bootstrap_info = BootstrapInformation(manifest=manifest, debug=opts['--debug'])

	try:
		# Run all the tasks the tasklist has gathered
		tasklist.run(info=bootstrap_info, dry_run=opts['--dry-run'])
		# We're done! :-)
		log.info('Successfully completed bootstrapping')
	except (Exception, KeyboardInterrupt) as e:
		# When an error occurs, log it and begin rollback
		log.exception(e)
		if opts['--pause-on-error']:
			# The --pause-on-error is useful when the user wants to inspect the volume before rollback
			raw_input('Press Enter to commence rollback')
		log.error('Rolling back')

		# Create a new tasklist to gather the necessary tasks for rollback
		rollback_tasklist = TaskList()

		# Create a useful little function for the provider and plugins to use,
		# when figuring out what tasks should be added to the rollback list.
		def counter_task(task, counter):
			"""counter_task() adds the second argument to the rollback tasklist
			if the first argument is present in the list of completed tasks

			Args:
				task (Task): The task to look for in the completed tasks list
				counter (Task): The task to add to the rollback tasklist
			"""
			if task in tasklist.tasks_completed and counter not in tasklist.tasks_completed:
				rollback_tasklist.tasks.add(counter)
		# Ask the provider and plugins for tasks they'd like to add to the rollback tasklist
		# Any additional arguments beyond the first two are passed directly to the provider and plugins
		rollback_tasklist.load('resolve_rollback_tasks', manifest, counter_task)

		# Run the rollback tasklist
		rollback_tasklist.run(info=bootstrap_info, dry_run=opts['--dry-run'])
		log.info('Successfully completed rollback')
		raise e
Ejemplo n.º 6
0
    def test_create_destroy(self):
        name = "test1"

        tl = TaskList(name, self.workingD)
        tl.save()

        assert os.path.exists(os.path.join(self.workingD, name + ".tsk"))

        tl.destroy()

        assert not os.path.exists(os.path.join(self.workingD, name + ".tsk"))
Ejemplo n.º 7
0
def run(manifest, debug=False, pause_on_error=False, dry_run=False):
    """Runs the bootstrapping process

    :params Manifest manifest: The manifest to run the bootstrapping process for
    :params bool debug: Whether to turn debugging mode on
    :params bool pause_on_error: Whether to pause on error, before rollback
    :params bool dry_run: Don't actually run the tasks
    """
    import logging

    log = logging.getLogger(__name__)
    # Get the tasklist
    from tasklist import load_tasks
    from tasklist import TaskList
    log.info('Generating tasklist')
    tasks = load_tasks('resolve_tasks', manifest)
    tasklist = TaskList(tasks)
    # 'resolve_tasks' is the name of the function to call on the provider and plugins

    # Create the bootstrap information object that'll be used throughout the bootstrapping process
    from bootstrapinfo import BootstrapInformation
    bootstrap_info = BootstrapInformation(manifest=manifest, debug=debug)

    try:
        # Run all the tasks the tasklist has gathered
        tasklist.run(info=bootstrap_info, dry_run=dry_run)
        # We're done! :-)
        log.info('Successfully completed bootstrapping')
    except (Exception, KeyboardInterrupt) as e:
        # When an error occurs, log it and begin rollback
        log.exception(e)
        if pause_on_error:
            # The --pause-on-error is useful when the user wants to inspect the volume before rollback
            raw_input('Press Enter to commence rollback')
        log.error('Rolling back')

        # Create a useful little function for the provider and plugins to use,
        # when figuring out what tasks should be added to the rollback list.
        def counter_task(taskset, task, counter):
            """counter_task() adds the third argument to the rollback tasklist
            if the second argument is present in the list of completed tasks

            :param set taskset: The taskset to add the rollback task to
            :param Task task: The task to look for in the completed tasks list
            :param Task counter: The task to add to the rollback tasklist
            """
            if task in tasklist.tasks_completed and counter not in tasklist.tasks_completed:
                taskset.add(counter)

        # Ask the provider and plugins for tasks they'd like to add to the rollback tasklist
        # Any additional arguments beyond the first two are passed directly to the provider and plugins
        rollback_tasks = load_tasks('resolve_rollback_tasks', manifest, tasklist.tasks_completed, counter_task)
        rollback_tasklist = TaskList(rollback_tasks)

        # Run the rollback tasklist
        rollback_tasklist.run(info=bootstrap_info, dry_run=dry_run)
        log.info('Successfully completed rollback')
        raise
    return bootstrap_info
Ejemplo n.º 8
0
	def __init__(self):
		"""Initialize the task list."""

		self.tasklist = TaskList()
		self.legend = '\nLegend: Not Due  ' + Fore.CYAN + Style.BRIGHT + 'Upcoming  ' + Fore.BLUE + \
		              Style.BRIGHT + 'Due  ' + Fore.RED + Style.BRIGHT + 'Overdue  ' + Fore.WHITE + Style.BRIGHT + \
		              Back.WHITE + 'Completed' + Fore.RESET + Style.NORMAL + Back.RESET
Ejemplo n.º 9
0
def run(opts):
    """Runs the bootstrapping process

	:params dict opts: Dictionary of options from the commandline
	"""
    # Load the manifest
    from manifest import Manifest
    manifest = Manifest(opts['MANIFEST'])

    # Get the tasklist
    from tasklist import load_tasks
    from tasklist import TaskList
    tasks = load_tasks('resolve_tasks', manifest)
    tasklist = TaskList(tasks)
    # 'resolve_tasks' is the name of the function to call on the provider and plugins

    # Create the bootstrap information object that'll be used throughout the bootstrapping process
    from bootstrapinfo import BootstrapInformation
    bootstrap_info = BootstrapInformation(manifest=manifest,
                                          debug=opts['--debug'])

    try:
        # Run all the tasks the tasklist has gathered
        tasklist.run(info=bootstrap_info, dry_run=opts['--dry-run'])
        # We're done! :-)
        log.info('Successfully completed bootstrapping')
    except (Exception, KeyboardInterrupt) as e:
        # When an error occurs, log it and begin rollback
        log.exception(e)
        if opts['--pause-on-error']:
            # The --pause-on-error is useful when the user wants to inspect the volume before rollback
            raw_input('Press Enter to commence rollback')
        log.error('Rolling back')

        # Create a useful little function for the provider and plugins to use,
        # when figuring out what tasks should be added to the rollback list.
        def counter_task(taskset, task, counter):
            """counter_task() adds the second argument to the rollback tasklist
			if the first argument is present in the list of completed tasks

			:param set taskset: The taskset to add the rollback task to
			:param Task task: The task to look for in the completed tasks list
			:param Task counter: The task to add to the rollback tasklist
			"""
            if task in tasklist.tasks_completed and counter not in tasklist.tasks_completed:
                taskset.add(counter)

        # Ask the provider and plugins for tasks they'd like to add to the rollback tasklist
        # Any additional arguments beyond the first two are passed directly to the provider and plugins
        rollback_tasks = load_tasks('resolve_rollback_tasks', manifest,
                                    tasklist.tasks_completed, counter_task)
        rollback_tasklist = TaskList(rollback_tasks)

        # Run the rollback tasklist
        rollback_tasklist.run(info=bootstrap_info, dry_run=opts['--dry-run'])
        log.info('Successfully completed rollback')
        raise e
Ejemplo n.º 10
0
    def __init__(self):
        """Initialize the task list and populate the dictionary for menu actions."""

        self.tasklist = TaskList()
        self.current_task = ''
        self.current_task_file = ''
        self.main_view = ''
        self.controls_enabled = False
Ejemplo n.º 11
0
  def testcreate_and_delete(self):
    tasklist = TaskList("rays-test=00")
    tasklist.create()
    self.failIf(not tasklist.exists())

    tasklist.delete()
    self.failIf(tasklist.exists())
Ejemplo n.º 12
0
class Strategy(Task):
    def __init__(self, xml, actions, orders, communicator):
        super(Strategy, self).__init__(xml)
        self.Name = xml.attrib["name"]
        self.communicator = communicator
        self.loadxml(xml, actions, orders)

    def loadxml(self, xml, actions, orders):
        self.TASKS = TaskList(xml, actions, orders)

    def canContinue(self):
        return self.getStatus() in [
            TaskStatus.FREE, TaskStatus.PENDING, TaskStatus.PAUSED
        ]

    def getNext(
            self):  # Returns the next free task (TaskList, Action or Order).
        return self.TASKS.getNext()

    def sendReward(self, communicator):
        communicator.SendRequest("/ai/scheduler/score",
                                 {"score": self.TASKS.getActiveReward()})

    def getStatus(self, text_version=False):
        return self.TASKS.getStatus(text_version)

    def PrettyPrint(self):
        rospy.loginfo("[STRATEGY {}⚡ ACTIVE] {}".format(
            self.TASKS.getActiveReward(), self.__repr__()))
        self.TASKS.prettyprint(1)

    def __repr__(self):
        return self.Name
Ejemplo n.º 13
0
def test_take_2(sentence1):
    node_0 = Node('', 0, sentence1, state=NodeState.ROOT)
    tasklist = TaskList(node_0)
    assert len(tasklist) == 1

    nodes = tasklist.next(size=2)
    assert len(nodes) == 1
    next_node_0 = nodes[0]
    assert len(tasklist) == 0
    assert next_node_0.next_pos == 0

    node_1 = Node('..', 0, '-.--.', parent=next_node_0)
    tasklist.add(node_1)
    node_2 = Node('-', 2, '.--.', parent=node_1)
    tasklist.add(node_2)

    nodes = tasklist.next(size=2)
    assert len(nodes) == 2
Ejemplo n.º 14
0
    def test_active_sort(self):
        name = "test3"
        
        tl = TaskList(name, self.workingD)

        tsk1 = task.Task("Task with early due date and priority 0", 1367144200 , 0)
        tsk2 = task.Task("Task with later due date and priority 0", 1367144210 , 0)

        tl.add(tsk1)
        tl.add(tsk2)

        assert tl.activetasks[0].equals(tsk1)

        tsk3 = task.Task("Task with earlier due date and priority 0", 1367144100 , 0)

        tl.add(tsk3)

        assert tl.activetasks[0].equals(tsk3)

        tsk4 = task.Task("Task with the same due date and higher priority", 1367144100, 1)
        
        tl.add(tsk4)

        assert tl.activetasks[0].equals(tsk4)
Ejemplo n.º 15
0
    def test_save_load(self):
        name = "test2"
        tsk1 = task.Task("Do something", 1367144289 , 0)
        tsk2 = task.Task("Do something else", 1367144288 , 0)
        tsk3 = task.Task("A completed task", 13671442887, 0)

        before = TaskList(name, self.workingD)
        before.add(tsk1)
        before.add(tsk2)

        before.add(tsk3)
        before.complete(2)

        before.save()

        after = TaskList(name, self.workingD)
        assert after.active() == 2
        assert after.completed() == 1
        
        assert after.activetasks[0].equals(before.activetasks[0])
        assert after.activetasks[1].equals(before.activetasks[1])

        assert after.completedtasks[0].equals(before.completedtasks[0])

        before.destroy()
Ejemplo n.º 16
0
def test_first_task(sentence1):
    node_0 = Node('', 0, sentence1, state=NodeState.ROOT)
    tasklist = TaskList(node_0)
    next_node = tasklist.next()
    assert next_node.remaining == sentence1
Ejemplo n.º 17
0
def test_task_order(sentence1):
    node_0 = Node('', 0, sentence1, state=NodeState.ROOT)
    tasklist = TaskList(node_0)

    node_1a = Node('6', 6, '', parent=node_0)
    tasklist.add(node_1a)
    node_1b = Node('5', 5, '', parent=node_0)
    tasklist.add(node_1b)
    node_1c = Node('2', 2, '', parent=node_0)
    tasklist.add(node_1c)
    node_1d = Node('3', 3, '', parent=node_0)
    tasklist.add(node_1d)
    node_1e = Node('4', 4, '', parent=node_0)
    tasklist.add(node_1e)
    node_1f = Node('1', 1, '', parent=node_0)
    tasklist.add(node_1f)

    assert len(tasklist) == 7

    next_node = tasklist.next()
    assert next_node.next_pos == 7
    assert len(tasklist) == 6

    next_node = tasklist.next()
    assert next_node.next_pos == 6
    assert len(tasklist) == 5
Ejemplo n.º 18
0
class Menu:

    def __init__(self):
        """Initialize the task list and populate the dictionary for menu actions."""

        self.tasklist = TaskList()
        self.current_task = ''
        self.current_task_file = ''
        self.main_view = ''
        self.controls_enabled = False

    def display_message(self, message):
        self.message_dialog = ui.load_view('dialogs/message')
        self.message_dialog['label1'].text = message
        self.message_dialog.present('popover', popover_location = (500,500))
		
    def show_tasks(self, sender, tasks=None):
        """Display the tasks (in ID order)

        :param tasks: tasks object
        """
        
        if not tasks:
            tasks = self.tasklist.tasks
        tv_text = ""
        if len(tasks) > 0:
            if not self.controls_enabled:
                #enable controls if there are tasks loaded
                self.main_view['button_number'].enabled = True
                self.main_view['button_priority'].enabled = True
                self.main_view['button_save'].enabled = True
                self.main_view['button_delete_task'].enabled = True
                self.main_view['button_modify'].enabled = True
                self.main_view['button_search'].enabled = True
                self.controls_enabled = True
            for task in tasks:
                tv_text += '{}: {}\n\tPriority: {}\n\tTags: {}\n'.format(task.id, task.note, task.priority, task.tags)
        else:
            tv_text = '\nThere are no tasks to display!\n'
        
        self.task_textview.text = tv_text

    def show_tasks_by_priority(self, sender, tasks=None):
        """Display the tasks (in Priority order)

        :param tasks: tasks object
        """
        low_dict = OrderedDict()
        med_dict = OrderedDict()
        high_dict = OrderedDict()

        if not tasks:
            tasks = self.tasklist.tasks
        tv_text = ''

        if len(tasks) > 0:
            for task in tasks:
                if task.priority == 'Low':
                    low_dict[task.id] = [task.note, task.priority, task.tags]
                if task.priority == 'Medium':
                    med_dict[task.id] = [task.note, task.priority, task.tags]
                if task.priority == 'High':
                    high_dict[task.id] = [task.note, task.priority, task.tags]
        else:
            tv_text += '\nThere are no tasks to display!\n'
            return

        tv_text += 'High\n' + '-' * 20 + '\n'
        if len(high_dict) > 0:
            for key in high_dict:
                tv_text += '{}: {}\n\tTags: {}\n'.format(key, high_dict[key][0], high_dict[key][2])
        else:
            tv_text += 'There are no high priority tasks\n'

        tv_text += '\nMedium\n' + '-' * 20 + '\n'
        if len(med_dict) > 0:
            for key in med_dict:
                tv_text += '{}: {}\n\tTags: {}\n'.format(key, med_dict[key][0], med_dict[key][2])
        else:
            tv_text += 'There are no medium priority tasks\n'

        tv_text+= '\nLow\n' + '-' * 20 + '\n'
        if len(low_dict) > 0:
            for key in low_dict:
                tv_text += '{}: {}\n\tTags: {}\n'.format(key, low_dict[key][0], low_dict[key][2])
        else:
            tv_text += 'There are no low priority tasks\n'

        self.task_textview.text = tv_text

    def prompt_search(self, sender):
    	"""Prompt the user for a search string."""
    	
        self.search_dialog = ui.load_view('dialogs/search_tasks')
        self.search_dialog.present('sheet')

    def search_tasks(self, sender):
        """Search the task list for a task whose note or tag contains the user provided search string."""

        search_string = self.search_dialog['textfield1'].text.lower()
        tasks = self.tasklist.search(search_string)
        if tasks:
            self.search_dialog.close()
            self.show_tasks(sender,tasks=tasks)
        else:
            #self.search_dialog.close()
            message = 'There were no tasks containing "{}".'.format(search_string)
            self.display_message(message)
            
    def prompt_add(self, sender):
    	"""Prompt the user to add a task."""
    	
    	self.add_dialog = ui.load_view('dialogs/add_task')
        self.add_dialog.present('sheet')

    def add_task(self, sender):
        """Add a new task."""

        note = self.add_dialog['textfield_task'].text
        priority_num = self.add_dialog['segmentedcontrol1'].selected_index
        if priority_num == 0:
        	priority = 'Low'
        elif priority_num == 1:
        	priority = 'Medium'
        elif priority_num == 2:
        	priority = 'High'
        tags = self.add_dialog['textfield_tags'].text
        self.tasklist.add_task(note, priority, tags)
        self.add_dialog.close()
        self.show_tasks(None)

    def prompt_delete_file(self, sender):
    	"""Prompt the user to delete a task file."""
    	
    	self.delete_dialog = ui.load_view('dialogs/delete_task_file')
        self.delete_dialog.present('sheet')

    def delete_file(self, sender):
    	"""Delete a task file."""
        task_file = self.delete_dialog['textfield1'].text
        if not task_file == '':
        	task_file = util.validate_file(task_file)
        if task_file:
        	self.delete_dialog.close()
        	util.delete(task_file)
        else:
        	self.display_message(self.delete_dialog['textfield1'].text + ' is not a valid file!')
        	self.delete_dialog['textfield1'].text = ''

    def prompt_delete_task(self, sender):
    	"""Prompt the user to delete a task."""
    	
    	self.delete_dialog = ui.load_view('dialogs/delete_task')
        self.delete_dialog.present('popover', popover_location = (500,500))

    def delete_task(self, sendr):
        """Delete a task."""
        task_id = self.delete_dialog['textfield1'].text
        task_id = self._validate_task_id(task_id)
        if task_id:
            self.delete_dialog.close()
            self.tasklist.delete_task(task_id)
            self.tasklist._renumber_tasks()
            #Task.last_id -= 1
            self.show_tasks(None)
        else:
            self.delete_dialog['textfield1'].text = ''
            
    def prompt_modify_task_number(self, sender):
    	"""Prompt the user for the number of the task modify."""
    	
    	self.modify_dialog = ui.load_view('dialogs/modify_task_number')
        self.modify_dialog.present('popover', popover_location = (500,500))

    def modify_task(self, sender):
        """Change the fields of a task."""

        task_id = self._validate_task_id(self.modify_dialog['textfield1'].text)
        if task_id:
            self.current_task = self.tasklist._find_task(task_id)
            self.modify_dialog.close()
            self.modify_dialog = ui.load_view('dialogs/modify_task')
            self.modify_dialog['textfield_task'].text = self.current_task.note
            if self.current_task.priority == 'Low':
                self.modify_dialog['segmentedcontrol1'].selected_index = 0
            if self.current_task.priority == 'Medium':
                self.modify_dialog['segmentedcontrol1'].selected_index = 1
            if self.current_task.priority == 'High':
                self.modify_dialog['segmentedcontrol1'].selected_index = 2
            self.modify_dialog['textfield_tags'].text = self.current_task.tags
            self.modify_dialog.present('sheet')

    def save_modified_task(self, sender):
        """Save the contents of the modified task."""
        	
        self.current_task.note = self.modify_dialog['textfield_task'].text
        priority_num = self.modify_dialog['segmentedcontrol1'].selected_index
        if priority_num == 0:
        	self.current_task.priority = 'Low'
        elif priority_num == 1:
        	self.current_task.priority = 'Medium'
        elif priority_num == 2:
        	self.current_task.priority = 'High'
        self.current_task.tags = self.modify_dialog['textfield_tags'].text
        self.modify_dialog.close()
        self.show_tasks(None)
                
    def prompt_load(self, sender):
    	"""Prompt the user for the name of a task file."""
    	
        self.load_dialog = ui.load_view('dialogs/load_task_file')
        self.load_dialog.present('sheet')

    def load_tasks(self, sender):
        """Retrieve the contents of the task file."""

        task_file = self.load_dialog['textfield1'].text
        if not task_file == '':
        	task_file = util.validate_file(task_file)
        if task_file:
        	self.load_dialog.close()
	        self.tasklist.tasks = util.load(task_file)
	        self.current_task_file = task_file
	        Task.last_id = len(self.tasklist.tasks)
	        self.show_tasks(None)
        else:
        	self.display_message(self.load_dialog['textfield1'].text + ' is not a valid file')
        	self.load_dialog['textfield1'].text = ''

    def prompt_save(self, sender):
    	"""Prompt the user for the name of a task file."""
    	
        self.save_dialog = ui.load_view('dialogs/save_task_file')
        self.save_dialog.present('sheet')

    def save_tasks(self, sender):
		"""Save the tasks to the specified file."""
		
		task_file = self.save_dialog['textfield1'].text
		if not task_file == '':
			if task_file.rfind('.tsk', len(task_file) -4) == -1:
				task_file += '.tsk'
			self.save_dialog.close()
			if task_file == self.current_task_file:
				# some bug; even though the file should be closed, I can't overwrite 
				util.delete(task_file)
			util.save(self.tasklist.tasks, task_file)
		else:
			self.save_dialog['textfield1'].text = ''

    def _validate_task_id(self, task_id):
        """Validate the given task ID.

        :return: False if an invalid ID was provided, otherwise a string containing the valid task id.
        """

        if task_id.isdecimal() and int(task_id) <= len(self.tasklist.tasks):
            return task_id
        else:
            self.display_message('{} is not an existing task!'.format(task_id))
            return None

    def run(self):
        main_view = ui.load_view("menu")
    	# turn off invalid controls
    	main_view['button_number'].enabled = False
    	main_view['button_priority'].enabled = False
    	main_view['button_save'].enabled = False
    	main_view['button_delete_task'].enabled = False
    	main_view['button_modify'].enabled = False
    	main_view['button_search'].enabled = False
        main_view.present("sheet")
        self.main_view = main_view
        self.task_textview = main_view['task_textview']
    	self.task_textview.text = help.help_text
Ejemplo n.º 19
0
def test_simple_path(sentence1):
    node_0 = Node('', 0, sentence1, state=NodeState.ROOT)
    tasklist = TaskList(node_0)
    assert len(tasklist) == 1

    next_node_0 = tasklist.next()
    assert len(tasklist) == 0
    assert next_node_0.next_pos == 0

    node_1 = Node('..', 0, '-.--.', parent=next_node_0)
    tasklist.add(node_1)
    next_node_1 = tasklist.next()
    assert len(tasklist) == 0
    assert next_node_1.next_pos == 2

    node_2 = Node('-', 2, '.--.', parent=next_node_1)
    tasklist.add(node_2)
    next_node_2 = tasklist.next()
    assert len(tasklist) == 0
    assert next_node_2.next_pos == 3

    node_3 = Node('.--', 3, '.', parent=next_node_2)
    tasklist.add(node_3)
    next_node_3 = tasklist.next()
    assert len(tasklist) == 0
    assert next_node_3.next_pos == 6

    node_4 = Node('.', 6, '', parent=next_node_3)
    tasklist.add(node_4)
    next_node_4 = tasklist.next()
    assert len(tasklist) == 0
    assert next_node_4.next_pos == 7

    next_node_done = tasklist.next()
    assert next_node_done is None
Ejemplo n.º 20
0
from tasklist import TaskList
from lxml import etree
import time
import socket

__BIND_ADDR__ = "0.0.0.0"  # 监听本机的所有网卡IP
__BIND_PORT__ = 8888  # 监听8888端口

__LIST_URL__ = "http://finance.sina.com.cn/china/"  # 文章列表的网址
__COUNT_URL__ = 50  # 设定只获取50篇文章的URL

__XPATH__URL__ = "//div[@class='feed-card-item']/h2/a/@href"
__XPATH_NEXT__ = "//span[@class='pagebox_next']/a"

# 初始化一个任务列表
task_list = TaskList(timeout=30)

# 初始化一个套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((__BIND_ADDR__, int(__BIND_PORT__)))
sock.listen(50)

# 初始化一个Selenium WebDriver
chrome_options = webdriver.ChromeOptions()  # 获取ChromeWebdriver配置文件
prefs = {"profile.managed_default_content_settings.images": 2}  # 设置不加载图片以加快速度
chrome_options.add_experimental_option("prefs", prefs)
chrome_options.add_argument("--headless")  # 不使用GUI界面
chrome_options.add_argument("--disable-gpu")  # 禁用GPU渲染加速
driver = webdriver.Chrome(chrome_options=chrome_options)  # 创建ChromeWebdriver
driver.set_page_load_timeout(10)  # 设置连接超时时间为15s
Ejemplo n.º 21
0
"""
Controller for our app, does the routes for us and calls the methods of the TaskList.
"""

from flask import Flask, render_template

from tasklist import TaskList

app = Flask(__name__)
task_list = TaskList()


@app.route('/')
def index():
    view_data = {
        'title':
        'Task List',
        'message':
        'Welcome to Task List!  To see the requests available, try help.'
    }
    return render_template('message.html', view_data=view_data)
    #return view_data['message']


@app.route('/help/')
def help():
    return 'Requests available: show-tasks, create-task, remove-task'


@app.route('/show-tasks/')
def get_tasks():
Ejemplo n.º 22
0
 def testcreate(self):
   tasklist = TaskList()
   name = "rays-test-01"
   tasklist.create(name)
   self.failIf(not tasklist.exists(name))
Ejemplo n.º 23
0
class Functions:
    def __init__(self):
        """Initialize the task list."""

        self.tasklist = TaskList()
        self.legend = '\nLegend: Not Due  ' + Fore.CYAN + Style.BRIGHT + 'Upcoming  ' + Fore.BLUE + \
                      Style.BRIGHT + 'Due  ' + Fore.RED + Style.BRIGHT + 'Overdue  ' + Fore.WHITE + Style.BRIGHT + \
                      Back.WHITE + 'Completed' + Fore.RESET + Style.NORMAL + Back.RESET

    def show_tasks(self, tasks=None, date_format=None):
        """Display the tasks (in ID order)

		:param tasks: tasks object
		"""

        if not tasks:
            tasks = self.tasklist.tasks

        if len(tasks) > 0:

            template = '{0:^3} {1:20} {2:^3} {3:20} {4:15} {5:20}'
            print template.format('\nID', 'Description', ' Pri', 'Due',
                                  'Created', 'Tags')
            print template.format('---', '--------------------', '---',
                                  '--------------------', '---------------',
                                  '--------------------')
            for task in tasks:
                if task.priority == 'L':
                    priority = Fore.YELLOW + Style.BRIGHT + task.priority.center(
                        3) + Fore.RESET + Style.NORMAL
                elif task.priority == 'M':
                    priority = Fore.BLUE + Style.BRIGHT + task.priority.center(
                        3) + Fore.RESET + Style.NORMAL
                elif task.priority == 'H':
                    priority = Fore.RED + Style.BRIGHT + task.priority.center(
                        3) + Fore.RESET + Style.NORMAL
                else:
                    priority = ''

                if task.due_date is None:
                    due_date = ''
                else:
                    if date_format:
                        due_date = task.due_date.rsplit(' ', 1)[0].ljust(20)
                    else:
                        due_date = (arrow.get(
                            task.due_date,
                            task.due_date_format).humanize()).ljust(20)

                    if not task.completed:
                        today = arrow.now()
                        diff = arrow.get(task.due_date,
                                         task.due_date_format) - today
                        if diff.days >= 1 and diff.seconds > 0:
                            due_date = Fore.CYAN + Style.BRIGHT + due_date + Fore.RESET + Style.NORMAL
                        elif diff.days >= 0:
                            due_date = Fore.BLUE + Style.BRIGHT + due_date + Fore.RESET + Style.NORMAL
                        elif diff.days <= 0:
                            due_date = Fore.RED + Style.BRIGHT + due_date + Fore.RESET + Style.NORMAL

                if date_format:
                    age = (str(task.creation_date).split()[0]).ljust(
                        15)  # drop the time zone
                else:
                    age = (arrow.get(
                        task.creation_date,
                        'MM/DD/YYYY h:mm:ss A ZZ').humanize()).ljust(15)

                if task.note:
                    desc = task.task + ' *'
                else:
                    desc = task.task

                if task.completed:
                    if task.priority:
                        priority = task.priority
                    else:
                        priority = ''
                    task_id = Fore.WHITE + Style.BRIGHT + Back.WHITE + str(
                        task.id).center(3)
                    tags = str(
                        task.tags) + Fore.RESET + Style.NORMAL + Back.RESET
                    print template.format(task_id, desc, priority, due_date,
                                          age, tags)
                else:
                    print template.format(task.id, desc, priority, due_date,
                                          age, task.tags)

            print self.legend
        else:
            print('\nThere are no tasks to display!\n')

    def show_tasks_by_priority(self, tasks=None, date_format=None):
        """Display the tasks (in Priority order)

		:param tasks: tasks object
		"""

        low_dict_o = OrderedDict()
        med_dict_o = OrderedDict()
        high_dict_o = OrderedDict()
        no_dict_o = OrderedDict()
        completed_dict_o = OrderedDict()

        low_dict = {}
        med_dict = {}
        high_dict = {}
        no_dict = {}
        completed_dict = {}

        temp_dict = {}

        if not tasks:
            tasks = self.tasklist.tasks

        if len(tasks) > 0:
            for task in tasks:
                if task.due_date is None:
                    due_date = ''
                else:
                    if date_format:
                        due_date = task.due_date.rsplit(' ', 1)[0].ljust(20)
                    else:
                        due_date = (arrow.get(
                            task.due_date,
                            task.due_date_format).humanize()).ljust(20)

                age = (str(task.creation_date).split()[0]).ljust(
                    15)  # drop the time zone

                if task.note:
                    desc = task.task + ' *'
                else:
                    desc = task.task

                if task.completed:
                    completed_dict[
                        task.
                        id] = task.priority, due_date, age, desc, task.tags
                elif task.priority == 'L':
                    low_dict[task.id] = [
                        task.priority, due_date, age, desc, task.tags
                    ]
                elif task.priority == 'M':
                    med_dict[task.id] = [
                        task.priority, due_date, age, desc, task.tags
                    ]
                elif task.priority == 'H':
                    high_dict[task.id] = [
                        task.priority, due_date, age, desc, task.tags
                    ]
                else:
                    no_dict[task.id] = [
                        task.priority, due_date, age, desc, task.tags
                    ]

        else:
            print('\nThere are no tasks to display!\n')
            return

        for key, value in sorted(no_dict.items(), key=lambda e: e[1][1]):
            if value[1] is not '':
                no_dict_o[key] = value
            else:
                temp_dict[key] = value

        for key in temp_dict:
            no_dict_o[key] = temp_dict[key]

        temp_dict.clear()

        for key, value in sorted(low_dict.items(), key=lambda e: e[1][1]):
            if value[1] is not '':
                low_dict_o[key] = value
            else:
                temp_dict[key] = value

        for key, value in temp_dict.items():
            low_dict_o[key] = value

        temp_dict.clear()

        for key, value in sorted(med_dict.items(), key=lambda e: e[1][1]):
            if value[1] is not '':
                med_dict_o[key] = value
            else:
                temp_dict[key] = value

        for key, value in temp_dict.items():
            med_dict_o[key] = value

        temp_dict.clear()

        for key, value in sorted(high_dict.items(), key=lambda e: e[1][1]):
            if value[1] is not '':
                high_dict_o[key] = value
            else:
                temp_dict[key] = value

        for key, value in sorted(temp_dict.items(), key=lambda e: e[1][1]):
            high_dict_o[key] = value

        temp_dict.clear()

        for key, value in sorted(completed_dict.items(),
                                 key=lambda e: e[1][1]):
            if value[1] is not '':
                completed_dict_o[key] = value
            else:
                temp_dict[key] = value

        for key, value in temp_dict.items():
            completed_dict_o[key] = value

        temp_dict.clear()

        del low_dict
        del med_dict
        del high_dict
        del no_dict
        del completed_dict

        today = arrow.now()

        # TODO: Figure out why the key is a tuple instead of a list

        for dict in [low_dict_o, med_dict_o, high_dict_o, no_dict_o]:
            for key, value in dict.items():
                dict[key] = list(
                    dict[key])  # hack - how is this key a tuple!?!
                if value[0] == 'L':
                    dict[key][0] = Fore.YELLOW + Style.BRIGHT + value[
                        0].center(3) + Fore.RESET + Style.NORMAL
                elif value[0] == 'M':
                    dict[key][0] = Fore.BLUE + Style.BRIGHT + value[0].center(
                        3) + Fore.RESET + Style.NORMAL
                elif value[0] == 'H':
                    dict[key][0] = Fore.RED + Style.BRIGHT + value[0].center(
                        3) + Fore.RESET + Style.NORMAL
                else:
                    dict[key][0] = ''

                task = self.tasklist.find_task(key)
                if task.due_date:
                    diff = arrow.get(task.due_date,
                                     task.due_date_format) - today
                    if diff.days >= 1 and diff.seconds > 0:
                        dict[key][1] = Fore.CYAN + Style.BRIGHT + value[
                            1] + Fore.RESET + Style.NORMAL
                    elif diff.days >= 0:
                        dict[key][1] = Fore.BLUE + Style.BRIGHT + value[
                            1] + Fore.RESET + Style.NORMAL
                    elif diff.days <= 0:
                        dict[key][1] = Fore.RED + Style.BRIGHT + value[
                            1] + Fore.RESET + Style.NORMAL

        template = '{0:^3} {1:20} {2:^3} {3:20} {4:15} {5:20}'
        print template.format('\nPri', 'Description', 'ID', 'Due', 'Created',
                              'Tags')
        print template.format('---', '--------------------', '---',
                              '--------------------', '---------------',
                              '--------------------')

        if len(high_dict_o) > 0:
            for key in high_dict_o:
                print template.format(high_dict_o[key][0], high_dict_o[key][3],
                                      key, high_dict_o[key][1],
                                      high_dict_o[key][2], high_dict_o[key][4])
        if len(med_dict_o) > 0:
            for key in med_dict_o:
                print template.format(med_dict_o[key][0], med_dict_o[key][3],
                                      key, med_dict_o[key][1],
                                      med_dict_o[key][2], med_dict_o[key][4])
        if len(low_dict_o) > 0:
            for key in low_dict_o:
                print template.format(low_dict_o[key][0], low_dict_o[key][3],
                                      key, low_dict_o[key][1],
                                      low_dict_o[key][2], low_dict_o[key][4])
        if len(no_dict_o) > 0:
            for key in no_dict_o:
                print template.format(no_dict_o[key][0], no_dict_o[key][3],
                                      key, no_dict_o[key][1],
                                      no_dict_o[key][2], no_dict_o[key][4])

        completed_template = Fore.WHITE + Style.BRIGHT + Back.WHITE + '{0:^3} {1:20} {2:^3} {3:20} {4:15} {5:20}' + \
                             Fore.RESET + Style.NORMAL + Back.RESET
        if len(completed_dict_o) > 0:
            for key in completed_dict_o:
                if completed_dict_o[key][0]:
                    priority = completed_dict_o[key][0]
                else:
                    priority = ''
                print completed_template.format(priority,
                                                completed_dict_o[key][3], key,
                                                completed_dict_o[key][1],
                                                completed_dict_o[key][2],
                                                completed_dict_o[key][4])
        print self.legend

    def show_task(self, task_id):
        """Display the specified task, including its notes, if any.

		:param str task_id: the task_id of the task.
		"""

        task_id = self._validate_task_id(task_id)
        if task_id:
            task = self.tasklist.find_task(task_id)
            if task:
                if task.priority == 'L':
                    priority = Fore.YELLOW + Style.BRIGHT + ' ' + task.priority + ' ' + Fore.RESET + Style.NORMAL
                elif task.priority == 'M':
                    priority = Fore.BLUE + Style.BRIGHT + ' ' + task.priority + ' ' + Fore.RESET + Style.NORMAL
                elif task.priority == 'H':
                    priority = Fore.RED + Style.BRIGHT + ' ' + task.priority + ' ' + Fore.RESET + Style.NORMAL
                else:
                    priority = ''
                template = '{0:^3} {1:^3} {2:20} {3:40}'
                print template.format('\nID', ' Pri', 'Description', 'Note')
                print template.format(
                    '---', '---', '--------------------',
                    '----------------------------------------')
                print template.format(task.id, priority, task.task, task.note)

    def search_tasks(self, search_string):
        """Search the task list for a task whose contents contains the user provided search string.

		:param str search_string:    the string to search for.
		"""

        tasks = self.tasklist.search(search_string.lower())
        if tasks:
            self.show_tasks(tasks)
        else:
            print('\nThere were no tasks containing "{}".\n'.format(
                search_string))

    def add_task(self,
                 task,
                 priority=None,
                 due_date=None,
                 tags=None,
                 note=None):
        """Add a new task."""

        self.tasklist.add_task(task, priority, due_date, tags, note)

    def delete_task(self, task_id):
        """Delete a task."""

        task_id = self._validate_task_id(task_id)
        if task_id:
            self.tasklist.delete_task(task_id)
            self.tasklist.renumber_tasks()
            print('Task ' + task_id + ' was deleted.')

    def modify_task(self,
                    task_id,
                    task_=None,
                    completed=False,
                    priority=None,
                    due_date=None,
                    note=None,
                    tags=None,
                    time=None):
        """Modify a task."""

        task_id = self._validate_task_id(task_id)
        if task_id:
            task = self.tasklist.find_task(task_id)
            if task:
                print 'Modifying task ' + str(task_id) + ': ' + task.task
                if task_:
                    task.task = task_
                elif priority:
                    task.priority = priority
                elif due_date:
                    if isinstance(due_date, list):
                        task.due_date = due_date[0]
                        task.due_date_format = due_date[1]
                    else:
                        task.due_date = due_date
                elif note:
                    task.note = note
                elif tags:
                    task.tags = tags
                elif time:
                    time_str = time.split(' ')[0]
                    time_hour, time_minute = time_str.split(':')
                    if 'PM' in time:
                        time_hour = int(time_hour) + 12
                    due_date = arrow.get(task.due_date, task.due_date_format)
                    due_date = due_date.replace(hour=time_hour,
                                                minute=int(time_minute))
                    task.due_date = due_date.format(task.due_date_format)
                elif completed:
                    task.completed = True
                print 'Modified task ' + str(task_id)

    def load_tasks(self, task_file):
        """Load the task file and retrieve the tasks."""

        self.tasklist.tasks = util.load(task_file)
        Task.last_id = len(self.tasklist.tasks)

    def save_tasks(self, task_file):
        """Save the task file."""

        util.save(self.tasklist.tasks, task_file)

    def _validate_task_id(self, task_id):
        """Validate a task id.

		:return: None if an invalid ID was provided, otherwise a string containing the valid task id.
		"""

        if task_id.isdigit() and int(task_id) <= len(self.tasklist.tasks):
            return task_id
        else:
            print('{} is not an existing task!'.format(task_id))
            return None
Ejemplo n.º 24
0
# This is the main program entry point.
#  Build up the workers and queues, and then kick everything off.

from tasklist import TaskList
import queue
import threading
import page_summary
import argparse

tasklist = TaskList()
output_queue = queue.Queue()


def output_worker():  # where the results get printed
    while True:
        p = output_queue.get()
        try:
            print(p.toString(args["showThreadNames"]))
        finally:
            output_queue.task_done(
            )  #mark the url printed, even if somthing went wrong.


def page_worker():  # where the pages get summarised
    while True:
        url = tasklist.get()
        try:
            p = page_summary.page_summary(url, lambda x: tasklist.put(x))
            output_queue.put(p)
        finally:
            tasklist.task_done(
Ejemplo n.º 25
0
def run(args):
    """Runs the bootstrapping process

	Args:
		args (dict): Dictionary of arguments from the commandline
	"""
    # Load the manifest
    from manifest import Manifest
    manifest = Manifest(args.manifest)

    # Get the tasklist
    from tasklist import TaskList
    tasklist = TaskList()
    # 'resolve_tasks' is the name of the function to call on the provider and plugins
    tasklist.load('resolve_tasks', manifest)

    # Create the bootstrap information object that'll be used throughout the bootstrapping process
    from bootstrapinfo import BootstrapInformation
    bootstrap_info = BootstrapInformation(manifest=manifest, debug=args.debug)

    try:
        # Run all the tasks the tasklist has gathered
        tasklist.run(info=bootstrap_info, dry_run=args.dry_run)
        # We're done! :-)
        log.info('Successfully completed bootstrapping')
    except (Exception, KeyboardInterrupt) as e:
        # When an error occurs, log it and begin rollback
        log.exception(e)
        if args.pause_on_error:
            # The --pause-on-error is useful when the user wants to inspect the volume before rollback
            raw_input('Press Enter to commence rollback')
        log.error('Rolling back')

        # Create a new tasklist to gather the necessary tasks for rollback
        rollback_tasklist = TaskList()

        # Create a useful little function for the provider and plugins to use,
        # when figuring out what tasks should be added to the rollback list.
        def counter_task(task, counter):
            """counter_task() adds the second argument to the rollback tasklist
			if the first argument is present in the list of completed tasks

			Args:
				task (Task): The task to look for in the completed tasks list
				counter (Task): The task to add to the rollback tasklist
			"""
            if task in tasklist.tasks_completed and counter not in tasklist.tasks_completed:
                rollback_tasklist.tasks.add(counter)

        # Ask the provider and plugins for tasks they'd like to add to the rollback tasklist
        # Any additional arguments beyond the first two are passed directly to the provider and plugins
        rollback_tasklist.load('resolve_rollback_tasks', manifest,
                               counter_task)

        # Run the rollback tasklist
        rollback_tasklist.run(info=bootstrap_info, dry_run=args.dry_run)
        log.info('Successfully completed rollback')
Ejemplo n.º 26
0
def main():
    addr = "0.0.0.0"
    port = 9992

    main_url = "http://money.163.com/special/00252C1E/gjcj.html"

    task_list = TaskList(timeout=30)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((addr, port))
    sock.listen(50)

    #driver = webdriver.Chrome()
    #driver.get(main_url)

    print("正在从网页中解析URL链接...")

    def gethtmltext(url, code="gbk"):
        try:
            r = requests.get(url)
            r.raise_for_status()
            r.encoding = code
            return r.text
        except requests.exceptions.ConnectionError:
            return ""

    html = gethtmltext(main_url)
    try:
        if html == "":
            print("---html error1!---")
        soup = BeautifulSoup(html, 'html.parser')
        url_info = soup.find_all('div', attrs={'class': 'list_item clearfix'})
        news_url = list()
        for i in url_info:
            # noinspection PyBroadException
            try:
                a = i.find(name='h2')
                url = a.find(name='a').attrs['href']
                news_url.append(url)
                print(url)
            except:
                continue
        task_list.put_tasks(news_url)
    except:
        print("---url error2!---")
        # driver.close()

    print("等待client中.......")
    while 1:
        if task_list.is_empty():
            print("====任务完成====")
            sock.close()
            break

        conn, addr = sock.accept()  # 接受TCP连接,并返回新的套接字与IP地址
        print('Connected by\n', addr, conn)  # 输出客户端的IP地址
        try:
            data = conn.recv(1024).decode("gbk")
            if data.split(',')[0] == "get":
                client_id = data.split(',')[1]
                task_url = task_list.get_task()

                print("向client {0} 分配 {1}".format(client_id, task_url))
                conn.send(task_url.encode("gbk"))
            elif data.split(',')[0] == "done":
                client_id = data.split(',')[1]
                client_url = data.split(',')[2]
                print("client {0}' 完成爬取 {1}".format(client_id, client_url))
                task_list.done_task(client_url)
                conn.send("ok".encode("gbk"))
        except socket.timeout:
            print("Timeout!")
        conn.close()  # 关闭连接
Ejemplo n.º 27
0
 def loadxml(self, xml, actions, orders):
     self.TASKS = TaskList(xml, actions, orders)
Ejemplo n.º 28
0
    taskerfolder = path.join(home, ".tasker")
    if not path.exists(taskerfolder):
        # Create it if it does not exist
        print 'Creating Tasker folder at: ' + taskerfolder
        os.makedirs(taskerfolder)

    # No arguments, default to list by adding it
    if len(sys.argv) == 1:
        sys.argv.append('list')

    # Get command from args
    cmd = sys.argv[1].lower()

    if cmd == 'list':
        # List tasks
        t = TaskList('default', taskerfolder)
        t.print_list()

    elif cmd == 'add':
        t = TaskList('default', taskerfolder)
        t.add(create_new_task())
        t.save()

        t.print_list()

    elif cmd =='-h' or cmd == '--help':
        # Show usage
        print "Try one of the following:"
        print "  list \t:   List your tasks."
        print "  add  \t:   Add a new task to the list"
    else:
Ejemplo n.º 29
0
class Functions:
	def __init__(self):
		"""Initialize the task list."""

		self.tasklist = TaskList()
		self.legend = '\nLegend: Not Due  ' + Fore.CYAN + Style.BRIGHT + 'Upcoming  ' + Fore.BLUE + \
		              Style.BRIGHT + 'Due  ' + Fore.RED + Style.BRIGHT + 'Overdue  ' + Fore.WHITE + Style.BRIGHT + \
		              Back.WHITE + 'Completed' + Fore.RESET + Style.NORMAL + Back.RESET

	def show_tasks(self, tasks=None, date_format=None):
		"""Display the tasks (in ID order)

		:param tasks: tasks object
		"""

		if not tasks:
			tasks = self.tasklist.tasks

		if len(tasks) > 0:

			template = '{0:^3} {1:20} {2:^3} {3:20} {4:15} {5:20}'
			print template.format('\nID', 'Description', ' Pri', 'Due', 'Created', 'Tags')
			print template.format('---', '--------------------', '---', '--------------------', '---------------',
			                      '--------------------')
			for task in tasks:
				if task.priority == 'L':
					priority = Fore.YELLOW + Style.BRIGHT + task.priority.center(3) + Fore.RESET + Style.NORMAL
				elif task.priority == 'M':
					priority = Fore.BLUE + Style.BRIGHT + task.priority.center(3) + Fore.RESET + Style.NORMAL
				elif task.priority == 'H':
					priority = Fore.RED + Style.BRIGHT + task.priority.center(3) + Fore.RESET + Style.NORMAL
				else:
					priority = ''

				if task.due_date is None:
					due_date = ''
				else:
					if date_format:
						due_date = task.due_date.rsplit(' ', 1)[0].ljust(20)
					else:
						due_date = (arrow.get(task.due_date, task.due_date_format).humanize()).ljust(20)

					if not task.completed:
						today = arrow.now()
						diff = arrow.get(task.due_date, task.due_date_format) - today
						if diff.days >= 1 and diff.seconds > 0:
							due_date = Fore.CYAN + Style.BRIGHT + due_date + Fore.RESET + Style.NORMAL
						elif diff.days >= 0:
							due_date = Fore.BLUE + Style.BRIGHT + due_date + Fore.RESET + Style.NORMAL
						elif diff.days <= 0:
							due_date = Fore.RED + Style.BRIGHT + due_date + Fore.RESET + Style.NORMAL

				if date_format:
					age = (str(task.creation_date).split()[0]).ljust(15)  # drop the time zone
				else:
					age = (arrow.get(task.creation_date, 'MM/DD/YYYY h:mm:ss A ZZ').humanize()).ljust(15)

				if task.note:
					desc = task.task + ' *'
				else:
					desc = task.task

				if task.completed:
					if task.priority:
						priority = task.priority
					else:
						priority = ''
					task_id = Fore.WHITE + Style.BRIGHT + Back.WHITE + str(task.id).center(3)
					tags = str(task.tags) + Fore.RESET + Style.NORMAL + Back.RESET
					print template.format(task_id, desc, priority, due_date, age, tags)
				else:
					print template.format(task.id, desc, priority, due_date, age, task.tags)

			print self.legend
		else:
			print('\nThere are no tasks to display!\n')

	def show_tasks_by_priority(self, tasks=None, date_format=None):
		"""Display the tasks (in Priority order)

		:param tasks: tasks object
		"""

		low_dict_o = OrderedDict()
		med_dict_o = OrderedDict()
		high_dict_o = OrderedDict()
		no_dict_o = OrderedDict()
		completed_dict_o = OrderedDict()

		low_dict = {}
		med_dict = {}
		high_dict = {}
		no_dict = {}
		completed_dict = {}

		temp_dict = {}

		if not tasks:
			tasks = self.tasklist.tasks

		if len(tasks) > 0:
			for task in tasks:
				if task.due_date is None:
					due_date = ''
				else:
					if date_format:
						due_date = task.due_date.rsplit(' ', 1)[0].ljust(20)
					else:
						due_date = (arrow.get(task.due_date, task.due_date_format).humanize()).ljust(20)

				age = (str(task.creation_date).split()[0]).ljust(15)  # drop the time zone

				if task.note:
					desc = task.task + ' *'
				else:
					desc = task.task

				if task.completed:
					completed_dict[task.id] = task.priority, due_date, age, desc, task.tags
				elif task.priority == 'L':
					low_dict[task.id] = [task.priority, due_date, age, desc, task.tags]
				elif task.priority == 'M':
					med_dict[task.id] = [task.priority, due_date, age, desc, task.tags]
				elif task.priority == 'H':
					high_dict[task.id] = [task.priority, due_date, age, desc, task.tags]
				else:
					no_dict[task.id] = [task.priority, due_date, age, desc, task.tags]

		else:
			print('\nThere are no tasks to display!\n')
			return

		for key, value in sorted(no_dict.items(), key=lambda e: e[1][1]):
			if value[1] is not '':
				no_dict_o[key] = value
			else:
				temp_dict[key] = value

		for key in temp_dict:
			no_dict_o[key] = temp_dict[key]

		temp_dict.clear()

		for key, value in sorted(low_dict.items(), key=lambda e: e[1][1]):
			if value[1] is not '':
				low_dict_o[key] = value
			else:
				temp_dict[key] = value

		for key, value in temp_dict.items():
			low_dict_o[key] = value

		temp_dict.clear()

		for key, value in sorted(med_dict.items(), key=lambda e: e[1][1]):
			if value[1] is not '':
				med_dict_o[key] = value
			else:
				temp_dict[key] = value

		for key, value in temp_dict.items():
			med_dict_o[key] = value

		temp_dict.clear()

		for key, value in sorted(high_dict.items(), key=lambda e: e[1][1]):
			if value[1] is not '':
				high_dict_o[key] = value
			else:
				temp_dict[key] = value

		for key, value in sorted(temp_dict.items(), key=lambda e: e[1][1]):
			high_dict_o[key] = value

		temp_dict.clear()

		for key, value in sorted(completed_dict.items(), key=lambda e: e[1][1]):
			if value[1] is not '':
				completed_dict_o[key] = value
			else:
				temp_dict[key] = value

		for key, value in temp_dict.items():
			completed_dict_o[key] = value

		temp_dict.clear()

		del low_dict
		del med_dict
		del high_dict
		del no_dict
		del completed_dict

		today = arrow.now()

# TODO: Figure out why the key is a tuple instead of a list

		for dict in [low_dict_o, med_dict_o, high_dict_o, no_dict_o]:
			for key, value in dict.items():
				dict[key] = list(dict[key])  # hack - how is this key a tuple!?!
				if value[0] == 'L':
					dict[key][0] = Fore.YELLOW + Style.BRIGHT + value[0].center(3) + Fore.RESET + Style.NORMAL
				elif value[0] == 'M':
					dict[key][0] = Fore.BLUE + Style.BRIGHT + value[0].center(3) + Fore.RESET + Style.NORMAL
				elif value[0] == 'H':
					dict[key][0] =  Fore.RED + Style.BRIGHT + value[0].center(3) + Fore.RESET + Style.NORMAL
				else:
					dict[key][0] = ''

				task = self.tasklist.find_task(key)
				if task.due_date:
					diff = arrow.get(task.due_date, task.due_date_format) - today
					if diff.days >= 1 and diff.seconds > 0:
						dict[key][1] = Fore.CYAN + Style.BRIGHT + value[1] + Fore.RESET + Style.NORMAL
					elif diff.days >= 0:
						dict[key][1] = Fore.BLUE + Style.BRIGHT + value[1] + Fore.RESET + Style.NORMAL
					elif diff.days <= 0:
						dict[key][1] = Fore.RED + Style.BRIGHT + value[1] + Fore.RESET + Style.NORMAL

		template = '{0:^3} {1:20} {2:^3} {3:20} {4:15} {5:20}'
		print template.format('\nPri', 'Description', 'ID', 'Due', 'Created', 'Tags')
		print template.format('---', '--------------------', '---', '--------------------', '---------------',
		                      '--------------------')

		if len(high_dict_o) > 0:
			for key in high_dict_o:
				print template.format(high_dict_o[key][0], high_dict_o[key][3], key, high_dict_o[key][1],
				                      high_dict_o[key][2], high_dict_o[key][4])
		if len(med_dict_o) > 0:
			for key in med_dict_o:
				print template.format(med_dict_o[key][0], med_dict_o[key][3], key, med_dict_o[key][1],
				                      med_dict_o[key][2], med_dict_o[key][4])
		if len(low_dict_o) > 0:
			for key in low_dict_o:
				print template.format(low_dict_o[key][0], low_dict_o[key][3], key, low_dict_o[key][1],
				                      low_dict_o[key][2], low_dict_o[key][4])
		if len(no_dict_o) > 0:
			for key in no_dict_o:
				print template.format(no_dict_o[key][0], no_dict_o[key][3], key, no_dict_o[key][1],
				                      no_dict_o[key][2], no_dict_o[key][4])

		completed_template = Fore.WHITE + Style.BRIGHT + Back.WHITE + '{0:^3} {1:20} {2:^3} {3:20} {4:15} {5:20}' + \
		                     Fore.RESET + Style.NORMAL + Back.RESET
		if len(completed_dict_o) > 0:
			for key in completed_dict_o:
				if completed_dict_o[key][0]:
					priority = completed_dict_o[key][0]
				else:
					priority = ''
				print completed_template.format(priority, completed_dict_o[key][3], key, completed_dict_o[key][1],
				                                completed_dict_o[key][2], completed_dict_o[key][4])
		print self.legend

	def show_task(self, task_id):
		"""Display the specified task, including its notes, if any.

		:param str task_id: the task_id of the task.
		"""

		task_id = self._validate_task_id(task_id)
		if task_id:
			task = self.tasklist.find_task(task_id)
			if task:
				if task.priority == 'L':
					priority = Fore.YELLOW + Style.BRIGHT + ' ' + task.priority + ' ' + Fore.RESET + Style.NORMAL
				elif task.priority == 'M':
					priority = Fore.BLUE + Style.BRIGHT + ' ' + task.priority + ' ' + Fore.RESET + Style.NORMAL
				elif task.priority == 'H':
					priority = Fore.RED + Style.BRIGHT + ' ' + task.priority + ' ' + Fore.RESET + Style.NORMAL
				else:
					priority = ''
				template = '{0:^3} {1:^3} {2:20} {3:40}'
				print template.format('\nID', ' Pri', 'Description', 'Note')
				print template.format('---', '---', '--------------------',
				                      '----------------------------------------')
				print template.format(task.id, priority, task.task, task.note)

	def search_tasks(self, search_string):
		"""Search the task list for a task whose contents contains the user provided search string.

		:param str search_string:    the string to search for.
		"""

		tasks = self.tasklist.search(search_string.lower())
		if tasks:
			self.show_tasks(tasks)
		else:
			print('\nThere were no tasks containing "{}".\n'.format(search_string))

	def add_task(self, task, priority=None, due_date=None, tags=None, note=None):
		"""Add a new task."""

		self.tasklist.add_task(task, priority, due_date, tags, note)

	def delete_task(self, task_id):
		"""Delete a task."""

		task_id = self._validate_task_id(task_id)
		if task_id:
			self.tasklist.delete_task(task_id)
			self.tasklist.renumber_tasks()
			print('Task ' + task_id + ' was deleted.')

	def modify_task(self, task_id, task_=None, completed=False, priority=None, due_date=None, note=None, tags=None, time=None):
		"""Modify a task."""

		task_id = self._validate_task_id(task_id)
		if task_id:
			task = self.tasklist.find_task(task_id)
			if task:
				print 'Modifying task ' + str(task_id) + ': ' + task.task
				if task_:
					task.task = task_
				elif priority:
					task.priority = priority
				elif due_date:
					if isinstance(due_date, list):
						task.due_date = due_date[0]
						task.due_date_format = due_date[1]
					else:
						task.due_date = due_date
				elif note:
					task.note = note
				elif tags:
					task.tags = tags
				elif time:
					time_str = time.split(' ')[0]
					time_hour, time_minute = time_str.split(':')
					if 'PM' in time:
						time_hour = int(time_hour) + 12
					due_date = arrow.get(task.due_date, task.due_date_format)
					due_date = due_date.replace(hour=time_hour, minute=int(time_minute))
					task.due_date = due_date.format(task.due_date_format)
				elif completed:
					task.completed = True
				print 'Modified task ' + str(task_id)

	def load_tasks(self, task_file):
		"""Load the task file and retrieve the tasks."""

		self.tasklist.tasks = util.load(task_file)
		Task.last_id = len(self.tasklist.tasks)

	def save_tasks(self, task_file):
		"""Save the task file."""

		util.save(self.tasklist.tasks, task_file)

	def _validate_task_id(self, task_id):
		"""Validate a task id.

		:return: None if an invalid ID was provided, otherwise a string containing the valid task id.
		"""

		if task_id.isdigit() and int(task_id) <= len(self.tasklist.tasks):
			return task_id
		else:
			print('{} is not an existing task!'.format(task_id))
			return None