def test_job_seeker(self): result_1 = Job("random_input") answer_1 = result_1.job_seeker() result_2 = Job("testing123") answer_2 = result_2.job_seeker() self.assertIsInstance(answer_1, float) self.assertIsInstance(answer_2, float)
def main(): ''' This is main function which takes file containing jobs as input and prints whoever is doing job. :return: None. ''' cathy = GarageHeap(lambda x, y: x.cost > y.cost) howard = GarageHeap(lambda x, y: x.time < y.time) file = input("Enter the name of the file which contains garage jobs.") try: fileHandle = open(file) for line in fileHandle: line = line.strip() data = line.split() if len(data) == 3 and data[1].isnumeric() and data[2].isnumeric(): n = Job(data[0], int(data[1]), int(data[2])) cathy.insertHeap(n) howard.insertHeap(n) print(n) elif len(data) == 2 and (data[0] == 'Cathy' or data[0] == 'cathy') and data[1] == 'ready': job = cathy.popHeap() print("Cathy starting job", job.name) elif len(data) == 2 and (data[0] == 'Harold' or data[0] == 'harold') and data[1] == 'ready': job = howard.popHeap() print("Harold starting job", job.name) else: print("Invalid input, please try again with valid input.") sys.exit(0) except FileNotFoundError: print("please enter valid file name.") sys.exit(0)
def main(): garageObj = Garage() file = input("enter the name of the file which contains garage operation.") try: filehandle = open(file) for line in filehandle: line = line.strip() data = line.split() if len(data) == 3 and data[1].isnumeric() and data[2].isnumeric(): n = Job(data[0], int(data[1]), int(data[2])) garageObj.insertHeap(n) print(n) elif len(data) == 2 and data[0] == 'Cathy' and data[1] == 'ready': job = garageObj.popCathyHeap() print("Cathy starting job", job.name) elif len(data) == 2 and data[0] == 'Howard' and data[1] == 'ready': job = garageObj.popHowardHeap() print("Howard starting job", job.name) else: print("Invalid input.") sys.exit(0) except FileNotFoundError: print("please enter valid file name.") sys.exit(0)
def upload_file(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash("No file part") return render_template('dashboard/upload.html') user_file = request.files['file'] # if user does not select file, browser also # submit a empty part without filename if user_file.filename == '': flash("No file extension") return render_template('dashboard/upload.html') if not allowed_file(user_file.filename): flash("Invalid file extension") return render_template('dashboard/upload.html') if user_file and allowed_file(user_file.filename): filename = secure_filename(user_file.filename) path = os.path.join(app.config['UPLOAD_FOLDER'], filename) user_file.save(path) new_job = Job(path, 'black', 'PLA', current_user) waiting_q.put(new_job) flash("File uploaded succesfully") return render_template('dashboard/upload.html') return render_template('dashboard/upload.html')
async def test_enqueue_job(redis): job_repo = JobRepo(_redis=redis) job = Job(id='fake_id', task=asyncio.sleep, queue_id='test_queue') await job_repo.enqueue(job) assert bool(redis.exists(job.id)) is True assert await redis.llen(job.queue_id) != 0
async def test_get_job(redis): job_repo = JobRepo(_redis=redis) expected_job = Job(id='fake_id', task=asyncio.sleep, queue_id='test_queue') await job_repo.enqueue(expected_job) result_job = await job_repo.get(expected_job.queue_id) assert isinstance(result_job, Job) assert result_job == expected_job
async def test_execute_job_use_case(): async def task(): return 1 job = Job(task=task) use_case = ExecuteJobUseCase(job) result = await use_case.execute() assert result == 1
async def test_enqueue_job_successfully(): job = Job(id='fake_id') repo_mock = AsyncMock() use_case = EnqueueJobUseCase(job, _job_repo=repo_mock) await use_case.execute() assert job.id != 'fake_id' assert job.queued_time is not None repo_mock.enqueue.assert_called_once()
async def test_consumer_integration(redis): async def task(): return 1 queue = Queue(id='test_queue') job = Job(queue_id=queue.id, task=task) await EnqueueJobUseCase(job).execute() result = await ConsumeQueue(queue).execute() assert result == 1
def start_job(s): s.cancel_job() log.info("PR %s: queueing build of commit %s", s.url, s.head) env = { "CI_PULL_COMMIT": s.head, "CI_PULL_REPO": s.repo, "CI_PULL_BRANCH": s.branch, "CI_PULL_NR": str(s.nr), "CI_PULL_URL": s.url, "CI_PULL_TITLE": s.title, "CI_PULL_USER": s.user, "CI_BASE_REPO": s.base_repo, "CI_BASE_BRANCH": s.base_branch, "CI_BASE_COMMIT": s.base_commit, "CI_SCRIPTS_DIR": config.scripts_dir, "CI_PULL_LABELS": ";".join(sorted(list(s.labels))), "CI_BUILD_HTTP_ROOT": os.path.join(config.http_root, s.base_full_name, str(s.nr), s.head), } if s.mergeable: env["CI_MERGE_COMMIT"] = s.merge_commit for key, value in env.items(): if not value: log.warning("PR %s: env %s has NoneType!", s.url, key) return s s.current_job = Job(s.get_job_path(s.head), os.path.join(config.scripts_dir, "build.sh"), env, s.job_hook, s.head) s.jobs.append(s.current_job) queue.put(s.current_job) s.current_job.set_state(JobState.queued) return s
def list_jobs(self): """ For each job found in the details dict, a new Job object is initialized and added to the self.jobs list. :returns jobs: List of Job objects """ jobs = [] for job in self.details['jobs']: instance = Job(job['name'], job['color'], url=self.url, auth=self.auth, verify=self.verify) jobs.append(instance) self.jobs = jobs return jobs
def __init__(self): self.client = zulip.Client(site="https://rhtp.zulipchat.com/api/") self.subscribe_all() self.chatbot = ChatBot( "Test", trainer='chatterbot.trainers.ChatterBotCorpusTrainer') #self.chatbot.train("chatterbot.corpus.english") #self.chatbot.train("chatterbot.corpus.english.greetings") #self.chatbot.train("chatterbot.corpus.english.conversations") self.currency = curr() #self.lat_lon = latlon() self.language = Lang() self.restaurants = Rest() self.bus_stations = Bus() self.tourist_places = Tour() self.jobs = Job() self.directions = Direct() self.atm = Atm() self.subkeys = [ "currency", "language", "restaurant", "bus", "tourist", "job", "direction", "atm" ]
def create_jobs(self): jobs = [] # jobs cj = self.counter() #hyperperiod = get_hyperperiod(self.tasks) for time in range(0, self.stop_point): for task in self.tasks: if (time - task.offset ) % task.period == 0 and time >= task.offset: start = time end = start + task.period priority_1 = task.priority_1 priority_2 = task.priority_2 wcet = task.computation_time task_id = task.task_id s = start + task.s jobs.append( Job(start, end, wcet, task_id, cj[task.task_id], priority_1, priority_2, s)) cj[task.task_id] += 1 #print(jobs) return jobs
def read_jobs_from_file_merged(path_to_file): """ Reads jobs from the given file. Expected format (prefix, infix or suffix whitespaces are allowed): 1 14 2 6 3 17 2 5 3 21 1 10 Format semantics: <machine job1/op1> <time job1/op1> <machine job1/op1> <time job1/op2> ... <machine job2/op1> <time job2/op1> ... Keyword arguments: path_to_file -- relative path to the text file to be parsed Returns: list of jobs, read from the file """ with open(path_to_file, "r") as f: jobs = list() for line in f: normalised_line = re.sub(r"(^\s*)|(\s*$)", "", line) split_line = re.split(r"\s+", normalised_line) if len(split_line) % 2 != 0: print("Failed to parse \"" + path_to_file + "\" as a job contains an odd number of values!") sys.exit(1) job = Job() for (machine, time) in zip(split_line[::2], split_line[1::2]): op = Operation(int(time), int(machine)) job.add_operation(op) jobs.append(job) return jobs
def add_to_current_jobs(self, created_job: List[Action]): """Add the list of actions sent to the jobs window, and then perform the actions in the order created. Parameters ---------- created_job : List[Action] - List of actions that should be performed. """ job = Job(created_job, self.job_index) scroll_area_widget = self.jobsScrollAreaWidgetContents job_progress_widget = JobProgressWidget(scroll_area_widget, created_job, self.job_index, self) scroll_layout = self.jobsScrollAreaWidgetContents.layout() index_to_add = scroll_layout.count() - 1 scroll_layout.insertWidget(index_to_add, job_progress_widget) self.jobsShownCount.setText(f"{index_to_add}") job.signals.job_progress.connect(self.update_job_progress) job.signals.job_finished.connect(self.update_job_complete) self.job_index = self.job_index + 1 self.add_new_job(job)
def decide_for_next_job(connection, job, job_results): return Job(connection, "Dummier job", job.configs, "...")
from jobs import Job, Benchmark_run import brain import CLperfDB import time SLEEP_FOR_RESULTS = 1 NUMBER_OF_JOBS = 1 #I suppose this won't be convergence condition if __name__ == "__main__": connection = CLperfDB.connect() with open("first_job.json", "r+") as starting_job_file: starting_job_configs = starting_job_file.read() job = Job(connection, "Dummy job", starting_job_configs, "First job scheduled from Python") number_of_finished_jobs = 0 job_results = [] while number_of_finished_jobs < NUMBER_OF_JOBS: #I suppose this won't be convergence condition CLperfDB.schedule_job(job) next_job = brain.decide_for_next_job( connection, job, job_results ) #maybe this will decide for list of jobs, not one job... while not CLperfDB.is_job_finished(job): time.sleep(SLEEP_FOR_RESULTS) number_of_finished_jobs += 1
from queue import Queue import time from jobs import Job def do_stuff(q): while not q.empty(): job = q.get() if (job.colour == True): print("Done task" , job.filename) q.task_done() else: job.colour = True q.put(job) q.task_done() q = Queue(maxsize=0) for x, b in zip(['1','2','3','4'], [True, False, True, True]): q.put(Job(x, b, 'b')) print(q.queue) # do_stuff(q)
class TestUser(): def __init__(self): self.username = '******' p = Printer('Duplicator i3', '192.168.0.201', 'B5A36115A3DC49148EFC52012E7EBCD9', 'Hackspace', 'duplicator', 'PLA', 'black') # o = Orchestrator(ps) # # thread = threading.Thread(target=o.run) # thread.start() # # j = Job('1', 'r', 'PLA') job = Job('stepperspacer.gcode', 'black', 'PLA', user=TestUser()) print(p.cancel()) # printer = ps[0] # print(printer.cancel()) # if(printer.can_make(jj)): # printer.make(jj) # time.sleep(2) # o.queue.put(j) # # time.sleep(3) # o.queue.put(jj) # # o.queue.put(jj) # # o.queue.put(jj) # time.sleep(1) #
from languages import list_of_languages from jobs import Job """For Loop to update Json data file for """ for lang in list_of_languages: language = Job(lang) language.job_seeker() language.data_update_process()
def read_jobs_from_file_split(path_to_file): """ Reads jobs from the given file. Expected format (prefix, infix or suffix whitespaces are allowed): Times 14 6 17 5 21 10 Machines 1 2 3 2 3 1 Format semantics: Times <time job1/op1> <time job1/op2> ... <time job2/op1> ... Machines <machine job1/op1> <machine job1/op2> ... <machine job2/op1> ... Keyword arguments: path_to_file -- relative path to the text file to be parsed Returns: list of jobs, read from the file """ with open(path_to_file, "r") as f: times = list() machines = list() times_and_not_machines = True for line in f: normalised_line = re.sub(r"(^\s*)|(\s*$)", "", line) if normalised_line == "Times": times_and_not_machines = True continue elif normalised_line == "Machines": times_and_not_machines = False continue split_line = re.split(r"\s+", normalised_line) if times_and_not_machines: times.append(split_line) else: machines.append(split_line) if len(times) != len(machines): print("Failed to parse \"" + path_to_file + "\" as the number of jobs is inconsistent!") sys.exit(1) jobs = list() for i in range(0, len(times)): if len(times[i]) != len(machines[i]): print( "Failed to parse \"" + path_to_file + "\" as a job contains an inconsistent number of times and machines!" ) sys.exit(1) job = Job() for (time, machine) in zip(times[i], machines[i]): op = Operation(int(time), int(machine)) job.add_operation(op) jobs.append(job) return jobs
| ' You have been dropped into a pit. You | | dont remember anything except you were | | surrounded by a group of thugs' | | | | | | | | | | | ------------------------------------------- """) time.sleep(3) player = Player() print(f"Welcome {player.name}") job_choice = input('what class would you like? "black mage" or "paladin" ') job = Job(job_choice) player.job = job enemy = Enemy('enemy') def battle(): print( 'an adversary is jumps in front of you, ready to strike. Not to fear though because due to your tuned senses you noticed it, and are ready' ) while (not player.victory and player.is_alive()): choice = input('Will you attack it? y or n: ') if (choice == 'y'): damage = player.attack() print(f"you have dealt {damage} damage") enemy.take_damage(damage)
class FreelanceJobs(db.Expando, MyConstants, ErrorCodes): clsJob = Job() # Class to read and store freelance jobs to the data store and also to perform related tasks on the # Job clsBid = Bids() # Class to read and store freelance jobs Bids to the data store # The Person Class will be accessed using the DataType module clsWallet = Wallet() # Class to read and store Account Information for freelancers # All the temporary variables must be holding the correct values # All The variables within clsjob must be holding correct values also def createFreelanceJob(self): pass def readJob(self): try: if self.clsJob.isValid(): return self.clsJob else: return self._JobIsInvalid except: return self._generalError #write job will write all the temporary values back to datastore #TODO - CREATE FUNCTIONS TO ACCEPT INPUT FOR SUB CLASSES SUCH AS OWNER COMPANIES AND OWNER FREELANCERS #TODO- FOR JOBS THE FUNC #TODO- WILL BE CALLED BY WRITE JOB IN ORDER TO COMPLETE THE OVERALL OPERATION FOR WRITING A JOB #TODO- NOTE THAT THE SUBFUNCTIONS TO WRITE DATA WITHIN A SUBCLASS ARE CONTAINED WITHIN SUCH A SUB CLASS def writeJob(self, clsinput): try: Guser = users.get_current_user() if Guser: if (Guser.user_id() == clsinput.jobOwner()) or (users.is_current_user_admin()): if clsinput.isValid(): self.clsJob.writeJobOwner(clsinput.readJobOwner()) self.clsJob.writeEmployerCompany(clsinput.readEmployerCompany()) self.clsJob.writeCompanyOwner(clsinput.readCompanyOwner()) self.clsJob.writeDateTimeEndBidorRemove(clsinput.readDateTimeEndBidorRemove()) self.clsJob.writeDateTimeOfBidsDisplay(clsinput.readDateTimeOfBidsDisplay()) self.clsJob.writeJobBudgetSalary(clsinput.readJobBudgetSalary()) self.clsJob.writeJobDefinition(clsinput.readJobDefinition()) self.clsJob.writeJobKind(clsinput.readJobKind()) self.clsJob.writeJobType(clsinput.readJobType()) self.clsJob.writeNotes(clsinput.readNotes()) self.clsJob.writeRequiredEduQualifications(clsinput.readRequiredEduQualifications()) self.clsJob.writeSkillRequired(clsinput.readSkillsRequired()) self.clsJob.writestrJobTitle(clsinput.readstrJobTitle()) if not(self.clsJob.readBidsActivated() == self._generalError): self.clsjob.BidsActivated = clsinput.readBidsActivated() return True else: return False else: return False else: return self._UserNotAuthorised else: return self._userNotLoggedin except: return self._generalError def saveJob(self): try: Guser = users.get_current_user() if Guser: if (Guser.user_id() == self.clsJob.strOwnerReference) or (users.is_current_user_admin()): if self.clsJob.isValid(): self.clsJob._jobPkey = self.clsJob.put() return self.clsJob._jobPkey else: return self.undefined else: return self._UserNotAuthorised else: return self._userNotLoggedin except: return self._generalError def retrieveJobByPkey(self): try: if not(self.clsJob._jobPkey == self.undefined): temp = Job.get(self.clsJob._jobPkey) if temp.isValid(): return temp else: return self.undefined else: return self._pkeyNotSet except: return self._generalError def retrieveJobsByJobOwner(self, strinput): try: if strinput.isalnum(): findquery = db.Query(Job).filter('strOwnerReference = ', strinput) results = findquery.fetch(limit=self._maxQResults) if len(results) > 0: logging.info('FOUND JOBS') return results else: logging.info('FOUND JOBS') return self._JobsNotFound else: logging.info('NOT FOUND JOBS') return self._pkeyNotSet except: return self._generalError def retrieveJobsByCompanyOwner(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if strinput.isalnum(): findquery = db.Query(Job).filter('clsCompanyOwner =', strinput) results = findquery.fetch(limit=self._maxQResults) if len(results) > 0: return results else: return self._JobsNotFound else: return self._pkeyNotSet except: return self._generalError def retrieveJobsByEmployerCompany(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if strinput.isalnum(): findquery = db.Query(Job).filter('clsEmployerCompany =', strinput) results = findquery.fetch(limit=self._maxQResults) if len(results) > 0: return results else: return self._JobsNotFound else: return self._pkeyNotSet except: return self._generalError def retrieveJobsByJobTitle(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if strinput.isalnum() or strinput.isalpha(): findquery = db.Query(Job).filter('strJobTitle =', strinput) results = findquery.fetch(limit=self._maxQResults) if len(results) > 0: return results else: return self._JobsNotFound else: return self.undefined except: return self._generalError def retrieveJobsByJobType(self, strinput): try: logging.info('RETIRVE FREELANCE JOBS CALLED') strinput = str(strinput) strinput = strinput.strip() if strinput in self.clsJob._lstJobTypes: findquery = db.Query(Job).filter('strJobType =', strinput).order('-BidsActivated').order('-DateTimeSubmitted') results = findquery.fetch(limit=self._maxQResults) if len(results) > 0: return results else: return self._JobsNotFound else: return self._pkeyNotSet except: return self._generalError def retrieveJobsByJobKind(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if strinput in self.clsJob._lstJobKinds: findquery = db.Query(Job).filter('strJobKind =', strinput) results = findquery.fetch(limit=self._maxQResults) if len(results) > 0: return results else: return self._JobsNotFound else: return self._pkeyNotSet except: return self._generalError def retrieveJobsByJobBudget(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if strinput in self.clsJob._lstFreelanceJobBudget: findquery = db.Query(Job).filter('strFreelanceJobBudget =', strinput) results = findquery.fetch(limit=self._maxQResults) if len(results) > 0: return results else: return self._JobsNotFound else: return self._pkeyNotSet except: return self._generalError def retrieveJobsBySkillsPkey(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if strinput.isalnum(): findquery = db.Query(Job).filter('clsSkillsRequired =', strinput) results = findquery.fetch(limit=self._maxQResults) if len(results) > 0: return results else: return self._JobsNotFound else: return self._pkeyNotSet except: return self._generalError def retrieveJobsByEduQualificationsPkey(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if strinput.isalnum(): findquery = db.Query(Job).filter('clsRequiredEduQualifications =', strinput) results = findquery.fetch(limit=self._maxQResults) if len(results) > 0: return results else: return self._JobsNotFound else: return self._pkeyNotSet except: return self._generalError def getJobByBid(self): pass # Given The reference Number of the freelance job search for all the jobs and return only those jobs which are # freelance jobs and owned by a certain user def GetFreelanceJobsByReference(self, strinput): try: strinput = str(strinput) strinput = strinput.strip() if strinput.isalpha() or strinput.isalnum(): findrequest = db.Query(Job).filter('strOwnerReference =', strinput) findrequest = findrequest.filter('strJobType =', self.clsJob._lstJobTypes[2]).order('DateTimeSubmitted') results = findrequest.fetch(limit=self._maxQResults) logging.info('NUMBER OF PERSONAL JOBS RETURNED :' + str(len(results))) if len(results) > 0: # All the jobs are returned # find freelance jobs from the list and return only freelance jobs return results else: return self._JobsNotFound else: return self._referenceDoNotExist except: return self._generalError