Exemplo n.º 1
0
    def __init__(self, workflow_spec, **kwargs):
        """
        Constructor.
        """
        assert workflow_spec is not None
        self.spec = workflow_spec
        self.task_id_assigner = TaskIdAssigner()
        self.attributes = {}
        self.outer_workflow = kwargs.get('parent', self)
        self.locks = {}
        self.last_task = None
        self.task_tree = Task(self, specs.Simple(workflow_spec, 'Root'))
        self.success = True
        self.debug = False

        # Events.
        self.completed_event = Event()

        # Prevent the root task from being executed.
        self.task_tree.state = Task.COMPLETED
        start = self.task_tree._add_child(self.spec.start)

        self.spec.start._predict(start)
        if not kwargs.has_key('parent'):
            start.task_spec._update_state(start)
Exemplo n.º 2
0
 def checkScore(agent, taskgrid):
     if taskgrid.cells[agent.row][agent.col] == 1:
         for b in TaskList.TaskList:
             if b.row == agent.row and b.col == agent.col:
                 agent.earn_score()
                 b.removeTask()
                 Task.crateTask(agent.grid, taskgrid)
Exemplo n.º 3
0
def newtask(id):
    task = Task(id)

    if task.width != 1080 and task.width != 720:
        print('分辨率'+str(task.width)+',不支持,联系开发')
    else:
        while True:
            try:
                task.thumb()
                time.sleep(10)
            except KeyboardInterrupt:
                raise
            except Exception as e:
                print('出异常了,重启中。。。')
                print(e)
                traceback.print_exc()
                time.sleep(5)
                task.android.ClickReturn()
                time.sleep(5)
                task.android.ClickReturn()
                time.sleep(5)
                task.android.ClickReturn()
                time.sleep(5)
                task.android.ClickReturn()
                time.sleep(5)
                task.android.ClickReturn()
                time.sleep(5)
                task.android.WX()
                time.sleep(10)
