コード例 #1
0
ファイル: client_service.py プロジェクト: netmebtc/xmr-proxy
    def handle_event(self, method, params, connection_ref):
        '''Handle RPC calls and notifications from the pool'''
        # Yay, we received something from the pool,
        # let's restart the timeout.
        self.reset_timeout()
        
        if method == 'job':
            '''Proxy just received information about new mining job'''
            if 'id' in params:
            (blob, job_id, target, user_id) = params["blob"],params["job_id"],params["target"],params["id"]
         
            # Broadcast to Stratum client
            stratum_listener.MiningSubscription.on_template(job_id, blob, target, user_id)
            
            # Broadcast to getwork clients
            job = Job.build_from_pool(job_id, blob, target)
            log.info("New job %s for %s" % (job_id, user_id))

            self.job_registry.add_job(job, True)
            
            else:
            (blob, job_id, target) = params["blob"],params["job_id"],params["target"]
            stratum_listener.MiningSubscription.on_template_all(job_id, blob, target)
            job = Job.build_from_pool(job_id, blob, target)
            log.info("New job %s for all" % (job_id))

            self.job_registry.add_job(job, True)
        else:
            '''Pool just asked us for something which we don't support...'''
            log.error("Unhandled method %s with params %s" % (method, params))
コード例 #2
0
ファイル: garage.py プロジェクト: dolekapil/CPS-Assignments
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)
コード例 #3
0
ファイル: app.py プロジェクト: beepboop-tech/printer-farm
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')
コード例 #4
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)
コード例 #5
0
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
コード例 #6
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
コード例 #7
0
ファイル: test_use_cases.py プロジェクト: GuillemSerra/aiorq
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()
コード例 #8
0
ファイル: test_use_cases.py プロジェクト: GuillemSerra/aiorq
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
コード例 #9
0
ファイル: test_consumer.py プロジェクト: GuillemSerra/aiorq
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
コード例 #10
0
 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
コード例 #11
0
ファイル: bids.py プロジェクト: Blue-IT-Marketing/cloud-jobs
    def retrieveBidOnThisJob(self):
        try:

            if not (self.BidonThisJob == self.undefined):
                temp = Job.get(self.BidonThisJob)
                if temp.readisValid():
                    return temp
                else:
                    return self.undefined
            else:
                return self._JobsNotFound
        except:
            return self._generalError
コード例 #12
0
    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"
        ]
コード例 #13
0
    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
コード例 #14
0
ファイル: test.py プロジェクト: Folarin93/Job_market_app
    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)
コード例 #15
0
ファイル: job_parser.py プロジェクト: chlewe/job-scheduling
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
コード例 #16
0
ファイル: client_service.py プロジェクト: Atrides/eth-proxy
 def handle_event(self, method, params, connection_ref):
     '''Handle RPC calls and notifications from the pool'''
     # Yay, we received something from the pool,
     # let's restart the timeout.
     self.reset_timeout()
     
     if method == 'eth_getWork':
         '''Proxy just received information about new mining job'''
         # Broadcast to getwork clients
         job = Job.build_from_pool(params)
         self.job_registry.replace_job(job, connection_ref)
         
     else:
         '''Pool just asked us for something which we don't support...'''
         log.error("Unhandled method %s with params %s" % (method, params))
コード例 #17
0
    def handle_event(self, method, params, connection_ref):
        '''Handle RPC calls and notifications from the pool'''
        # Yay, we received something from the pool,
        # let's restart the timeout.
        self.reset_timeout()

        if method == 'eth_getWork':
            '''Proxy just received information about new mining job'''
            # Broadcast to getwork clients
            job = Job.build_from_pool(params)
            self.job_registry.replace_job(job, connection_ref)

        else:
            '''Pool just asked us for something which we don't support...'''
            log.error("Unhandled method %s with params %s" % (method, params))
コード例 #18
0
    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
コード例 #19
0
ファイル: bids.py プロジェクト: Blue-IT-Marketing/cloud-jobs
    def removeBid(self, strinput):
        try:

            Guser = users.get_current_user()

            if Guser:
                BidtoRemove = Bids.get(strinput)
                BidJob = Job.get(BidtoRemove.BidonThisJob)
                if (Guser.user_id() == BidtoRemove.pBidder) or (
                        BidJob.jobOwner()
                        == Guser.user_id()) or (users.is_current_user_admin()):
                    BidtoRemove.delete()
                    return True
                else:
                    return False
            else:
                return self._userNotLoggedin
        except:
            return self._generalError
