<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
=============
TAP plus
=============

@author: <NAME>
@contact: <EMAIL>

European Space Astronomy Centre (ESAC)
European Space Agency (ESA)

Created on 30 jun. 2016


"""

import time

from astroquery.utils.tap.model import modelutils
from astroquery.utils.tap.xmlparser import utils
from astroquery.utils.tap import taputils
import requests
import sys

__all__ = ['Job']


class Job(object):
    """Job class
    """

    def __init__(self, async_job, query=None, connhandler=None):
        """Constructor

        Parameters
        ----------
        async_job : bool, mandatory
            'True' if the job is asynchronous
        query : str, optional, default None
            Query
        connhandler : TapConn, optional, default None
            Connection handler
        """
        # async is a reserved keyword starting python 3.7
        self.async_ = async_job
        self.connHandler = None
        self.isFinished = None
        self.jobid = None
        self.remoteLocation = None
        # phase is actually indended to be private as get_phase is non-trivial
        self._phase = None
        self.outputFile = None
        self.responseStatus = 0
        self.responseMsg = None
        self.results = None
        self.__resultInMemory = False    # only used within class
        self.failed = False
        self.runid = None
        self.ownerid = None
        self.startTime = None
        self.endTime = None
        self.creationTime = None
        self.executionDuration = None
        self.destruction = None
        self.locationId = None
        self.name = None
        self.quote = None

        self.connHandler = connhandler
        self.parameters = {}
        self.parameters['query'] = query
        # default output format
        self.parameters['format'] = 'votable'

    def set_phase(self, phase):
        """Sets the job phase

        Parameters
        ----------
        phase : str, mandatory
            job phase
        """
        if self.is_finished():
            raise ValueError("Cannot assign a pahse when a job is finished")
        self._phase = phase

    def start(self, verbose=False):
        """Starts the job (allowed in PENDING phase only)

        Parameters
        ----------
        verbose : bool, optional, default 'False'
            flag to display information about the process
        """
        self.__change_phase(phase="RUN", verbose=verbose)

    def abort(self, verbose=False):
        """Aborts the job (allowed in PENDING phase only)

        Parameters
        ----------
        verbose : bool, optional, default 'False'
            flag to display information about the process
        """
        self.__change_phase(phase="ABORT", verbose=verbose)

    def __change_phase(self, phase, verbose=False):
        if self.__phase == 'PENDING':
            context = "async/"+str(self.get_jobid())+"/phase"
            args = {
                "PHASE": str(phase)}
            data = self.__connHandler.url_encode(args)
            response = self.__connHandler.execute_tappost(subcontext=context,
                                                          data=data,
                                                          verbose=verbose)
            if verbose:
                print(response.status, response.reason)
                print(response.getheaders())
            self.__last_phase_response_status = response.status
            if phase == 'RUN':
                phase = 'QUEUED'
                if response.status != 200 and response.status != 303:
                    errMsg = taputils.get_http_response_error(response)
                    print(response.status, errMsg)
                    raise Exception(errMsg)
            else:
                if response.status != 200:
                    errMsg = taputils.get_http_response_error(response)
                    print(response.status, errMsg)
                    raise Exception(errMsg)
            self.__phase = phase
            return response
        else:
            raise ValueError("Cannot start a job in phase: " + str(self.__phase))

    def send_parameter(self, name=None, value=None, verbose=False):
        """Sends a job parameter (allowed in PENDING phase only).

        Parameters
        ----------
        name : string
            Parameter name.
        value : string
            Parameter value.
        """
        if self.__phase == 'PENDING':
            # send post parameter/value
            context = "async/"+str(self.get_jobid())
            args = {
                name: str(value)}
            data = self.__connHandler.url_encode(args)
            response = self.__connHandler.execute_tappost(subcontext=context, data=data, verbose=verbose)
            if verbose:
                print(response.status, response.reason)
                print(response.getheaders())
            self.__last_phase_response_status = response.status
            if response.status != 200:<commit_msg>Fixed access to __phase attr (now it is _phase)<commit_after># Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
=============
TAP plus
=============

@author: <NAME>
@contact: <EMAIL>

European Space Astronomy Centre (ESAC)
European Space Agency (ESA)

Created on 30 jun. 2016


"""