Exemplo n.º 4
0
def resetProgram():
    """This will reset the program"""
    global currentTaskActions, tasks, shellCoords, currentPos
    currentTaskActions = []
    tasks = ['t']
    fakeActions = [('drive', 50), ('turn', 90), ('drive', 50), ('turn', 90),
                   ('drive', 50), ('turn', 90), ('drive', 50), ('turn', 90)]
    #shellCoords = shellConfigArray[0]
    ##    move blocks at start: Coors are now real
    moveBlocks = Task('move starting blocks', [(12, 17), (24, 20)], [1, 1])
    #tasks.append(moveBlocks)
    #currentTaskActions = moveBlocks.generatePath(pathPlanner, currentPos)
    currentPos = (24, 20)
    currentTaskActions = fakeActions
    rospy.loginfo(currentTaskActions)
    ##    close doors command
    closeDoor = Task('close doors', [(45, 20), (33, 33)], [1, 2])
    #tasks.append(closeDoor)
    ##   adding shells
    for coord in shellCoords:
        shellTask = Task('pick up shell {}'.format(shellCoords.index(coord)),
                         [coord], [4])
        tasks.append(shellTask)
    rospy.loginfo("******************************")
    rospy.loginfo("TASK ID \t NAME")
    """
Exemplo n.º 5
0
def build():
    task1 = Task("Finish testing Code", "", 15, 3, 3, 2018)
    task2 = Task("Commit to GIT", "Git Gud", 12, 3, 3, 2018)
    task3 = Task()

    #Tests writing to JSON File
    writer = TaskWriter("def.json")
    writer.writeToJSON([task1, task2, task3])
    writer.closeFile()

    #Tests conversion of JSON to string, for conversion from JSON to another file
    reader = TaskReader("def.json")
    JSON2strTest = reader.JSONtoString()
    print("{0}".format(JSON2strTest))
    reader.closeFile()

    #Writes JSON string to a file
    writer2 = TaskWriter("jsonOutput.txt")
    writer2.writeToText(JSON2strTest)

    #tests conversion of JSON data back into Task Class, prints to show results
    reader2 = TaskReader("def.json")
    readInTasks = reader2.readFromJSON()
    reader2.closeFile()
    for task in readInTasks:
        print("{0}".format((task.toString())))
Exemplo n.º 6
0
 def __setattr__(self, name, value):
     if name in self._data_adverbs:
         prefix = name.replace('data', '')
         Task.__setattr__(self, prefix + 'name', value.name)
         Task.__setattr__(self, prefix + 'class', value.klass)
         Task.__setattr__(self, prefix + 'disk', value.disk)
         Task.__setattr__(self, prefix + 'seq', value.seq)
     else:
         # We treat 'infile', 'outfile' and 'outprint' special.
         # Instead of checking the length of the complete string,
         # we only check the length of the final component of the
         # pathname.  The backend will split of the direcrory
         # component and use that as an "area".
         attr = self._findattr(name)
         #file_adverbs = ['infile', 'outfile', 'outprint']
         if attr in self._file_adverbs and type(value) == str and \
                os.path.dirname(value):
             if len(os.path.basename(value)) > self._strlen_dict[attr] - 2:
                 msg = "string '%s' is too long for attribute '%s'" \
                       % (value, attr)
                 raise ValueError, msg
             self.__dict__[attr] = value
         else:
             Task.__setattr__(self, name, value)
             pass
         pass
     return
Exemplo n.º 7
0
def json_task_post(scrumteam, jira_connection):

    body = '''
    {
	"jql": "filter=AWO-%s-Sprint-Task",
	            "startAt": 0,
            "maxResults" : 2000,
            "fields": [
            	"assignee",
            	"issuetype",
            	"status",
                "aggregateprogress"
            ]
    }
    ''' % scrumteam

    jira_connection.\
            setUserAndPass(userpsw).\
            setHeader().\
            setBody(body)

    try:
        x = jira_connection.sendRequest()
    except Exception:
        raise

    task = Task(json.loads(x.decode()))

    return task.get_task()
Exemplo n.º 8
0
 def test_increase_cost(self):
     task = Task('test_task', 50, 50, None)
     cost = 50
     for i in range(100, 150):
         cost += i
         task.increase_cost(i)
         self.assertTrue(task.actual_cost == cost)
Exemplo n.º 9
0
 def __init__(self, engine, controlnum, samprate=44100):
   Task.__init__(self)
   self.engine = engine
   self.controlnum = controlnum
   devnum = self.engine.input.controls.micDevice[controlnum]
   if devnum == -1:
     devnum = None
     self.devname = pa.get_default_input_device_info()['name']
   else:
     self.devname = pa.get_device_info_by_index(devnum)['name']
   self.mic = pa.open(samprate, 1, pyaudio.paFloat32, input=True, input_device_index=devnum, start=False)
   if Config.get('game', 'use_new_pitch_analyzer') or not have_pypitch:
     self.analyzer = Analyzer(samprate)
   else:
     self.analyzer = pypitch.Analyzer(samprate)
   self.mic_started = False
   self.lastPeak    = 0
   self.detectTaps  = True
   self.tapStatus   = False
   self.tapThreshold = -self.engine.input.controls.micTapSensitivity[controlnum]
   self.passthroughQueue = []
   passthroughVolume = self.engine.input.controls.micPassthroughVolume[controlnum]
   if passthroughVolume > 0.0:
     Log.debug('Microphone: creating passthrough stream at %d%% volume' % round(passthroughVolume * 100))
     self.passthroughStream = Audio.MicrophonePassthroughStream(engine, self)
     self.passthroughStream.setVolume(passthroughVolume)
   else:
     Log.debug('Microphone: not creating passthrough stream')
     self.passthroughStream = None
Exemplo n.º 10
0
 def __init__(self, goal):
     Task.__init__(self)
     self.goal = goal
     self.path_request = None
     self.path = deque()
     self.stuck = False
     self.update = self.__request_path
Exemplo n.º 11
0
 def __init__(self, engine, mic):
   Task.__init__(self)
   self.engine = engine
   self.channel = None
   self.mic = mic
   self.playing = False
   self.volume = 1.0
Exemplo n.º 12
0
    def check_pressure_sensors(self):
        # Check pressure sensors
        for sensor in self.sensors.get_type('pressure').values():
            # If the sensor's status is unsafe...
            if sensor.status != SensorStatus.SAFE:
                # Warn about the sensor's status
                self.telemetry.warn('sensor', sensor.to_json())

                # If the pressure is critically high...
                if sensor.status == SensorStatus.CRITICALLY_HIGH:
                    # Open the pressure relief valve
                    self.task_queue.put(
                        Task(
                            'set_valve_actuation', {
                                'type': 'solenoid',
                                'location': 'pressure_relief',
                                'actuation': ValveActuation(1, 0)
                            }))

            # If the sensor's status is fine...
            else:
                # If the pressure relief valve is open...
                if self.valves.get('solenoid',
                                   'pressure_relief').actuation.type == 1:
                    # Close the pressure relief valve
                    self.task_queue.put(
                        Task(
                            'set_valve_actuation', {
                                'type': 'solenoid',
                                'location': 'pressure_relief',
                                'actuation': ValveActuation(0, 0)
                            }))
Exemplo n.º 13
0
def search(problem, optimizer, output, script, launch_delay,
           parallelism, points_init, points_max):
    print("search start:")

    # Create the initial sample points
    points = optimizer.ask(n_points=points_init)

    # Number of tasks submitted so far:
    task_count = 0
    # Number of tasks running in the background
    tasks_running = 0

    # Map from PID to (params, Task object)
    # Need to hold these references or Popen objects are garbage-collected
    pids = {}

    # Once we find a failure, we stop producing new tasks
    success = True

    while True:

        jsons = create_list_of_json_strings(points, problem.params)
        for i, json in enumerate(jsons):
            # Note: this puts the task in a background process
            global logger
            T = Task(logger, output, script,
                     parallelism, number=task_count, params=json)
            status = T.go()
            if not status:
                success = False
                break
            pids[T.process.pid] = (points[i], T)
            task_count += 1
            tasks_running += 1
            time.sleep(launch_delay)
        print("tasks_running: ", tasks_running)
        if tasks_running == 0:
            break

        # Wait for exactly one task to complete, get its PID
        (pid, status) = os.wait()
        tasks_running -= 1
        if os.WEXITSTATUS(status):
            print("pid failed: ", pid)
            success = False

        # Look up the task and delete it from the dictionary
        (point, task) = pids[pid]
        del pids[pid]

        # Pass the result back to the optimizer
        result = read_val_loss(output, task)
        optimizer.tell(point, result)

        # Create another sample point (if not exhausted or failed)
        if task_count < points_max and success:
            points = optimizer.ask(n_points=1)
        else:
            points = []
    return success
Exemplo n.º 14
0
    def __init__(self, name, **kwds):
        Task.__init__(self)
        self._name = name
        self._input_list = []
        self._output_list = []
        self._message_list = []

        # Optional arguments.
        if 'version' in kwds:
            self.version = kwds['version']

        # Update default user number.
        if self.userno == -1:
            self.userno = AIPS.userno

        # See if there is a proxy that can hand us the details for
        # this task.
        params = None
        for proxy in AIPS.proxies:
            try:
                inst = getattr(proxy, self.__class__.__name__)
                params = inst.params(name, self.version)
            except Exception, exception:
                if AIPS.debuglog:
                    print >>AIPS.debuglog, exception
                continue
            break
Exemplo n.º 15
0
    def __init__(self):
        Task.__init__(self)
        self.mouse                = pygame.mouse
        self.mouseListeners       = []
        self.keyListeners         = []
        self.systemListeners      = []
        self.priorityKeyListeners = []
        self.controls             = Controls()
        self.disableKeyRepeat()

        # Initialize joysticks
        pygame.joystick.init()
        self.joystickAxes = {}
        self.joystickHats = {}

        self.joysticks = [pygame.joystick.Joystick(id) for id in range(pygame.joystick.get_count())]
        for j in self.joysticks:
            j.init()
            self.joystickAxes[j.get_id()] = [0] * j.get_numaxes() 
            self.joystickHats[j.get_id()] = [(0, 0)] * j.get_numhats() 
        Log.debug("%d joysticks found." % (len(self.joysticks)))

        # Enable music events
        Audio.Music.setEndEvent(MusicFinished)

        # Custom key names
        self.getSystemKeyName = pygame.key.name
        pygame.key.name       = self.getKeyName
Exemplo n.º 16
0
 def __init__(self, engine, mic):
     Task.__init__(self)
     self.engine = engine
     self.channel = None
     self.mic = mic
     self.playing = False
     self.volume = 1.0
Exemplo n.º 17
0
 def initiate_task(self, file_path):
     template = loadJsonFile(path=file_path)
     task = Task(template)
     task.description["initiator"] = self.xmpp_id
     task.description["identifier"] = str(hex(uuid.getnode()))
     raw_contract_source = requests.get(task.description["contract"]).text
     compiled_contract = compile_source(raw_contract_source)
     task_contract_interface = compiled_contract['<stdin>:' +
                                                 task.description["task"]]
     w3 = Web3(Web3.HTTPProvider(task.description["blockchain_node"]))
     task_contract = w3.eth.contract(
         abi=task_contract_interface['abi'],
         bytecode=task_contract_interface['bin'])
     # have to come up with a better method to handle accounts.
     tx_hash = task_contract.constructor().transact(
         transaction={
             'from': w3.eth.accounts[0],
             'gas': 1000000
         })
     tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
     task_contract_address = tx_receipt.contractAddress
     # set up an event listener on the block chain
     network_delegation_event = task_contract.eventFilter('network_delegate_registered',\
                                                          {'fromBlock':0, 'toBlock':'latest'})
     self.blockChainEvents.append(network_delegation_event)
     print("address of deployed task contract is {}".format(
         task_contract_address))
     task.description["task_contract_address"] = task_contract_address
     payload = dict(setup="resource_solicitation", msg_type="task_template", \
                    payload=json.dumps(template))
     self.broadcast_queue.put(payload)
Exemplo n.º 18
0
def schrage_pmtn(tasks: List[Task]):
    ready = set()
    Cmax = 0
    not_ready = set(tasks)
    l = Task(0, 0, sys.maxsize, -1)
    t = min(task.get_r() for task in not_ready)
    while ready or not_ready:
        while not_ready and min(task.get_r() for task in not_ready) <= t:
            e = min(not_ready, key=Task.get_r)
            ready.add(e)
            not_ready.remove(e)
            if e.get_q() > l.get_q():
                l = l.copy().change_p(t - e.get_r()) ##tutaj byla zmiana na z kopia
                t = e.r
                if l.p > 0:
                    ready.add(l)

        if not ready:
            t = min(task.get_r() for task in not_ready)
        else:
            e = max(ready, key=Task.get_q)
            ready.remove(e)
            l = e
            t += e.p
            Cmax = max(Cmax, t + e.q)
    return Cmax
Exemplo n.º 19
0
    def test_sort_backlog_alphanumeric(self):
        StorageDouble.reset()
        #            [Summary, id, due_date]
        tasksTruth = [["Task1", 1, 9],
                      ["Task2", 2, 8],
                      ["Task3", 3, 7],
                      ["Task4", 4, 6],
                      ["Taske", 5, None],
                      ["Taskd", 6, None],
                      ["Taskc", 7, None],
                      ["Taskb", 8, None],
                      ["Taska", 9, None]]

        # Add some tasks and set due dates
        for truth in tasksTruth:
            task = Task(truth[0], "", 0)
            task.id = truth[1]
            task.set_due_date(truth[2])
            StorageDouble.add_task(task)

        # Verify they get sorted correctly
        self.assertTrue(self._runTsk('sort_backlog -a'))
        idOrderTruth = [4, 3, 2, 1, 9, 8, 7, 6, 5]
        idOrder = [ t.id for t in StorageDouble.tasks ]
        self.assertEquals(idOrderTruth, idOrder)
Exemplo n.º 20
0
  def __init__(self):

    self.logClassInits = Config.get("game", "log_class_inits")
    if self.logClassInits == 1:
      Log.debug("Input class init (Input.py)...")
  
    Task.__init__(self)
    self.mouse                = pygame.mouse
    self.mouseListeners       = []
    self.keyListeners         = []
    self.systemListeners      = []
    self.priorityKeyListeners = []
    self.controls             = Controls()
    self.disableKeyRepeat()

    # Initialize joysticks
    pygame.joystick.init()
    self.joystickAxes = {}
    self.joystickHats = {}

    self.joysticks = [pygame.joystick.Joystick(id) for id in range(pygame.joystick.get_count())]
    for j in self.joysticks:
      j.init()
      self.joystickAxes[j.get_id()] = [0] * j.get_numaxes() 
      self.joystickHats[j.get_id()] = [(0, 0)] * j.get_numhats() 
    Log.debug("%d joysticks found." % (len(self.joysticks)))

    # Enable music events
    Audio.Music.setEndEvent(MusicFinished)

    # Custom key names
    self.getSystemKeyName = pygame.key.name
    pygame.key.name       = self.getKeyName
Exemplo n.º 21
0
	def new_trainings(self):
		co = False
		for cert in self.requiredcertifications:
			if cert in self.certifications:  # this only adds the has expired
				if self.certifications[cert] > self.requiredcertifications[cert]:
					print(self.certifications[cert])
					pass
				else:
					print(cert)
					co = True
					training_task = Task(project_id=111111,
										 deadline=datetime.datetime.today() + datetime.timedelta(days=7),
										 creator=self.zenbotid, dur_estim=datetime.timedelta(seconds=600), importance=2,
										 effort=0, category='training', description={'title': cert, 'description': str(
							self.requiredcertifications[cert])})
			else:
				print(cert)
				co = True
				training_task = Task(project_id=111111, deadline=datetime.datetime.today() + datetime.timedelta(days=7),
									 creator=self.zenbotid, dur_estim=datetime.timedelta(seconds=600), importance=2,
									 effort=0, category='training',
									 description={'title': cert, 'description': str(self.requiredcertifications[cert])})

			if co:
				# print('Added task for ' + cert)
				self.tasks.append(training_task)
Exemplo n.º 22
0
 def test_add(self):
     t1 = Task(foo=1)
     t2 = Task(bar=2)
     p1 = Path([t1])
     p2 = Path([t2])
     self.assertEqual((p1 + p2).get_tasks(), [t1, t2])
     self.assertEqual((p2 + p1).get_tasks(), [t2, t1])
Exemplo n.º 23
0
def taskEditPost(handler, ids, p_hours, p_status, p_goal, p_assigned=[], p_include={}):
    handler.title("Edit tasks")
    requirePriv(handler, "Write")

    allIDs = map(int, uniq(ids.split(",")))
    ids = map(lambda i: to_int(i, "include", ErrorBox.die), p_include.keys())
    if not set(ids) <= set(allIDs):
        ErrorBox.die("Included tasks don't match query arguments")

    tasks = dict((id, Task.load(id)) for id in ids)
    if not all(tasks.values()):
        ids = [str(id) for (id, task) in tasks.iteritems() if not task]
        ErrorBox.die(
            "No %s with %s %s"
            % ("task" if len(ids) == 1 else "tasks", "ID" if len(ids) == 1 else "IDs", ", ".join(ids))
        )
    tasks = [tasks[id] for id in ids]
    if len(set(task.sprint for task in tasks)) > 1:
        ErrorBox.die("All tasks must be in the same sprint")
    sprint = (tasks[0] if len(tasks) > 0 else Task.load(allIDs[0])).sprint
    if sprint.isHidden(handler.session["user"]):
        ErrorBox.die(
            "No %s with %s %s"
            % ("task" if len(ids) == 1 else "tasks", "ID" if len(ids) == 1 else "IDs", ", ".join(ids))
        )
    if not sprint.canEdit(handler.session["user"]):
        ErrorBox.die("You don't have permission to modify this sprint")

    assignedids = set(to_int(i, "assigned", ErrorBox.die) for i in p_assigned)

    changes = {
        "assigned": False if assignedids == set() else {User.load(assignedid) for assignedid in assignedids},
        "hours": False if p_hours == "" else int(p_hours),
        "status": False if p_status == "" else p_status,
        "goal": False if p_goal == "" else Goal.load(int(p_goal)),
    }

    if changes["assigned"] and not all(changes["assigned"]):
        ErrorBox.die("Invalid assignee")
    if changes["assigned"] and not set(changes["assigned"]).issubset(sprint.members):
        ErrorBox.die("Unable to assign tasks to non-sprint members")
    if changes["goal"] and changes["goal"].sprint != sprint:
        ErrorBox.die("Unable to set goal to a goal outside the sprint")

    changed = set()
    for task in tasks:
        for field, value in changes.iteritems():
            if value is not False and getattr(task, field) != value:
                setattr(task, field, value)
                changed.add(task)
                Event.taskUpdate(handler, task, field, value)

    if len(changed) == 0:
        delay(handler, WarningBox("No changes necessary", close=3, fixed=True))
    else:
        for task in changed:
            task.saveRevision(handler.session["user"])
        delay(handler, SuccessBox("Updated %d %s" % (len(changed), "task" if len(changed) == 1 else "tasks")))
    redirect("/sprints/%d" % sprint.id)
Exemplo n.º 24
0
    def InitActions(self):
        impression = Task()
        talk = Task()

        impression.set_c_attribute("Pre", self)

        self.__actions["Impression"] = impression
        self.__actions["Talk"] = talk
 def __init__(self, server, command):
     Task.__init__(self)
     self.server= server
     self.command=command
     
     self.name="ExecuteRemoteWinCommandTask"
     self.description= "this task is used to execute command on remote machine through rpyc"
     self.stat=TaskStatus.RUNNING
Exemplo n.º 26
0
def createTask(data):
    parts = data.data.split("|")
    #print(parts)
    #taskType, sender, recipient, payLoad, location, modifier
    task = Task(parts[0], parts[1], parts[2], parts[3], parts[4],
                int(parts[5]), False, data.data)
    task.printTask()
    return task
Exemplo n.º 27
0
 def addTask(self, ID, time, nodes):
     """ Create a task object to be released at specific time step,
     made up of different nodes and time at each node. Assign unique 
     ID for differentiation.
     """
     taskAdd = Task(ID, time, nodes)
     self.tasks[self.totalTasks] = taskAdd
     self.totalTasks = self.totalTasks + 1
     print("Job at time step", taskAdd.getTime(), "created.")
Exemplo n.º 28
0
def importTasks():

# ---  Read tasks from files.	
	global taskList,resourceFileName,taskFileName,dependencyFileName
	global resources
	fptasks = open(taskFileName,"r")#"tasks.txt","r")

	for line in fptasks.readlines():		
		newTask = Task()
		t = line.split(",")	
		newTask.name = t[1]		
		newTask.id = int(t[0])
		newTask.duration = int(t[2])
		adjacencyList[newTask.id] = []
		taskList.append(newTask)	
	fptasks.close()			

#---- Read resources
	fpresources = open(resourceFileName,"r")#("resources.txt","r")
	
	for line in fpresources.readlines():
		r = line.strip().split(",")
		newResource = Resource(int(r[0]),r[1])
		resources += [newResource]
				
	fpresources.close()

# ---- Read depedencies and create predecessor list -----
	fpdependencies = open(dependencyFileName,"r")#("dependencies.txt","r")	

	for line in fpdependencies.readlines():
		line = line.rstrip()
		print(line)		
		x = line.split(",")
		if(len(x)>1):
			task = getTaskFromId(int(x[0]))
			for i in range(1,len(x)):
				task.predecessors.append(int(x[i]))
		"""if len(x) >1:			
			z = x[1]		
			for task in taskList:
				if task.id == int(x[0]):			 					
					y = z.strip().split(",")	
					for b in y:
						task.predecessors.append(int(b))"""								
				#print(x[0],task.predecessor)
	fpdependencies.close()


# ---- Create successor list ----
	for succTask in taskList:
		#succTask = getTaskFromId()
		for predId in succTask.predecessors:
			task = getTaskFromId(predId)
			task.successors.append(succTask.id)
 			adjacencyList[task.id] = task.successors
Exemplo n.º 29
0
def newTaskPost(handler, p_group, p_name, p_goal, p_status, p_hours, p_assigned=[]):
    def die(msg):
        print msg
        done()

    requirePriv(handler, "User")
    handler.wrappers = False

    groupid = to_int(p_group, "group", die)
    group = Group.load(groupid)
    if not group or group.sprint.isHidden(handler.session["user"]):
        die("No group with ID <b>%d</b>" % groupid)

    sprint = group.sprint
    if not (sprint.isActive() or sprint.isPlanning()):
        die("Unable to modify inactive sprint")
    elif not sprint.canEdit(handler.session["user"]):
        die("You don't have permission to modify this sprint")

    if p_name.strip() == "":
        die("Task must have a non-empty name")

    assignedids = set(to_int(i, "assigned", die) for i in p_assigned)
    assigned = set(User.load(assignedid) for assignedid in assignedids)
    if assigned == set():
        assigned.add(handler.session["user"] if handler.session["user"] in sprint.members else sprint.owner)
    if not all(assigned):
        die("Invalid assignee")

    goalid = to_int(p_goal, "goal", die)
    if goalid != 0:
        goal = Goal.load(goalid)
        if not goal:
            die("No goal with ID <b>%d</b>" % goalid)
        if goal.sprint != group.sprint:
            die("Goal does not belong to the correct sprint")

    hours = to_int(p_hours, "hours", die)

    task = Task(groupid, group.sprintid, handler.session["user"].id, goalid, p_name, p_status, hours)
    task.assigned |= assigned
    task.save()

    handler.responseCode = 299
    delay(
        handler,
        """