コード例 #20
0
    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
コード例 #21
0
ファイル: client_service.py プロジェクト: Atrides/xmr-proxy
    def handle_event(self, method, params, connection_ref):
        '''Handle RPC calls and notifications from the pool'''
        # Yay, we received something from the pool,
        # let's restart the timeout.
        self.reset_timeout()
        
        if method == 'job':
            '''Proxy just received information about new mining job'''
            
            (blob, job_id, target, user_id, height) = params["blob"],params["job_id"],params["target"],params["id"],params["height"]
        
            # Broadcast to Stratum client
            stratum_listener.MiningSubscription.on_template(job_id, blob, target, user_id, height)
            
            # Broadcast to getwork clients
            job = Job.build_from_pool(job_id, blob, target, height)
            log.info("New job %s for %s on height %s" % (job_id, user_id, height))

            self.job_registry.add_job(job, True)
            
        else:
            '''Pool just asked us for something which we don't support...'''
            log.error("Unhandled method %s with params %s" % (method, params))
コード例 #22
0
    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)
コード例 #23
0
ファイル: client_service.py プロジェクト: jstefanop/AlcheMist
    def handle_event(self, method, params, connection_ref):
        """Handle RPC calls and notifications from the pool"""
        log.warn("@@ %s @@" % method)
        # Yay, we received something from the pool,
        # let's restart the timeout.
        self.reset_timeout()

        if method == "mining.notify":
            """Proxy just received information about new mining job"""

            (job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs) = params[:9]
            # print len(str(params)), len(merkle_branch)

            if clean_jobs:
                log.warn("--Clean Jobs!--")
                rpc_tx = {"method": "clean_job", "params": [], "id": "cj"}
                for c in ws_svr:
                    print "ws_svr"
                    print c
                    c.sendMessage(json.dumps(rpc_tx))
            """
            log.debug("Received new job #%s" % job_id)
            log.debug("prevhash = %s" % prevhash)
            log.debug("version = %s" % version)
            log.debug("nbits = %s" % nbits)
            log.debug("ntime = %s" % ntime)
            log.debug("clean_jobs = %s" % clean_jobs)
            log.debug("coinb1 = %s" % coinb1)
            log.debug("coinb2 = %s" % coinb2)
            log.debug("merkle_branch = %s" % merkle_branch)
            """

            # Broadcast to Stratum clients
            stratum_listener.MiningSubscription.on_template(
                job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs
            )

            # Broadcast to getwork clients
            job = Job.build_from_broadcast(job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime)
            log.info(
                "New job %s for prevhash %s, clean_jobs=%s" % (job.job_id, utils.format_hash(job.prevhash), clean_jobs)
            )

            self.job_registry.add_template(job, clean_jobs)

        elif method == "mining.set_difficulty":
            difficulty = params[0]
            log.info("Setting new difficulty: %s" % difficulty)

            stratum_listener.DifficultySubscription.on_new_difficulty(difficulty)
            self.job_registry.set_difficulty(difficulty)

        elif method == "client.reconnect":
            (hostname, port, wait) = params[:3]
            new = list(self.job_registry.f.main_host[::])
            if hostname:
                new[0] = hostname
            if port:
                new[1] = port

            log.info("Server asked us to reconnect to %s:%d" % tuple(new))
            self.job_registry.f.reconnect(new[0], new[1], wait)

        elif method == "client.add_peers":
            """New peers which can be used on connection failure"""
            return False
            """
            peerlist = params[0] # TODO
            for peer in peerlist:
                self.job_registry.f.add_peer(peer)
            return True
            """
        elif method == "client.get_version":
            return "stratum-proxy/%s" % _version.VERSION

        elif method == "client.show_message":

            # Displays message from the server to the terminal
            utils.show_message(params[0])
            return True

        elif method == "mining.get_hashrate":
            return {}  # TODO

        elif method == "mining.get_temperature":
            return {}  # TODO

        else:
            """Pool just asked us for something which we don't support..."""
            log.error("Unhandled method %s with params %s" % (method, params))