import time

from astroquery.utils.tap.model import modelutils
from astroquery.utils.tap.xmlparser import utils
from astroquery.utils.tap import taputils
import requests
import sys

__all__ = ['Job']


class Job(object):
    """Job class
    """

    def __init__(self, async_job, query=None, connhandler=None):
        """Constructor

        Parameters
        ----------
        async_job : bool, mandatory
            'True' if the job is asynchronous
        query : str, optional, default None
            Query
        connhandler : TapConn, optional, default None
            Connection handler
        """
        # async is a reserved keyword starting python 3.7
        self.async_ = async_job
        self.connHandler = None
        self.isFinished = None
        self.jobid = None
        self.remoteLocation = None
        # phase is actually indended to be private as get_phase is non-trivial
        self._phase = None
        self.outputFile = None
        self.responseStatus = 0
        self.responseMsg = None
        self.results = None
        self.__resultInMemory = False    # only used within class
        self.failed = False
        self.runid = None
        self.ownerid = None
        self.startTime = None
        self.endTime = None
        self.creationTime = None
        self.executionDuration = None
        self.destruction = None
        self.locationId = None
        self.name = None
        self.quote = None

        self.connHandler = connhandler
        self.parameters = {}
        self.parameters['query'] = query
        # default output format
        self.parameters['format'] = 'votable'

    def set_phase(self, phase):
        """Sets the job phase

        Parameters
        ----------
        phase : str, mandatory
            job phase
        """
        if self.is_finished():
            raise ValueError("Cannot assign a pahse when a job is finished")
        self._phase = phase

    def start(self, verbose=False):
        """Starts the job (allowed in PENDING phase only)

        Parameters
        ----------
        verbose : bool, optional, default 'False'
            flag to display information about the process
        """
        self.__change_phase(phase="RUN", verbose=verbose)

    def abort(self, verbose=False):
        """Aborts the job (allowed in PENDING phase only)

        Parameters
        ----------
        verbose : bool, optional, default 'False'
            flag to display information about the process
        """
        self.__change_phase(phase="ABORT", verbose=verbose)

    def __change_phase(self, phase, verbose=False):
        if self.__phase == 'PENDING':
            context = "async/"+str(self.get_jobid())+"/phase"
            args = {
                "PHASE": str(phase)}
            data = self.__connHandler.url_encode(args)
            response = self.__connHandler.execute_tappost(subcontext=context,
                                                          data=data,
                                                          verbose=verbose)
            if verbose:
                print(response.status, response.reason)
                print(response.getheaders())
            self.__last_phase_response_status = response.status
            if phase == 'RUN':
                # a request for RUN does not mean the server executes the job
                phase = 'QUEUED'
                if response.status != 200 and response.status != 303:
                    errMsg = taputils.get_http_response_error(response)
                    print(response.status, errMsg)
                    raise Exception(errMsg)
            else:
                if response.status != 200:
                    errMsg = taputils.get_http_response_error(response)
                    print(response.status, errMsg)
                    raise Exception(errMsg)
            self.__phase = phase
            return response
        else:
            raise ValueError("Cannot start a job in phase: " + str(self._phase))

    def send_parameter(self, name=None, value=None, verbose=False):
        """Sends a job parameter (allowed in PENDING phase only).

        Parameters
        ----------
        name : string
            Parameter name.
        value : string
            Parameter value.
        """
        if self.__phase == 'PENDING':
            # send post parameter/value
            context = "async/"+str(self.get_jobid())
            args = {
                name: str(value)}
            data = self.__connHandler.url_encode(args)
            response = self.__connHandler.execute_tappost(subcontext=context, data=data, verbose=verbose)
            if verbose:
                print(response.status, response.reason)
                print(response.getheaders())
            self.__last_phase_response_status = response.status
            if response.status != 200:
{'fraction_non_alphanumeric': 0.09533587562334996, 'fraction_numerical': 0.004302336951207588, 'mean_word_length': 1.7303790710090763, 'pattern_counts': {'":': 2, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4019570', 'n_tokens_mistral': 2635, 'n_tokens_neox': 2486, 'n_words': 727}