<script type=\"text/javascript\">
$(document).ready(function() {
	$('#task%d').effect('highlight', {}, 3000);
});
</script>"""
        % task.id,
    )
    delay(handler, SuccessBox("Added task <b>%s</b>" % task.safe.name, close=3, fixed=True))
    Event.newTask(handler, task)
Exemplo n.º 30
0
    def test_open(self):
        task = Task("Task", "", 0)
        task.id = 1
        task.close()
        StorageDouble.add_task(task)

        self.assertTrue(self._runTsk('open 1'))
        self.assertTrue(StorageDouble.get_task(1).is_open())

        self.assertFalse(self._runTsk('open 2'))
Exemplo n.º 31
0
 def __init__(self, machinename, localfile, remotefile):
     Task.__init__(self)
     
     self.name="DownloadFileTask"
     self.description="This task is used to download file from rpyc server"
     self.stat=TaskStatus.RUNNING
     
     self.machinename=machinename
     self.localfile=localfile
     self.remotefile=remotefile
Exemplo n.º 32
0
    def test_task_clone(self):
        t1 = Task(a=1, b=2)
        t2 = t1.clone(b=3, c=4)

        self.assertEqual(t1.a, 1)
        self.assertEqual(t1.b, 2)

        self.assertEqual(t2.a, 1)
        self.assertEqual(t2.b, 3)
        self.assertEqual(t2.c, 4)
Exemplo n.º 33
0
 def newTask(self, name=None, estimated=None, tag=""):
   name = colored("Untitled","red") if name == None else name
   estimated = 0.0 if estimated == None else estimated
   try:
     self.pauseCurrentTask()
   except TaskNotFoundException as nte:
     pass
   t = Task({ "name": name, "tag": tag, "estimated": estimated, })
   t.start()
   Taskr.tasks.append(t)
Exemplo n.º 34
0
def createTask():
    queryJson = request.json
    # titleとcontentは必須パラメータ
    if not queryJson.keys() >= {"title", "content"}:
        return make_response(jsonify("{'error': 'Invalid parameter'}"), 400)

    newTask = Task(queryJson['title'], queryJson['content'],
                   float(queryJson.get('limit')))
    tasks.append(newTask)
    return make_response(newTask.getObject(), 201)
Exemplo n.º 35
0
 def initiate_task(self, file_path):
     template = loadJsonFile(path=file_path)
     task = Task(template)
     task.description["initiator"] = self.xmpp_id
     task.description["identifier"] = str(hex(uuid.getnode()))
     # self.send_remote(setup="resource_solicitation", msg_type="task_template",\
     #                  payload=json.dumps(template),sendto="*****@*****.**")
     print (task)
     payload = dict(setup="resource_solicitation", msg_type="task_template",\
                      payload=json.dumps(template))
     self.broadcast_queue.put(payload)
Exemplo n.º 36
0
    def test_close_reason(self):
        task = Task("Task", "", 0)
        task.id = 1
        task.open()
        StorageDouble.add_task(task)

        self.assertTrue(self._runTsk('close 1 --r=Reason'))
        self.assertTrue(StorageDouble.get_task(1).is_closed())
        self.assertEquals("Reason", StorageDouble.get_task(1).closed_reason)

        self.assertFalse(self._runTsk('close 2'))
Exemplo n.º 37
0
def complete_tasks_submit(listbox, object_list, window):
    selections = list(listbox.curselection())
    # print (listbox.get(selections[0]))
    # print (object_list[selections[0]].name)
    dates, subjects = Task.date_subject_finder("ToDoList.txt")
    completed_object_list = [
        object for i, object in enumerate(object_list)
        if i in selections and object.name not in subjects
    ]
    Task.make_it_complete("ToDoList.txt", completed_object_list)
    window.destroy()
    def createTask(self, sectionId, taskTitle, taskOrder):
        task = Task(title=taskTitle)

        task.save()

        taskId = task.id
        section = self.__getSectionById(sectionId)

        section.addTaskId(taskId, taskOrder)

        return taskId
Exemplo n.º 39
0
 def __getattr__(self, name):
     if name in self._data_adverbs:
         class _AIPSData: pass
         value = _AIPSData()
         prefix = name.replace('data', '')
         value.name = Task.__getattr__(self, prefix + 'name')
         value.klass = Task.__getattr__(self, prefix + 'class')
         value.disk = Task.__getattr__(self, prefix + 'disk')
         value.seq = Task.__getattr__(self, prefix + 'seq')
         return value
     return Task.__getattr__(self, name)
Exemplo n.º 40
0
 def __init__(self, tasks):
     Task.__init__(self, 0, "Bundle-", 0, 0, 0, [])
     self.tasks     = tasks  # The Tasks in the bundle.
     self.TasksMap  = {}     # Mappings of tasks to days.
     self.SkillsMap = {}     # Mappings of skill hours to days.
     self.contents  = []     # IDs of the tasks in the bundle.
     
     self.initialize(tasks)
     self.calculateDays(tasks)
     self.allocate()
     self.distribute(tasks)        
Exemplo n.º 41
0
 def __getattr__(self, name):
     if name in self._data_adverbs:
         class _AIPSData: pass
         value = _AIPSData()
         prefix = name.replace('data', '')
         value.name = Task.__getattr__(self, prefix + 'name')
         value.klass = Task.__getattr__(self, prefix + 'class')
         value.disk = Task.__getattr__(self, prefix + 'disk')
         value.seq = Task.__getattr__(self, prefix + 'seq')
         return value
     return Task.__getattr__(self, name)
Exemplo n.º 42
0
    def addNewTaskFromLineEdit(self):
        title = self.addNewTaskLineEdit.text()
        self.addNewTaskLineEdit.deleteLater()

        if not title.isEmpty():
            task = Task(self)
            task.setTitle(title)
            self.addTask(task)
            self.saveState()

        self.isAddingTask = False
Exemplo n.º 43
0
def createTask():
    task = Task.get(request.json)
    session = get_session()
    lastTask = session.query(Task).order_by(Task.TaskId.desc()).first()
    task.TaskId = 1 if lastTask == None else lastTask.TaskId + 1
    try:
        session.add(task)
        session.flush()
    except:
        task = Task()
    return Response(json.dumps(task.to_dict()), mimetype='application/json')
Exemplo n.º 44
0
 def append_get_task(self, task_info_list):
     tasks = []
     now = datetime.datetime.now()
     timeslot = ((now.hour * 60 + now.minute) / 5 + 1) % 288
     for each in task_info_list:
         t = Task()
         t.source = ''
         t.content = ''
         t.timeslot = timeslot
         tasks.append(t)
     return tasks
Exemplo n.º 45
0
    def run(self):
        self.logger.debug('Scheduler Start')

        ## load and run tasks
        taskObj = Task(self.logger, self.config)
        taskObj.run()

        ## release lock
        self.lockObj.release()

        return (True)
Exemplo n.º 46
0
    def __init__(self, name, **kwds):
        """  Create AIPS task object
        
        Creates task object and calls server function to parse the
        task help and POPSDAT.HLP files to obtain task specific
        parametrs and documentation.
        Following is a list of class members:
        _default_dict   = Dictionary with default values of parameters
        _input_list     = List of input parameters in order
        _output_list    = List of output parameters in order
        _min_dict       = Parameter minimum values as a List
        _max_dict       = Parameter maximum values as a List
        _hlp_dict       = Parameter descriptions (list of strings)
                          as a dictionary
        _strlen_dict    = String parameter lengths as dictionary
        _help_string    = Task Help documentation as list of strings
        _explain_string = Task Explain documentation as list of strings
        _short_help     = One line description of task
        _message_list   = list of execution messages
        Current parameter values are given as class members.
        """
        if not self._task_type:
            self._task_type = 'AIPS'
        Task.__init__(self)
        self._name = name
        self._input_list = []
        self._output_list = []
        self._message_list = []
        self._remainder = ""     # Partial message buffer
        # Optional arguments.
        if 'version' in kwds:
            self.version = kwds['version']
        else:
            if 'AIPS_VERSION' in os.environ:
                self.version = os.environ["AIPS_VERSION"]

        # Update default user number.
        if self.__class__.userno == 0:
            self.__class__.userno = AIPS.userno

        # See if there is a proxy that can hand us the details for
        # this task.
        params = None
        for proxy in AIPS.proxies:
            try:
                inst = getattr(proxy, self.__class__.__name__)
                params = inst.params(name, self.version)
            except Exception, exception:
                print exception
                if AIPS.debuglog:
                    print >>AIPS.debuglog, exception
                continue
            break
Exemplo n.º 47
0
 def __init__(self, engine, channel, fileName):
   Task.__init__(self)
   self.engine       = engine
   self.fileName     = fileName
   self.channel      = channel.channel
   self.playing      = False
   self.bufferSize   = 1024 * 64
   self.bufferCount  = 8
   self.volume       = 1.0
   self.buffer       = numpy.zeros((2 * self.bufferSize, 2), dtype = numpy.int16)
   self.decodingRate = 4
   self._reset()
Exemplo n.º 48
0
def load_samples(sample_csv):
    with open(sample_csv, 'rb') as f:
        reader = csv.reader(f, delimiter=',', quotechar='"')
        title = next(reader, None)
        samples = []
        sample_names = []
        for row in reader:
            task = Task()
            sample_names.append(row[0])
            task.from_list(row[1:])
            samples.append(task)
        return title, sample_names, samples
def create_task_in_project(id):
    global task_counter_id
    if not "task_name" in request.json or not "description" in request.json:
        abort(400)

    project = select_project_by_id(id)
    task_counter_id += 1
    task_name = request.json.get("task_name")
    description = request.json.get("description")
    task = Task(task_counter_id, task_name, description)
    project.add_task(task)
    return jsonify({"task_added": task.to_json()})
Exemplo n.º 50
0
 def __init__(self, engine, channel, fileName):
     Task.__init__(self)
     self.engine = engine
     self.fileName = fileName
     self.channel = channel.channel
     self.playing = False
     self.bufferSize = 1024 * 64
     self.bufferCount = 8
     self.volume = 1.0
     self.buffer = Numeric.zeros((2 * self.bufferSize, 2), typecode="s")
     self.decodingRate = 4
     self._reset()
Exemplo n.º 51
0
 def __init__(self, engine, geometry = None):
     Task.__init__(self)
     self.layers = []
     self.incoming = []
     self.outgoing = []
     self.visibility = {}
     self.transitionTime = 512.0
     self.geometry = geometry or glGetIntegerv(GL_VIEWPORT)
     self.savedGeometry = None
     self.engine = engine
     w = self.geometry[2] - self.geometry[0]
     h = self.geometry[3] - self.geometry[1]
     self.aspectRatio = float(w) / float(h)
Exemplo n.º 52
0
    def test_save_tasks_and_pomo(self):
        storage = Storage(TimeDouble())

        pomo = Pomo()
        storage.pomo = pomo

        task = Task("Task1", "Task1Description word\nMultiline", 1000)
        task.id = 1
        task.state = "Blocked"
        task.blocked_reason = "BlockedReason"
        storage.tasks.append(task)

        task = Task("Task2", "Task2Description", 1001)
        task.id = 2
        task.close(1002)
        storage.tasks.append(task)

        openDouble.reset()
        fileDouble = FileDouble()
        openDouble.add_file(fileDouble)

        storage.save('test_file')
        self.assertEqual('test_file', openDouble.filename[0])
        self.assertEqual('w+', openDouble.mode[0])
        self.assertEqual("""#### Task