コード例 #24
0
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)
コード例 #25
0
    def handle_event(self, method, params, connection_ref):
        '''Handle RPC calls and notifications from the pool'''

        # Yay, we received something from the pool,
        # let's restart the timeout.
        self.reset_timeout()
        
        if method == 'mining.notify':
            '''Proxy just received information about new mining job'''
            
            (job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs) = params[:9]
            #print len(str(params)), len(merkle_branch)
            
            '''
            log.debug("Received new job #%s" % job_id)
            log.debug("prevhash = %s" % prevhash)
            log.debug("version = %s" % version)
            log.debug("nbits = %s" % nbits)
            log.debug("ntime = %s" % ntime)
            log.debug("clean_jobs = %s" % clean_jobs)
            log.debug("coinb1 = %s" % coinb1)
            log.debug("coinb2 = %s" % coinb2)
            log.debug("merkle_branch = %s" % merkle_branch)
            '''
        
            # Broadcast to Stratum clients
            stratum_listener.MiningSubscription.on_template(
                            job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime, clean_jobs)
            
            # Broadcast to getwork clients
            job = Job.build_from_broadcast(job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits, ntime)
            log.info("New job %s for prevhash %s, clean_jobs=%s" % \
                 (job.job_id, utils.format_hash(job.prevhash), clean_jobs))

            self.job_registry.add_template(job, clean_jobs)
            
            
            
        elif method == 'mining.set_difficulty':
            difficulty = params[0]
            log.info("Setting new difficulty: %s" % difficulty)
            
            stratum_listener.DifficultySubscription.on_new_difficulty(difficulty)
            self.job_registry.set_difficulty(difficulty)
                    
        elif method == 'client.reconnect':
            (hostname, port, wait) = params[:3]
            new = list(self.job_registry.f.main_host[::])
            if hostname: new[0] = hostname
            if port: new[1] = port

            log.info("Server asked us to reconnect to %s:%d" % tuple(new))
            self.job_registry.f.reconnect(new[0], new[1], wait)
            
        elif method == 'client.add_peers':
            '''New peers which can be used on connection failure'''
            return False
            '''
            peerlist = params[0] # TODO
            for peer in peerlist:
                self.job_registry.f.add_peer(peer)
            return True
            '''
        elif method == 'client.get_version':
            return "stratum-proxy/%s" % _version.VERSION

        elif method == 'client.show_message':
            
            # Displays message from the server to the terminal
            utils.show_message(params[0])
            return True
            
        elif method == 'mining.get_hashrate':
            return {} # TODO
        
        elif method == 'mining.get_temperature':
            return {} # TODO
        
        else:
            '''Pool just asked us for something which we don't support...'''
            log.error("Unhandled method %s with params %s" % (method, params))
コード例 #26
0
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)
#
コード例 #27
0
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
コード例 #28
0
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()
    
コード例 #29
0
    def handle_event(self, method, params, connection_ref):
        '''Handle RPC calls and notifications from the pool'''

        # Yay, we received something from the pool,
        # let's restart the timeout.
        self.reset_timeout()

        if method == 'mining.notify':
            '''Proxy just received information about new mining job'''

            (job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits,
             ntime, clean_jobs) = params[:9]
            #print len(str(params)), len(merkle_branch)
            '''
            log.debug("Received new job #%s" % job_id)
            log.debug("prevhash = %s" % prevhash)
            log.debug("version = %s" % version)
            log.debug("nbits = %s" % nbits)
            log.debug("ntime = %s" % ntime)
            log.debug("clean_jobs = %s" % clean_jobs)
            log.debug("coinb1 = %s" % coinb1)
            log.debug("coinb2 = %s" % coinb2)
            log.debug("merkle_branch = %s" % merkle_branch)
            '''

            # Broadcast to Stratum clients
            stratum_listener.MiningSubscription.on_template(
                job_id, prevhash, coinb1, coinb2, merkle_branch, version,
                nbits, ntime, clean_jobs)

            # Broadcast to getwork clients
            job = Job.build_from_broadcast(job_id, prevhash, coinb1, coinb2,
                                           merkle_branch, version, nbits,
                                           ntime)
            log.info("New job %s for prevhash %s, clean_jobs=%s" % \
                 (job.job_id, utils.format_hash(job.prevhash), clean_jobs))

            self.job_registry.add_template(job, clean_jobs)

        elif method == 'mining.set_difficulty':
            difficulty = params[0]
            log.info("Setting new difficulty: %s" % difficulty)

            stratum_listener.DifficultySubscription.on_new_difficulty(
                difficulty)
            self.job_registry.set_difficulty(difficulty)

        elif method == 'client.reconnect':
            (hostname, port, wait) = params[:3]
            new = list(self.job_registry.f.main_host[::])
            if hostname: new[0] = hostname
            if port: new[1] = port

            log.info("Server asked us to reconnect to %s:%d" % tuple(new))
            self.job_registry.f.reconnect(new[0], new[1], wait)

        elif method == 'client.add_peers':
            '''New peers which can be used on connection failure'''
            return False
            '''
            peerlist = params[0] # TODO
            for peer in peerlist:
                self.job_registry.f.add_peer(peer)
            return True
            '''
        elif method == 'client.get_version':
            return "stratum-proxy/%s" % _version.VERSION

        elif method == 'client.show_message':

            # Displays message from the server to the terminal
            utils.show_message(params[0])
            return True

        elif method == 'mining.get_hashrate':
            return {}  # TODO

        elif method == 'mining.get_temperature':
            return {}  # TODO

        else:
            '''Pool just asked us for something which we don't support...'''
            log.error("Unhandled method %s with params %s" % (method, params))
コード例 #30
0
ファイル: main.py プロジェクト: deathclock96/python-game
|  ' 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)
コード例 #31
0
    def handle_event(self, method, params, connection_ref):
        '''Handle RPC calls and notifications from the pool'''

        stp = stproxy_ng.StratumServer._get_pool_proxy(
            id(connection_ref.factory))

        if method == 'mining.notify':
            '''Proxy just received information about new mining job'''

            (job_id, prevhash, coinb1, coinb2, merkle_branch, version, nbits,
             ntime, clean_jobs) = params[:9]

            diff = stp.difficulty

            # print len(str(params)), len(merkle_branch)
            '''
            log.debug("Received new job #%s" % job_id)
            log.debug("prevhash = %s" % prevhash)
            log.debug("version = %s" % version)
            log.debug("nbits = %s" % nbits)
            log.debug("ntime = %s" % ntime)
            log.debug("clean_jobs = %s" % clean_jobs)
            log.debug("coinb1 = %s" % coinb1)
            log.debug("coinb2 = %s" % coinb2)
            log.debug("merkle_branch = %s" % merkle_branch)
            log.debug("difficulty = %s" % diff)
            '''

            # Broadcast to Stratum clients
            stratum_listener.MiningSubscription.on_template(
                stp, job_id, prevhash, coinb1, coinb2, merkle_branch, version,
                nbits, ntime, clean_jobs)

            # Broadcast to getwork clients
            job = Job.build_from_broadcast(job_id, prevhash, coinb1, coinb2,
                                           merkle_branch, version, nbits,
                                           ntime, diff)
            log.info("New job %s for prevhash %s, clean_jobs=%s" %
                     (job.job_id, job.prevhash[:8], clean_jobs))

            stp.job_registry.add_template(job, clean_jobs)

        elif method == 'mining.set_difficulty':
            difficulty = params[0]
            log.info("Setting new difficulty: %s" % difficulty)
            stratum_listener.DifficultySubscription.on_new_difficulty(
                stp, difficulty)

        elif method == 'client.reconnect':
            try:
                (hostname, port, wait) = params[:3]
            except:
                log.error("Pool sent client.reconnect")
                hostname = False
                port = False
                wait = False
            new = list(stp.f.main_host[::])
            if hostname and len(hostname) > 6:
                new[0] = hostname
            if port and port > 2:
                new[1] = port
            log.info("Reconnecting to %s:%d" % tuple(new))
            stp.f.reconnect(new[0], new[1], wait)

        elif method == 'mining.set_extranonce':
            '''Method to set new extranonce'''
            try:
                extranonce1 = params[0]
                extranonce2_size = params[1]
                log.info("Setting new extranonce: %s/%s" %
                         (extranonce1, extranonce2_size))
            except:
                log.error(
                    "Wrong extranonce information got from pool, ignoring")
                return False
            stp.job_registry.set_extranonce(extranonce1, int(extranonce2_size))
            log.info('Sending reconnect order to workers')
            stratum_listener.MiningSubscription.reconnect_all()
            return True

        elif method == 'client.add_peers':
            '''New peers which can be used on connection failure'''
            return False
            '''
            peerlist = params[0] # TODO
            for peer in peerlist:
                stp.f.add_peer(peer)
            return True
            '''
        elif method == 'client.get_version':
            return "stratum-proxy/%s" % _version.VERSION

        elif method == 'client.show_message':

            # Displays message from the server to the terminal
            log.warning("MESSAGE FROM THE SERVER OPERATOR: %s" % params[0])
            return True

        elif method == 'mining.get_hashrate':
            return {}  # TODO

        elif method == 'mining.get_temperature':
            return {}  # TODO

        else:
            '''Pool just asked us for something which we don't support...'''
            log.error("Unhandled method %s with params %s" % (method, params))