## State: Blocked
## Blocked Reason
BlockedReason
## Closed Reason
## Id: 1
## Date Created: 1000
## Date Closed:
## Date Due:
## Time Estimate: 0
## Time Spent: 0
## Summary
Task1
## Description
Task1Description word
Multiline
#### Task
## State: Closed
## Blocked Reason
## Closed Reason
## Id: 2
## Date Created: 1001
## Date Closed: 1002
## Date Due:
## Time Estimate: 0
## Time Spent: 0
## Summary
Task2
## Description
Task2Description
#### Pomodoro
## Time Remaining: 1500.000000
## Running: false
""", fileDouble.written_data)
Exemplo n.º 53
0
 def run(self):
     self.running = True
     
     #start up our worker processes
     for i in xrange(self.numProcesses):
         process = multiprocessing.Process(target=TaskManagerServerWorker, args=(self.workQueue, self.activeWorkers))
         process.start()
         self.workerProcesses.append(process)
         time.sleep(0.25)
         
     while self.running:
         #if the queue is full, don't look for any more jobs for now
         with self.activeWorkers.get_lock():
             if self.activeWorkers.value >= self.numProcesses:
                 time.sleep(1)
                 continue
         
         nextTask = Task.findNextUnclaimedNoConflictTask(self.dbConfig)
         
         if nextTask == None:
             time.sleep(1)
             continue
         else:
             #queue the work
             self.workQueue.put(nextTask)
Exemplo n.º 54
0
    def __init__(self, engine, channel, fileName):
      Task.__init__(self)
      self.engine       = engine
      self.fileName     = fileName
      self.channel      = channel
      self.playing      = False
      self.bufferSize   = 1024 * 64
      self.bufferCount  = 8
      self.volume       = 1.0

        #myfingershurt: buffer is 2D array (one D for each channel) of 16-bit UNSIGNED integers / samples
        #  2*1024*64 = 131072 samples per channel
      self.buffer       = zeros((2 * self.bufferSize, 2))

      self.decodingRate = 4
      self._reset()
Exemplo n.º 55
0
	def getTasks(self, orderby = 'seq', includeDeleted = False):
		from Task import Task
		tasks = Task.loadAll(sprintid = self.id, orderby = orderby)
		# This is filtered here instead of in Task.loadAll to prevent loading old revisions
		if not includeDeleted:
			tasks = filter(lambda t: not t.deleted, tasks)
		return tasks
Exemplo n.º 56
0
def taskByID(context, id):
	id = to_int(id, 'id', fail)
	context['task'] = Task.load(id)
	if not context['task']:
		fail("No task with ID %d" % id)
	print context['task'].safe.name
	return ('task', "[task %d] $" % id)
Exemplo n.º 57
0
    def __init__(self, workflow_spec, **kwargs):
        """
        Constructor.
        """
        assert workflow_spec is not None
        self.spec             = workflow_spec
        self.task_id_assigner = TaskIdAssigner()
        self.attributes       = {}
        self.outer_workflow   = kwargs.get('parent', self)
        self.locks            = {}
        self.last_task        = None
        self.task_tree        = Task(self, specs.Simple(workflow_spec, 'Root'))
        self.success          = True
        self.debug            = False

        # Events.
        self.completed_event = Event()

        # Prevent the root task from being executed.
        self.task_tree.state = Task.COMPLETED
        start                = self.task_tree._add_child(self.spec.start)

        self.spec.start._predict(start)
        if not kwargs.has_key('parent'):
            start.task_spec._update_state(start)
Exemplo n.º 58
0
def newNoteModify(handler, taskid, id, p_action):
    handler.title("New Note")
    requirePriv(handler, "User")

    if p_action != "delete":
        ErrorBox.die("Invalid Action", "Unrecognized action <b>%s</b>" % p_action)

    taskid = int(taskid)
    task = Task.load(taskid)
    if not task or task.sprint.isHidden(handler.session["user"]):
        ErrorBox.die("Invalid Task", "No task with ID <b>%d</b>" % taskid)

    id = int(id)
    note = Note.load(id)
    if not note:
        ErrorBox.die("Invalid Note", "No note with ID <b>%d</b>" % noteid)
    elif note.task != task:  # Doesn't really matter, but shouldn't happen
        ErrorBox.die("Task mismatch", "Note/task mismatch")
    elif note.user != handler.session["user"]:
        ErrorBox.die("Permission denied", "Notes can only be deleted by their creators")

    note.delete()
    delay(handler, SuccessBox("Deleted note", close=3))
    Event.deleteNote(handler, note)
    redirect("/tasks/%d" % task.id)
Exemplo n.º 59
0
    def setUp(self):
        StorageDouble.reset()
        #            [Summary, id, due_date]
        tasksTruth = [["Task1", 1],
                      ["Task2", 2],
                      ["Task3", 3],
                      ["Task4", 4],
                      ["Task5", 5],
                      ["Task6", 6],
                      ["Task7", 7],
                      ["Task8", 8],
                      ["Task9", 9]]

        # Add some tasks and set due dates
        for truth in tasksTruth:
            task = Task(truth[0], "", 0)
            task.id = truth[1]
            StorageDouble.add_task(task)
Exemplo n.º 60
0
 def add(self, name, period, last):
     """Creates a new task."""
     signal.signal(signal.SIGINT, signal.SIG_IGN)
     signal.signal(signal.SIGTERM, signal.SIG_IGN)
     creation = datetime.datetime.utcnow()
     uid = float((creation - datetime.datetime(1970, 1, 1)).total_seconds())
     taskpath = Task.writexml(self.taskspath, str(uid), creation, name.encode("utf-8"), float(period), float(last))
     task = Task(taskpath)
     self.taskhash[task.uid] = task
     return task.uid