コード例 #32
0
 def execute(self, driver: WebDriver):
     self._context = Context(driver)
     Job.run(self._job_list, self._context)
コード例 #33
0
class ZulipBot(object):
    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"
        ]
        #mesg = dhelp()
        #self.client.send_message({
        #	"type": "stream",
        #	"content" : self.mesg
        #	})

    def urls(self, link):
        urls = re.findall(
            'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
            link)
        return urls

    def subscribe_all(self):
        json = self.client.get_streams()["streams"]
        streams = [{"name": stream["name"]} for stream in json]
        self.client.add_subscriptions(streams)

    def help(self):
        message = "**Welcome to I-BOT**\nIBOT has various subfields\nType `ibot help <subfield>` to get help for specific subfield.\n"
        message += "\n**Subfields**\n"
        message += "`currency` - Get currency conversion rate\n"
        message += "`atm` - Get addresses of nearby ATM(s)\n"
        message += "`restaurant` - Get addresses of nearby restaurant(s)\n"
        message += "`bus` - Get addresses of nearest bus stand(s)\n"
        message += "`tourist` - Get addresses of nearby tourist place(s)\n"
        message += "`job` - Get a list of jobs available nearby\n"
        message += "`direction` - Get directions from one place to other\n"
        message += "`language` - Translate your English sentences to other languages\n"
        message += "\nIf you're bored Talk to IBOT, it will supercharge you"
        return message

    def help_sub(self, key):
        key = key.lower()
        message = "**Usage**\n"
        if key == "currency":
            message += "`ibot currency from <currency code - 1> to <currency code - 2>` - To get currency conversion rate.\n"
        elif key == "atm":
            message += "`ibot atm <nearby location>` - To get addresses of nearby ATM(s).\n"
        elif key == "restaurant":
            message += "`ibot restaurant <nearby location>` - To get addresses of nearby restaurant(s).\n"
        elif key == "bus":
            message += "`ibot bus <nearby location>` - To get addresses of nearby bus stand(s).\n"
        elif key == "tourist":
            message += "`ibot tourist <nearby location>` - To get addresses of nearby tourist place(s).\n"
        elif key == "job":
            message += "`ibot job <nearby location>` - To get a list of jobs available nearby.\n"
        elif key == "direction":
            message += "`ibot direction from <source> to <destination>` - To get directions from one place to another.\n"
        elif key == "language":
            message += "`ibot language to <language name>` - To translate your English sentences to other languages.\n"
        else:
            message = self.help()
            message += "\n{} is not a valid subfield\n".format(key)
        return message

    def process(self, msg):
        content = msg["content"].split()
        sender_email = msg["sender_email"]
        ttype = msg["type"]
        stream_name = msg['display_recipient']
        stream_topic = msg['subject']

        print(content)
        l = len(content)
        #		temstr = spell(content[1].lower())
        #		content[1] = temstr
        #		print(content[1])
        if sender_email == BOT_MAIL:
            return

        print("doing")

        if content[0].lower() == "ibot" or content[0] == "@**IBOT**":
            if content[1].lower() == "currency":
                message = self.currency.curfun(content)
                #print(message)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "latilongi":
                message = self.lat_lon.latlonfun(content)
                #print(message)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "language":
                message = self.language.langconvert(content)
                #print(message)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "restaurant":
                message = self.restaurants.restfun(content)
                #print(message)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "bus":
                message = self.bus_stations.busfun(content)
                #print(message)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "tourist":
                message = self.tourist_places.tourfun(content)
                #print(message)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "job":
                message = self.jobs.jobfun(content)
                #print(message)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "atm":
                message = self.atm.atmfun(content)
                #print(message)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "direction":
                message = self.directions.directfun(content)
                #print(message)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "help" and len(content) == 2:
                message = self.help()
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "help" and len(content) > 2:
                subkey = content[2]
                message = self.help_sub(subkey)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

            if content[1] not in self.subkeys:
                ip = content[1:]
                ip = " ".join(ip)
                message = self.chatbot.get_response(ip).text
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

        if self.urls(" ".join(content)):
            summary = self.w.wiki(" ".join(content))
            if summary:
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": summary
                })
        elif "ibot" in content and content[0] != "ibot":
            self.client.send_message({
                "type":
                "stream",
                "subject":
                msg["subject"],
                "to":
                msg["display_recipient"],
                "content":
                "Alas! Finally you called me :blush:"
            })
        else:
            return
コード例 #34
0
ファイル: job_parser.py プロジェクト: chlewe/job-scheduling
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