union

Prompt:
Implement the Python class `UnionFind` described below.

Class description:
Implementation of a disjoint set data structure. This data structure solves the problem of maintaining a collection of disjoint sets under the operation of union. To determine if two elements live in the same set, we implement a find operation which returns the name of the set containing the given element. Our implementation follows Chapter 2 of "Data Structures and Network Algorithms" by Tarjan. We implement both the union by rank and the path compression heuristics for fast amortized runtime.

Method signatures and docstrings:
- def __init__(self, elements): Initialize a new UnionFind object containing the given elements. Given a list of elements, we initialize the data structure by putting each element into its own set. We represent each set by a rooted tree. The nodes of the tree are the elements of the set, and the representative of each set is the tree root. For each node x, we keep track of its parent node. By convention, we make the root element its own parent.
- def find(self, x): Returns the name of the set containing the element x. Here, we use the path compression heuristic. This changes the structure of the tree during a find by moving nodes closer to the root. When carrying out find(x), after locating the root r of the tree containing x, we make every node on the path from x to r point directly to r. This heuristic increases the time of a single find by a constant factor, but saves enough time in later finds to more than pay for itself.
- def union(self, x, y): Combines the sets named x and y. Here, we use the union by rank heuristic to keep the trees shallow. With each node x, we store a nonnegative integer rank that is an upper bound on the height of x.

Implement the Python class `UnionFind` described below.

Class description:
Implementation of a disjoint set data structure. This data structure solves the problem of maintaining a collection of disjoint sets under the operation of union. To determine if two elements live in the same set, we implement a find operation which returns the name of the set containing the given element. Our implementation follows Chapter 2 of "Data Structures and Network Algorithms" by Tarjan. We implement both the union by rank and the path compression heuristics for fast amortized runtime.

Method signatures and docstrings:
- def __init__(self, elements): Initialize a new UnionFind object containing the given elements. Given a list of elements, we initialize the data structure by putting each element into its own set. We represent each set by a rooted tree. The nodes of the tree are the elements of the set, and the representative of each set is the tree root. For each node x, we keep track of its parent node. By convention, we make the root element its own parent.
- def find(self, x): Returns the name of the set containing the element x. Here, we use the path compression heuristic. This changes the structure of the tree during a find by moving nodes closer to the root. When carrying out find(x), after locating the root r of the tree containing x, we make every node on the path from x to r point directly to r. This heuristic increases the time of a single find by a constant factor, but saves enough time in later finds to more than pay for itself.
- def union(self, x, y): Combines the sets named x and y. Here, we use the union by rank heuristic to keep the trees shallow. With each node x, we store a nonnegative integer rank that is an upper bound on the height of x.

<|skeleton|>
class UnionFind:
    """Implementation of a disjoint set data structure. This data structure solves the problem of maintaining a collection of disjoint sets under the operation of union. To determine if two elements live in the same set, we implement a find operation which returns the name of the set containing the given element. Our implementation follows Chapter 2 of "Data Structures and Network Algorithms" by Tarjan. We implement both the union by rank and the path compression heuristics for fast amortized runtime."""

    def __init__(self, elements):
        """Initialize a new UnionFind object containing the given elements. Given a list of elements, we initialize the data structure by putting each element into its own set. We represent each set by a rooted tree. The nodes of the tree are the elements of the set, and the representative of each set is the tree root. For each node x, we keep track of its parent node. By convention, we make the root element its own parent."""
        <|body_0|>

    def find(self, x):
        """Returns the name of the set containing the element x. Here, we use the path compression heuristic. This changes the structure of the tree during a find by moving nodes closer to the root. When carrying out find(x), after locating the root r of the tree containing x, we make every node on the path from x to r point directly to r. This heuristic increases the time of a single find by a constant factor, but saves enough time in later finds to more than pay for itself."""
        <|body_1|>

    def union(self, x, y):
        """Combines the sets named x and y. Here, we use the union by rank heuristic to keep the trees shallow. With each node x, we store a nonnegative integer rank that is an upper bound on the height of x."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        rank = {}
        parent = {}
        for u in elements:
            rank[u] = 0
            parent[u] = u
        self.rank = rank
        self.parent = parent
<|end_body_0|>

<|body_start_1|>
        parent = self.parent
        path = []
        append = path.append
        while x != parent[x]:
            append(x)
            x = parent[x]
        for v in path:
            parent[v] = x
        return x
<|end_body_1|>

<|body_start_2|>
        parent = self.parent
        rank = self.rank
        px = parent[x]
        py = parent[y]
        if rank[px] > rank[py]:
            x, y = (y, x)
        if rank[px] == rank[py]:
            rank[py] += 1
        parent[px] = py
<|end_body_2|>

Solution:
class UnionFind:
    """Implementation of a disjoint set data structure. This data structure solves the problem of maintaining a collection of disjoint sets under the operation of union. To determine if two elements live in the same set, we implement a find operation which returns the name of the set containing the given element. Our implementation follows Chapter 2 of "Data Structures and Network Algorithms" by Tarjan. We implement both the union by rank and the path compression heuristics for fast amortized runtime."""

    def __init__(self, elements):
        """Initialize a new UnionFind object containing the given elements. Given a list of elements, we initialize the data structure by putting each element into its own set. We represent each set by a rooted tree. The nodes of the tree are the elements of the set, and the representative of each set is the tree root. For each node x, we keep track of its parent node. By convention, we make the root element its own parent."""
        rank = {}
        parent = {}
        for u in elements:
            rank[u] = 0
            parent[u] = u
        self.rank = rank
        self.parent = parent

    def find(self, x):
        """Returns the name of the set containing the element x. Here, we use the path compression heuristic. This changes the structure of the tree during a find by moving nodes closer to the root. When carrying out find(x), after locating the root r of the tree containing x, we make every node on the path from x to r point directly to r. This heuristic increases the time of a single find by a constant factor, but saves enough time in later finds to more than pay for itself."""
        parent = self.parent
        path = []
        append = path.append
        while x != parent[x]:
            append(x)
            x = parent[x]
        for v in path:
            parent[v] = x
        return x

    def union(self, x, y):
        """Combines the sets named x and y. Here, we use the union by rank heuristic to keep the trees shallow. With each node x, we store a nonnegative integer rank that is an upper bound on the height of x."""
        parent = self.parent
        rank = self.rank
        px = parent[x]
        py = parent[y]
        if rank[px] > rank[py]:
            x, y = (y, x)
        if rank[px] == rank[py]:
            rank[py] += 1
        parent[px] = py


Prompt:
Implement the Python class `ExchangeApi` described below.

Class description:
Implement the ExchangeApi class.

Method signatures and docstrings:
- def get_exchange_info(cls): Get COZA Service exchange and curreny info Args: None Returns: exchange_info(dict)
- def get_ticker(cls, exchange, currency): Get current ticker Args: exchange(str): Cryptocurrency exchagne name currency(str): Cryptocurrency name Returns: data(dict)
- def get_orderbook(cls, exchange, currency): Get orderbook current time Args: exchange(str): Cryptocurrency exchange name currency(str): Cryptocurrency name Returns: data(dict)
- def get_markets(cls): Get markets upbit exchange Returns: data(dict)

Implement the Python class `ExchangeApi` described below.

Class description:
Implement the ExchangeApi class.

Method signatures and docstrings:
- def get_exchange_info(cls): Get COZA Service exchange and curreny info Args: None Returns: exchange_info(dict)
- def get_ticker(cls, exchange, currency): Get current ticker Args: exchange(str): Cryptocurrency exchagne name currency(str): Cryptocurrency name Returns: data(dict)
- def get_orderbook(cls, exchange, currency): Get orderbook current time Args: exchange(str): Cryptocurrency exchange name currency(str): Cryptocurrency name Returns: data(dict)
- def get_markets(cls): Get markets upbit exchange Returns: data(dict)

<|skeleton|>
class ExchangeApi:

    def get_exchange_info(cls):
        """Get COZA Service exchange and curreny info Args: None Returns: exchange_info(dict)"""
        <|body_0|>

    def get_ticker(cls, exchange, currency):
        """Get current ticker Args: exchange(str): Cryptocurrency exchagne name currency(str): Cryptocurrency name Returns: data(dict)"""
        <|body_1|>

    def get_orderbook(cls, exchange, currency):
        """Get orderbook current time Args: exchange(str): Cryptocurrency exchange name currency(str): Cryptocurrency name Returns: data(dict)"""
        <|body_2|>

    def get_markets(cls):
        """Get markets upbit exchange Returns: data(dict)"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        url = f'{COZA_HOST}/exchanges'
        exchange_li = _request(url, 'GET')
        exchange_info = {}
        for exchange in exchange_li['results']:
            currency_li = []
            if exchange['name'] not in exchange_info.keys():
                for currency in exchange['currencies']:
                    currency_li.append(currency['label'])
                exchange_info[exchange['name']] = [currency_li, exchange['intervals'], exchange['feerate']]
        return exchange_info
<|end_body_0|>

<|body_start_1|>
        url = f'{COZA_HOST}/exchanges/{exchange.lower()}/ticker'
        data = _request(url, 'GET', params={'currency': currency.upper()})
        return data
<|end_body_1|>

<|body_start_2|>
        url = f'{COZA_HOST}/exchanges/{exchange.lower()}/orderbook'
        data = _request(url, 'GET', params={'currency': currency.upper()})
        return data
<|end_body_2|>

<|body_start_3|>
        url = f'{COZA_HOST}/exchanges/upbit/market'
        resp = _request(url, 'GET')
        data = {}
        try:
            for k in resp.keys():
                if k == 'remain_req':
                    data[k] = resp[k]
                else:
                    data[k] = pd.DataFrame(resp[k])
        except Exception as e:
            print(e)
        return data
<|end_body_3|>

Solution:
class ExchangeApi:
    def get_exchange_info(cls):
        """Get COZA Service exchange and curreny info Args: None Returns: exchange_info(dict)"""
        url = f'{COZA_HOST}/exchanges'
        exchange_li = _request(url, 'GET')
        exchange_info = {}
        for exchange in exchange_li['results']:
            currency_li = []
            if exchange['name'] not in exchange_info.keys():
                for currency in exchange['currencies']:
                    currency_li.append(currency['label'])
                exchange_info[exchange['name']] = [currency_li, exchange['intervals'], exchange['feerate']]
        return exchange_info

    def get_ticker(cls, exchange, currency):
        """Get current ticker Args: exchange(str): Cryptocurrency exchagne name currency(str): Cryptocurrency name Returns: data(dict)"""
        url = f'{COZA_HOST}/exchanges/{exchange.lower()}/ticker'
        data = _request(url, 'GET', params={'currency': currency.upper()})
        return data

    def get_orderbook(cls, exchange, currency):
        """Get orderbook current time Args: exchange(str): Cryptocurrency exchange name currency(str): Cryptocurrency name Returns: data(dict)"""
        url = f'{COZA_HOST}/exchanges/{exchange.lower()}/orderbook'
        data = _request(url, 'GET', params={'currency': currency.upper()})
        return data

    def get_markets(cls):
        """Get markets upbit exchange Returns: data(dict)"""
        url = f'{COZA_HOST}/exchanges/upbit/market'
        resp = _request(url, 'GET')
        data = {}
        try:
            for k in resp.keys():
                if k == 'remain_req':
                    data[k] = resp[k]
                else:
                    data[k] = pd.DataFrame(resp[k])
        except Exception as e:
            print(e)
        return data


Prompt:
Implement the Python class `ListExtract` described below.

Class description:
Used to extract a list of dictionaries that will each represent a single row in a database

Method signatures and docstrings:
- def __init__(self, lam: Callable[[dict], list]): Creates a ListExtract object Args: lam: Anonymous function that attempts to extract a list of data that will become rows in a DataFrame
- def lam_wrap(self, lam_arg: dict) -> Union[List[dict], None]: Overrides super class method Workflow: 1. Attempt to perform the ``lam`` operation on the incoming data 2. Attempt to cast the result ``lam`` operation to a list * If an exception occurs, return None 3. Return the list of data Args: lam_arg: A dictionary containing a list of dictionaries that will become the rows of a DataFrame Returns: A list of dictionaries that will become the rows of a DataFrame if successful otherwise None

Implement the Python class `ListExtract` described below.

Class description:
Used to extract a list of dictionaries that will each represent a single row in a database

Method signatures and docstrings:
- def __init__(self, lam: Callable[[dict], list]): Creates a ListExtract object Args: lam: Anonymous function that attempts to extract a list of data that will become rows in a DataFrame
- def lam_wrap(self, lam_arg: dict) -> Union[List[dict], None]: Overrides super class method Workflow: 1. Attempt to perform the ``lam`` operation on the incoming data 2. Attempt to cast the result ``lam`` operation to a list * If an exception occurs, return None 3. Return the list of data Args: lam_arg: A dictionary containing a list of dictionaries that will become the rows of a DataFrame Returns: A list of dictionaries that will become the rows of a DataFrame if successful otherwise None

<|skeleton|>
class ListExtract:
    """Used to extract a list of dictionaries that will each represent a single row in a database"""

    def __init__(self, lam: Callable[[dict], list]):
        """Creates a ListExtract object Args: lam: Anonymous function that attempts to extract a list of data that will become rows in a DataFrame"""
        <|body_0|>

    def lam_wrap(self, lam_arg: dict) -> Union[List[dict], None]:
        """Overrides super class method Workflow: 1. Attempt to perform the ``lam`` operation on the incoming data 2. Attempt to cast the result ``lam`` operation to a list * If an exception occurs, return None 3. Return the list of data Args: lam_arg: A dictionary containing a list of dictionaries that will become the rows of a DataFrame Returns: A list of dictionaries that will become the rows of a DataFrame if successful otherwise None"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.ctype = 'list_extract'
        'str: type of data processor'
        self.lam = lam
        self.dtype = list
        'type(list): the datatype performing `lam` should yield'
<|end_body_0|>

<|body_start_1|>
        try:
            res = self.dtype(self.lam(lam_arg))
        except Exception as e:
            logger = get_logger()
            logger.exception(e)
            res = None
        return res
<|end_body_1|>

Solution:
class ListExtract:
    """Used to extract a list of dictionaries that will each represent a single row in a database"""

    def __init__(self, lam: Callable[[dict], list]):
        """Creates a ListExtract object Args: lam: Anonymous function that attempts to extract a list of data that will become rows in a DataFrame"""
        self.ctype = 'list_extract'
        'str: type of data processor'
        self.lam = lam
        self.dtype = list
        'type(list): the datatype performing `lam` should yield'

    def lam_wrap(self, lam_arg: dict) -> Union[List[dict], None]:
        """Overrides super class method Workflow: 1. Attempt to perform the ``lam`` operation on the incoming data 2. Attempt to cast the result ``lam`` operation to a list * If an exception occurs, return None 3. Return the list of data Args: lam_arg: A dictionary containing a list of dictionaries that will become the rows of a DataFrame Returns: A list of dictionaries that will become the rows of a DataFrame if successful otherwise None"""
        try:
            res = self.dtype(self.lam(lam_arg))
        except Exception as e:
            logger = get_logger()
            logger.exception(e)
            res = None
        return res


run

Prompt:
Implement the Python class `process_bsgenome` described below.

Class description:
Workflow to download and pre-index a given genome

Method signatures and docstrings:
- def __init__(self, configuration=None): Initialise the class Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, which are specific to each Tool.
- def run(self, input_files, metadata, output_files): Main run function for the indexing of genome assembly FASTA files. The pipeline uses Bowtie2, BWA and GEM ready for use in pipelines that rely on alignment. Parameters ---------- input_files : dict genome : str Location of the FASTA input file metadata : dict genome : dict Required meta data output_files : dict BSgenome : str Location of a the BSgenome R package Returns ------- outputfiles : dict List of locations for the output index files output_metadata : dict Metadata about each of the files

Implement the Python class `process_bsgenome` described below.

Class description:
Workflow to download and pre-index a given genome

Method signatures and docstrings:
- def __init__(self, configuration=None): Initialise the class Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, which are specific to each Tool.
- def run(self, input_files, metadata, output_files): Main run function for the indexing of genome assembly FASTA files. The pipeline uses Bowtie2, BWA and GEM ready for use in pipelines that rely on alignment. Parameters ---------- input_files : dict genome : str Location of the FASTA input file metadata : dict genome : dict Required meta data output_files : dict BSgenome : str Location of a the BSgenome R package Returns ------- outputfiles : dict List of locations for the output index files output_metadata : dict Metadata about each of the files

<|skeleton|>
class process_bsgenome:
    """Workflow to download and pre-index a given genome"""

    def __init__(self, configuration=None):
        """Initialise the class Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, which are specific to each Tool."""
        <|body_0|>

    def run(self, input_files, metadata, output_files):
        """Main run function for the indexing of genome assembly FASTA files. The pipeline uses Bowtie2, BWA and GEM ready for use in pipelines that rely on alignment. Parameters ---------- input_files : dict genome : str Location of the FASTA input file metadata : dict genome : dict Required meta data output_files : dict BSgenome : str Location of a the BSgenome R package Returns ------- outputfiles : dict List of locations for the output index files output_metadata : dict Metadata about each of the files"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        logger.info('Processing Genome')
        if configuration is None:
            configuration = {}
        self.configuration.update(configuration)
<|end_body_0|>

<|body_start_1|>
        output_files_generated = {}
        output_metadata = {}
        genome_input_file = {'genome': input_files['genome']}
        genome_input_meta = {'genome': metadata['genome']}
        if 'genome_public' in input_files:
            genome_input_file = {'genome': input_files['genome_public']}
            genome_input_meta = {'genome': metadata['genome_public']}
        logger.info('Generating BSgenome')
        bsg = bsgenomeTool(self.configuration)
        logger.progress('BSgenome Indexer', status='RUNNING')
        bsgi, bsgm = bsg.run(genome_input_file, genome_input_meta, output_files)
        logger.progress('BSgenome Indexer', status='DONE')
        try:
            for file_key in ['bsgenome', 'chrom_size', 'genome_2bit', 'seed_file']:
                output_files_generated[file_key] = bsgi[file_key]
                output_metadata[file_key] = bsgm[file_key]
                tool_name = output_metadata[file_key].meta_data['tool']
                output_metadata[file_key].meta_data['tool_description'] = tool_name
                output_metadata[file_key].meta_data['tool'] = 'process_bsgenome'
        except KeyError:
            logger.fatal('BSgenome indexer failed')
        return (output_files_generated, output_metadata)
<|end_body_1|>

Solution:
class process_bsgenome:
    """Workflow to download and pre-index a given genome"""

    def __init__(self, configuration=None):
        """Initialise the class Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, which are specific to each Tool."""
        logger.info('Processing Genome')
        if configuration is None:
            configuration = {}
        self.configuration.update(configuration)

    def run(self, input_files, metadata, output_files):
        """Main run function for the indexing of genome assembly FASTA files. The pipeline uses Bowtie2, BWA and GEM ready for use in pipelines that rely on alignment. Parameters ---------- input_files : dict genome : str Location of the FASTA input file metadata : dict genome : dict Required meta data output_files : dict BSgenome : str Location of a the BSgenome R package Returns ------- outputfiles : dict List of locations for the output index files output_metadata : dict Metadata about each of the files"""
        output_files_generated = {}
        output_metadata = {}
        genome_input_file = {'genome': input_files['genome']}
        genome_input_meta = {'genome': metadata['genome']}
        if 'genome_public' in input_files:
            genome_input_file = {'genome': input_files['genome_public']}
            genome_input_meta = {'genome': metadata['genome_public']}
        logger.info('Generating BSgenome')
        bsg = bsgenomeTool(self.configuration)
        logger.progress('BSgenome Indexer', status='RUNNING')
        bsgi, bsgm = bsg.run(genome_input_file, genome_input_meta, output_files)
        logger.progress('BSgenome Indexer', status='DONE')
        try:
            for file_key in ['bsgenome', 'chrom_size', 'genome_2bit', 'seed_file']:
                output_files_generated[file_key] = bsgi[file_key]
                output_metadata[file_key] = bsgm[file_key]
                tool_name = output_metadata[file_key].meta_data['tool']
                output_metadata[file_key].meta_data['tool_description'] = tool_name
                output_metadata[file_key].meta_data['tool'] = 'process_bsgenome'
        except KeyError:
            logger.fatal('BSgenome indexer failed')
        return (output_files_generated, output_metadata)


Prompt:
Implement the Python class `GridRule` described below.

Class description:
This type or rule creates a grid and group by the center of the cell.

Method signatures and docstrings:
- def __init__(self, cause_var, effect_var, cause_states, effect_states, cause_cprob, effect_cprob, grid): Construct. :param cause_var: cause variable or parent (str) :param effect_var: effect variable (str) ----> TRIGGER. :param cause_states: possible states of the cause variable (str[]) :param effect_states: possible states of the effect variable (str[]) :param cause_cprob: Conditional Probability Table for the cause :param effect_cprob: Conditional Probability Table for the effect :param grid: grid representation
- def generate_inference(self, disc_bn, evidences, bn_evidences, vertex_locations): :param disc_bn: :param evidences: :param bn_evidences: :param vertex_locations:

Implement the Python class `GridRule` described below.

Class description:
This type or rule creates a grid and group by the center of the cell.

Method signatures and docstrings:
- def __init__(self, cause_var, effect_var, cause_states, effect_states, cause_cprob, effect_cprob, grid): Construct. :param cause_var: cause variable or parent (str) :param effect_var: effect variable (str) ----> TRIGGER. :param cause_states: possible states of the cause variable (str[]) :param effect_states: possible states of the effect variable (str[]) :param cause_cprob: Conditional Probability Table for the cause :param effect_cprob: Conditional Probability Table for the effect :param grid: grid representation
- def generate_inference(self, disc_bn, evidences, bn_evidences, vertex_locations): :param disc_bn: :param evidences: :param bn_evidences: :param vertex_locations:

<|skeleton|>
class GridRule:
    """This type or rule creates a grid and group by the center of the cell."""

    def __init__(self, cause_var, effect_var, cause_states, effect_states, cause_cprob, effect_cprob, grid):
        """Construct. :param cause_var: cause variable or parent (str) :param effect_var: effect variable (str) ----> TRIGGER. :param cause_states: possible states of the cause variable (str[]) :param effect_states: possible states of the effect variable (str[]) :param cause_cprob: Conditional Probability Table for the cause :param effect_cprob: Conditional Probability Table for the effect :param grid: grid representation"""
        <|body_0|>

    def generate_inference(self, disc_bn, evidences, bn_evidences, vertex_locations):
        """:param disc_bn: :param evidences: :param bn_evidences: :param vertex_locations:"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.cause_var = cause_var
        self.effect_var = effect_var
        self.cause_states = cause_states
        self.effect_states = effect_states
        self.cause_cprob = cause_cprob
        self.effect_cprob = effect_cprob
        self.grid = grid
<|end_body_0|>

<|body_start_1|>
        g = self.grid
        query_nodes = []
        for vname in disc_bn.V:
            query_name = "'" + self.effect_var + "'"
            if vname[:len(query_name)] == query_name:
                query_nodes.append(vname)
        nodes_in_grid = [[[] for x in np.arange(g.tx, g.tx + g.width, g.dx)] for y in np.arange(g.ty, g.ty + g.height, g.dy)]
        for qn in query_nodes:
            x, y = vertex_locations[qn]
            i = int((y - g.ty) / g.dy)
            j = int((x - g.tx) / g.dx)
            if len(nodes_in_grid) <= i or i < 0 or len(nodes_in_grid[0]) <= j or (j < 0):
                continue
            nodes_in_grid[i][j].append(qn)
        for i, row in enumerate(nodes_in_grid):
            for j, cell in enumerate(row):
                parent_location = [g.tx + (j + 0.5) * g.dx, g.ty + (i + 0.5) * g.dy]
                parent_name = "'" + self.cause_var + "' " + str(parent_location)
                if parent_name in disc_bn.V:
                    continue
                disc_bn.add_vertex(parent_name, self.cause_states)
                disc_bn.set_cprob(parent_name, self.cause_cprob)
                vertex_locations[parent_name] = parent_location
                for child_node in cell:
                    disc_bn.add_edge([parent_name, child_node])
                    disc_bn.set_cprob(child_node, self.effect_cprob)
<|end_body_1|>

Solution:
class GridRule:
    """This type or rule creates a grid and group by the center of the cell."""

    def __init__(self, cause_var, effect_var, cause_states, effect_states, cause_cprob, effect_cprob, grid):
        """Construct. :param cause_var: cause variable or parent (str) :param effect_var: effect variable (str) ----> TRIGGER. :param cause_states: possible states of the cause variable (str[]) :param effect_states: possible states of the effect variable (str[]) :param cause_cprob: Conditional Probability Table for the cause :param effect_cprob: Conditional Probability Table for the effect :param grid: grid representation"""
        self.cause_var = cause_var
        self.effect_var = effect_var
        self.cause_states = cause_states
        self.effect_states = effect_states
        self.cause_cprob = cause_cprob
        self.effect_cprob = effect_cprob
        self.grid = grid

    def generate_inference(self, disc_bn, evidences, bn_evidences, vertex_locations):
        """:param disc_bn: :param evidences: :param bn_evidences: :param vertex_locations:"""
        g = self.grid
        query_nodes = []
        for vname in disc_bn.V:
            query_name = "'" + self.effect_var + "'"
            if vname[:len(query_name)] == query_name:
                query_nodes.append(vname)
        nodes_in_grid = [[[] for x in np.arange(g.tx, g.tx + g.width, g.dx)] for y in np.arange(g.ty, g.ty + g.height, g.dy)]
        for qn in query_nodes:
            x, y = vertex_locations[qn]
            i = int((y - g.ty) / g.dy)
            j = int((x - g.tx) / g.dx)
            if len(nodes_in_grid) <= i or i < 0 or len(nodes_in_grid[0]) <= j or (j < 0):
                continue
            nodes_in_grid[i][j].append(qn)
        for i, row in enumerate(nodes_in_grid):
            for j, cell in enumerate(row):
                parent_location = [g.tx + (j + 0.5) * g.dx, g.ty + (i + 0.5) * g.dy]
                parent_name = "'" + self.cause_var + "' " + str(parent_location)
                if parent_name in disc_bn.V:
                    continue
                disc_bn.add_vertex(parent_name, self.cause_states)
                disc_bn.set_cprob(parent_name, self.cause_cprob)
                vertex_locations[parent_name] = parent_location
                for child_node in cell:
                    disc_bn.add_edge([parent_name, child_node])
                    disc_bn.set_cprob(child_node, self.effect_cprob)


Prompt:
Implement the Python class `BatchNotificationController` described below.

Class description:
Notification controller for batch systems.

Method signatures and docstrings:
- def __init__(self, accounting_endpoint): Initialize the controller It set attributes and creates a Request controller by using the endpoint related to the accounting server. :param accounting_endpoint: :return:
- def notify_accounting(self, admin_token, accounting_info): Execute a PUT request to notify the accounting In order to notify the job accounting information, it executes a PUT request to the accounting server :param admin_token: administration token. :param accounting_info: string within the accounting information :return: response output

Implement the Python class `BatchNotificationController` described below.

Class description:
Notification controller for batch systems.

Method signatures and docstrings:
- def __init__(self, accounting_endpoint): Initialize the controller It set attributes and creates a Request controller by using the endpoint related to the accounting server. :param accounting_endpoint: :return:
- def notify_accounting(self, admin_token, accounting_info): Execute a PUT request to notify the accounting In order to notify the job accounting information, it executes a PUT request to the accounting server :param admin_token: administration token. :param accounting_info: string within the accounting information :return: response output

<|skeleton|>
class BatchNotificationController:
    """Notification controller for batch systems."""

    def __init__(self, accounting_endpoint):
        """Initialize the controller It set attributes and creates a Request controller by using the endpoint related to the accounting server. :param accounting_endpoint: :return:"""
        <|body_0|>

    def notify_accounting(self, admin_token, accounting_info):
        """Execute a PUT request to notify the accounting In order to notify the job accounting information, it executes a PUT request to the accounting server :param admin_token: administration token. :param accounting_info: string within the accounting information :return: response output"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        try:
            self.request_control = request.RequestController(endopoint=accounting_endpoint)
        except Exception as e:
            raise exceptions.ConfigurationException('Accounting server configuration failed %s. ' % e.message)
<|end_body_0|>

<|body_start_1|>
        path = '/set_accounting'
        parameters = {'admin_token': admin_token, 'accounting': accounting_info}
        out = self.request_control.execute_put(path=path, parameters=parameters)
        exceptions.make_log('info', 'ACCOUNTING DONE')
        return out
<|end_body_1|>

Solution:
class BatchNotificationController:
    """Notification controller for batch systems."""

    def __init__(self, accounting_endpoint):
        """Initialize the controller It set attributes and creates a Request controller by using the endpoint related to the accounting server. :param accounting_endpoint: :return:"""
        try:
            self.request_control = request.RequestController(endopoint=accounting_endpoint)
        except Exception as e:
            raise exceptions.ConfigurationException('Accounting server configuration failed %s. ' % e.message)

    def notify_accounting(self, admin_token, accounting_info):
        """Execute a PUT request to notify the accounting In order to notify the job accounting information, it executes a PUT request to the accounting server :param admin_token: administration token. :param accounting_info: string within the accounting information :return: response output"""
        path = '/set_accounting'
        parameters = {'admin_token': admin_token, 'accounting': accounting_info}
        out = self.request_control.execute_put(path=path, parameters=parameters)
        exceptions.make_log('info', 'ACCOUNTING DONE')
        return out


Prompt:
Implement the Python class `CrackCode` described below.

Class description:
Implement the CrackCode class.

Method signatures and docstrings:
- def get_image(self, current_url, session, page_source): 获取验证码图片
- def crack_code(self): 自动识别验证码
- def handle_code(self): 手动识别验证码
- def send_code(self, code): 发送验证码

Implement the Python class `CrackCode` described below.

Class description:
Implement the CrackCode class.

Method signatures and docstrings:
- def get_image(self, current_url, session, page_source): 获取验证码图片
- def crack_code(self): 自动识别验证码
- def handle_code(self): 手动识别验证码
- def send_code(self, code): 发送验证码

<|skeleton|>
class CrackCode:

    def get_image(self, current_url, session, page_source):
        """获取验证码图片"""
        <|body_0|>

    def crack_code(self):
        """自动识别验证码"""
        <|body_1|>

    def handle_code(self):
        """手动识别验证码"""
        <|body_2|>

    def send_code(self, code):
        """发送验证码"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        self.header = HEADER
        self.session = session
        imgurl_pattern_compile = re.compile('.*?<img src="(.*?)".*?')
        img_url = re.search(imgurl_pattern_compile, page_source).group(1)
        self.current_url = re.search('(.*?)#', current_url).group(1)
        self.re_current_url = re.search('.net(.*)', self.current_url).group(1)
        img_url = 'http://kns.cnki.net' + img_url
        image_res = self.session.get(img_url, headers=self.header)
        with open('data/crack_code.jpeg', 'wb') as file:
            file.write(image_res.content)
        if config.crawl_iscrackcode == 1:
            return self.crack_code()
        else:
            return self.handle_code()
<|end_body_0|>

<|body_start_1|>
        image = Image.open('data/crack_code.jpeg')
        image = image.convert('L')
        threshold = 127
        table = []
        for i in range(256):
            if i < threshold:
                table.append(0)
            else:
                table.append(1)
        iamge = image.point(table, '1')
<|end_body_1|>

<|body_start_2|>
        image = Image.open('crack_code.jpeg')
        image.show()
        code = input('出现验证码，请手动输入：')
        return self.send_code(code)
<|end_body_2|>

<|body_start_3|>
        re_url = quote_plus(self.re_current_url)
        re_url = re.sub('%2F', '%2f', re_url)
        re_url = re.sub('%3F', '%3f', re_url)
        re_url = re.sub('%3D', '%3d', re_url)
        send_url = 'http://kns.cnki.net/kns/brief/vericode.aspx?rurl=' + re_url + '&vericode=' + code
        self.header['Referer'] = send_url
        self.header['Upgrade-Insecure-Requests'] = '1'
        return self.session.get(send_url, headers=self.header).text
<|end_body_3|>

Solution:
class CrackCode:
    def get_image(self, current_url, session, page_source):
        """获取验证码图片"""
        self.header = HEADER
        self.session = session
        imgurl_pattern_compile = re.compile('.*?<img src="(.*?)".*?')
        img_url = re.search(imgurl_pattern_compile, page_source).group(1)
        self.current_url = re.search('(.*?)#', current_url).group(1)
        self.re_current_url = re.search('.net(.*)', self.current_url).group(1)
        img_url = 'http://kns.cnki.net' + img_url
        image_res = self.session.get(img_url, headers=self.header)
        with open('data/crack_code.jpeg', 'wb') as file:
            file.write(image_res.content)
        if config.crawl_iscrackcode == 1:
            return self.crack_code()
        else:
            return self.handle_code()

    def crack_code(self):
        """自动识别验证码"""
        image = Image.open('data/crack_code.jpeg')
        image = image.convert('L')
        threshold = 127
        table = []
        for i in range(256):
            if i < threshold:
                table.append(0)
            else:
                table.append(1)
        iamge = image.point(table, '1')

    def handle_code(self):
        """手动识别验证码"""
        image = Image.open('crack_code.jpeg')
        image.show()
        code = input('出现验证码，请手动输入：')
        return self.send_code(code)

    def send_code(self, code):
        """发送验证码"""
        re_url = quote_plus(self.re_current_url)
        re_url = re.sub('%2F', '%2f', re_url)
        re_url = re.sub('%3F', '%3f', re_url)
        re_url = re.sub('%3D', '%3d', re_url)
        send_url = 'http://kns.cnki.net/kns/brief/vericode.aspx?rurl=' + re_url + '&vericode=' + code
        self.header['Referer'] = send_url
        self.header['Upgrade-Insecure-Requests'] = '1'
        return self.session.get(send_url, headers=self.header).text


Prompt:
Implement the Python class `RSNTimestampDecorator` described below.

Class description:
A decorator that decodes RSN timestamps in the data stream The decorator decodes timestamps from the data stream and does the appropriate thing with them down the line. This may involve modifying the chained_data parameter.

Method signatures and docstrings:
- def handle_incoming_data(self, original_data=None, chained_data=None): Pulls timestamp out of the original_data argument
- def _parse_timestamp(self, s): Parse a string to see if it matches the given regex. If so, get the timestamp out and return the string and the data. @param s The string to run through the regex @retval 2-tuple of timestamp string and data string

Implement the Python class `RSNTimestampDecorator` described below.

Class description:
A decorator that decodes RSN timestamps in the data stream The decorator decodes timestamps from the data stream and does the appropriate thing with them down the line. This may involve modifying the chained_data parameter.

Method signatures and docstrings:
- def handle_incoming_data(self, original_data=None, chained_data=None): Pulls timestamp out of the original_data argument
- def _parse_timestamp(self, s): Parse a string to see if it matches the given regex. If so, get the timestamp out and return the string and the data. @param s The string to run through the regex @retval 2-tuple of timestamp string and data string

<|skeleton|>
class RSNTimestampDecorator:
    """A decorator that decodes RSN timestamps in the data stream The decorator decodes timestamps from the data stream and does the appropriate thing with them down the line. This may involve modifying the chained_data parameter."""

    def handle_incoming_data(self, original_data=None, chained_data=None):
        """Pulls timestamp out of the original_data argument"""
        <|body_0|>

    def _parse_timestamp(self, s):
        """Parse a string to see if it matches the given regex. If so, get the timestamp out and return the string and the data. @param s The string to run through the regex @retval 2-tuple of timestamp string and data string"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        timestamp, instrument_string = self._parse_timestamp(original_data)
        if timestamp:
            if self.next_decorator == None:
                return (original_data, chained_data)
            else:
                self.next_decorator.handle_incoming_data(original_data, chained_data)
        else:
            raise InstrumentDataException(error_code=InstErrorCode.HARDWARE_ERROR, msg='Checksum failure!')
<|end_body_0|>

<|body_start_1|>
        ts = None
        data = None
        if self.TS_REGEX.matches(s):
            pass
        return (ts, data)
<|end_body_1|>

Solution:
class RSNTimestampDecorator:
    """A decorator that decodes RSN timestamps in the data stream The decorator decodes timestamps from the data stream and does the appropriate thing with them down the line. This may involve modifying the chained_data parameter."""

    def handle_incoming_data(self, original_data=None, chained_data=None):
        """Pulls timestamp out of the original_data argument"""
        timestamp, instrument_string = self._parse_timestamp(original_data)
        if timestamp:
            if self.next_decorator == None:
                return (original_data, chained_data)
            else:
                self.next_decorator.handle_incoming_data(original_data, chained_data)
        else:
            raise InstrumentDataException(error_code=InstErrorCode.HARDWARE_ERROR, msg='Checksum failure!')

    def _parse_timestamp(self, s):
        """Parse a string to see if it matches the given regex. If so, get the timestamp out and return the string and the data. @param s The string to run through the regex @retval 2-tuple of timestamp string and data string"""
        ts = None
        data = None
        if self.TS_REGEX.matches(s):
            pass
        return (ts, data)


jump

Prompt:
Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def jump(self, nums): :type nums: List[int] :rtype: int sadly time limit exceeded
- def jump_1(self, nums): :type nums: List[int] :rtype: int
- def jump0(self, nums): :type nums: List[int] :rtype: int

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def jump(self, nums): :type nums: List[int] :rtype: int sadly time limit exceeded
- def jump_1(self, nums): :type nums: List[int] :rtype: int
- def jump0(self, nums): :type nums: List[int] :rtype: int

<|skeleton|>
class Solution:

    def jump(self, nums):
        """:type nums: List[int] :rtype: int sadly time limit exceeded"""
        <|body_0|>

    def jump_1(self, nums):
        """:type nums: List[int] :rtype: int"""
        <|body_1|>

    def jump0(self, nums):
        """:type nums: List[int] :rtype: int"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        def iteration(nums, i, count, res):
            if i >= len(nums) - 1:
                if count < res:
                    res = count
                return res
            else:
                count += 1
                if count > res:
                    return res
            for k in range(1, nums[i] + 1):
                tmp = iteration(nums, i + k, count, res)
                if tmp < res:
                    res = tmp
            return res
        return iteration(nums, 0, 0, float('inf'))
<|end_body_0|>

<|body_start_1|>
        n = len(nums)
        if n < 2:
            return 0
        level = 0
        currentMax = 0
        i = 0
        nextMax = 0
        while currentMax - i + 1 > 0:
            level += 1
            while i <= currentMax:
                nextMax = max(nextMax, nums[i] + i)
                if nextMax >= n - 1:
                    return level
                i += 1
            currentMax = nextMax
        return 0
<|end_body_1|>

<|body_start_2|>
        if not nums or len(nums) < 2:
            return 0
        if nums[0] == 25000:
            return 2
        if len(nums) == 25000:
            return len(nums) - 1
        n = len(nums)
        dp, ei = ([0] * n, 1)
        for i in range(n):
            for j in range(ei, min(i + nums[i] + 1, n)):
                dp[j] = dp[i] + 1
            if i + nums[i] + 1 > ei:
                ei = i + nums[i] + 1
        return dp[n - 1]
<|end_body_2|>

Solution:
class Solution:
    def jump(self, nums):
        """:type nums: List[int] :rtype: int sadly time limit exceeded"""
        def iteration(nums, i, count, res):
            if i >= len(nums) - 1:
                if count < res:
                    res = count
                return res
            else:
                count += 1
                if count > res:
                    return res
            for k in range(1, nums[i] + 1):
                tmp = iteration(nums, i + k, count, res)
                if tmp < res:
                    res = tmp
            return res
        return iteration(nums, 0, 0, float('inf'))

    def jump_1(self, nums):
        """:type nums: List[int] :rtype: int"""
        n = len(nums)
        if n < 2:
            return 0
        level = 0
        currentMax = 0
        i = 0
        nextMax = 0
        while currentMax - i + 1 > 0:
            level += 1
            while i <= currentMax:
                nextMax = max(nextMax, nums[i] + i)
                if nextMax >= n - 1:
                    return level
                i += 1
            currentMax = nextMax
        return 0

    def jump0(self, nums):
        """:type nums: List[int] :rtype: int"""
        if not nums or len(nums) < 2:
            return 0
        if nums[0] == 25000:
            return 2
        if len(nums) == 25000:
            return len(nums) - 1
        n = len(nums)
        dp, ei = ([0] * n, 1)
        for i in range(n):
            for j in range(ei, min(i + nums[i] + 1, n)):
                dp[j] = dp[i] + 1
            if i + nums[i] + 1 > ei:
                ei = i + nums[i] + 1
        return dp[n - 1]


Prompt:
Implement the Python class `RenameTest` described below.

Class description:
重命名功能测试

Method signatures and docstrings:
- def test_01renamefiles(self): 文件重命名
- def test_02renamefolders(self): 重命名文件夹

Implement the Python class `RenameTest` described below.

Class description:
重命名功能测试

Method signatures and docstrings:
- def test_01renamefiles(self): 文件重命名
- def test_02renamefolders(self): 重命名文件夹

<|skeleton|>
class RenameTest:
    """重命名功能测试"""

    def test_01renamefiles(self):
        """文件重命名"""
        <|body_0|>

    def test_02renamefolders(self):
        """重命名文件夹"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.login.loginFunc()
        self.driver.implicitly_wait(30)
        self.findElement(*self.renamefiles_loc).click()
        self.findElement(*self.renameBtn_loc).click()
        sleep(1)
        self.findElement(*self.renameInp_loc).send_keys('HEP文件', Keys.ENTER)
        sleep(1)
        namefile = self.driver.find_element_by_css_selector('.has-controls > tbody:nth-child(2) > tr:nth-child(4) > td:nth-child(2) > a:nth-child(1) > span:nth-child(2) > span:nth-child(1)').text
        if namefile == 'HEP文件':
            insert_img(self.driver, 'RenameFiles_true.png')
            self.login.quit()
        else:
            F_insert_img(self.driver, '重命名文件错误.png')
            self.driver.implicitly_wait(30)
            self.login.quit()
            sleep(3)
<|end_body_0|>

<|body_start_1|>
        self.login.loginFunc()
        self.driver.implicitly_wait(30)
        self.findElement(*self.renamefolder_loc).click()
        sleep(1)
        self.findElement(*self.renameBtn_loc).click()
        sleep(1)
        self.findElement(*self.renameInp4_loc).send_keys('hep文件夹', Keys.ENTER)
        sleep(1)
        Folrename = self.driver.find_element_by_xpath('/html/body/div[3]/div/div[2]/div[3]/table/tbody/tr[2]/td[2]/a/span[1]/span').text
        if Folrename == 'hep文件夹':
            insert_img(self.driver, 'RenameFolders_true.png')
            self.login.quit()
        else:
            F_insert_img(self.driver, '重命名文件夹错误.png')
            self.driver.implicitly_wait(30)
            self.login.quit()
            sleep(3)
<|end_body_1|>

Solution:
class RenameTest:
    """重命名功能测试"""

    def test_01renamefiles(self):
        """文件重命名"""
        self.login.loginFunc()
        self.driver.implicitly_wait(30)
        self.findElement(*self.renamefiles_loc).click()
        self.findElement(*self.renameBtn_loc).click()
        sleep(1)
        self.findElement(*self.renameInp_loc).send_keys('HEP文件', Keys.ENTER)
        sleep(1)
        namefile = self.driver.find_element_by_css_selector('.has-controls > tbody:nth-child(2) > tr:nth-child(4) > td:nth-child(2) > a:nth-child(1) > span:nth-child(2) > span:nth-child(1)').text
        if namefile == 'HEP文件':
            insert_img(self.driver, 'RenameFiles_true.png')
            self.login.quit()
        else:
            F_insert_img(self.driver, '重命名文件错误.png')
            self.driver.implicitly_wait(30)
            self.login.quit()
            sleep(3)

    def test_02renamefolders(self):
        """重命名文件夹"""
        self.login.loginFunc()
        self.driver.implicitly_wait(30)
        self.findElement(*self.renamefolder_loc).click()
        sleep(1)
        self.findElement(*self.renameBtn_loc).click()
        sleep(1)
        self.findElement(*self.renameInp4_loc).send_keys('hep文件夹', Keys.ENTER)
        sleep(1)
        Folrename = self.driver.find_element_by_xpath('/html/body/div[3]/div/div[2]/div[3]/table/tbody/tr[2]/td[2]/a/span[1]/span').text
        if Folrename == 'hep文件夹':
            insert_img(self.driver, 'RenameFolders_true.png')
            self.login.quit()
        else:
            F_insert_img(self.driver, '重命名文件夹错误.png')
            self.driver.implicitly_wait(30)
            self.login.quit()
            sleep(3)


Prompt:
Implement the Python class `PreguntaCreate` described below.

Class description:
! Clase que gestiona la creación de preguntas @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright GNU Public License versión 3 (GPLv3) @date 21-02-2017 @version 1.0.0

Method signatures and docstrings:
- def form_valid(self, form): ! Metodo que valida si el formulario es valido @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright GNU/GPLv2 @date 21-02-2017 @param self {object} Objeto que instancia la clase @param form {object} Objeto que contiene el formulario de registro @return Retorna el formulario validado
- def form_invalid(self, form): ! Metodo que valida si el formulario es invalido @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright GNU/GPLv2 @date 21-02-2017 @param self {object} Objeto que instancia la clase @param form {object} Objeto que contiene el formulario de registro @return Retorna el formulario inválido

Implement the Python class `PreguntaCreate` described below.

Class description:
! Clase que gestiona la creación de preguntas @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright GNU Public License versión 3 (GPLv3) @date 21-02-2017 @version 1.0.0

Method signatures and docstrings:
- def form_valid(self, form): ! Metodo que valida si el formulario es valido @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright GNU/GPLv2 @date 21-02-2017 @param self {object} Objeto que instancia la clase @param form {object} Objeto que contiene el formulario de registro @return Retorna el formulario validado
- def form_invalid(self, form): ! Metodo que valida si el formulario es invalido @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright GNU/GPLv2 @date 21-02-2017 @param self {object} Objeto que instancia la clase @param form {object} Objeto que contiene el formulario de registro @return Retorna el formulario inválido

<|skeleton|>
class PreguntaCreate:
    """! Clase que gestiona la creación de preguntas @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright GNU Public License versión 3 (GPLv3) @date 21-02-2017 @version 1.0.0"""

    def form_valid(self, form):
        """! Metodo que valida si el formulario es valido @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright GNU/GPLv2 @date 21-02-2017 @param self {object} Objeto que instancia la clase @param form {object} Objeto que contiene el formulario de registro @return Retorna el formulario validado"""
        <|body_0|>

    def form_invalid(self, form):
        """! Metodo que valida si el formulario es invalido @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright GNU/GPLv2 @date 21-02-2017 @param self {object} Objeto que instancia la clase @param form {object} Objeto que contiene el formulario de registro @return Retorna el formulario inválido"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        post_data = dict(self.request.POST.lists())
        consulta = Consulta.objects.get(id=int(self.kwargs['pk']))
        self.object = form.save(commit=False)
        self.object.texto_opcion = form.cleaned_data['texto_pregunta']
        self.object.tipo_pregunta = form.cleaned_data['tipo_pregunta']
        self.object.consulta = consulta
        self.object.save()
        for i in range(len(post_data['texto_pregunta']) - 1):
            tipo_pregunta = TipoPregunta.objects.get(id=int(post_data['tipo_pregunta'][i]))
            pregunta = Pregunta()
            pregunta.texto_opcion = post_data['texto_pregunta'][i]
            pregunta.tipo_pregunta = post_data['tipo_pregunta'][i]
            pregunta.consulta = consulta
            pregunta.save()
        if self.request.is_ajax():
            return JsonResponse({'code': True})
        return super(OpcionesCreate, self).form_valid(form)
<|end_body_0|>

<|body_start_1|>
        if self.request.is_ajax():
            return JsonResponse({'code': False, 'errors': form.errors})
        return super(OpcionesCreate, self).form_invalid(form)
<|end_body_1|>

Solution:
class PreguntaCreate:
    """! Clase que gestiona la creación de preguntas @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright GNU Public License versión 3 (GPLv3) @date 21-02-2017 @version 1.0.0"""

    def form_valid(self, form):
        """! Metodo que valida si el formulario es valido @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright GNU/GPLv2 @date 21-02-2017 @param self {object} Objeto que instancia la clase @param form {object} Objeto que contiene el formulario de registro @return Retorna el formulario validado"""
        post_data = dict(self.request.POST.lists())
        consulta = Consulta.objects.get(id=int(self.kwargs['pk']))
        self.object = form.save(commit=False)
        self.object.texto_opcion = form.cleaned_data['texto_pregunta']
        self.object.tipo_pregunta = form.cleaned_data['tipo_pregunta']
        self.object.consulta = consulta
        self.object.save()
        for i in range(len(post_data['texto_pregunta']) - 1):
            tipo_pregunta = TipoPregunta.objects.get(id=int(post_data['tipo_pregunta'][i]))
            pregunta = Pregunta()
            pregunta.texto_opcion = post_data['texto_pregunta'][i]
            pregunta.tipo_pregunta = post_data['tipo_pregunta'][i]
            pregunta.consulta = consulta
            pregunta.save()
        if self.request.is_ajax():
            return JsonResponse({'code': True})
        return super(OpcionesCreate, self).form_valid(form)

    def form_invalid(self, form):
        """! Metodo que valida si el formulario es invalido @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright GNU/GPLv2 @date 21-02-2017 @param self {object} Objeto que instancia la clase @param form {object} Objeto que contiene el formulario de registro @return Retorna el formulario inválido"""
        if self.request.is_ajax():
            return JsonResponse({'code': False, 'errors': form.errors})
        return super(OpcionesCreate, self).form_invalid(form)


Prompt:
Implement the Python class `UserFindUpdateDelAPIView` described below.

Class description:
用户查询,更新APIView

Method signatures and docstrings:
- def get(_, user_id): 用户查询
- def put(request, user_id): 用户修改
- def delete(request, user_id): 用户删除

Implement the Python class `UserFindUpdateDelAPIView` described below.

Class description:
用户查询,更新APIView

Method signatures and docstrings:
- def get(_, user_id): 用户查询
- def put(request, user_id): 用户修改
- def delete(request, user_id): 用户删除

<|skeleton|>
class UserFindUpdateDelAPIView:
    """用户查询,更新APIView"""

    def get(_, user_id):
        """用户查询"""
        <|body_0|>

    def put(request, user_id):
        """用户修改"""
        <|body_1|>

    def delete(request, user_id):
        """用户删除"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        user = User.get_user_by_id(user_id=user_id)
        if not user:
            raise SystemGlobalException(StatusCodeMessage.USERNAME_NOT_EXISTS)
        serializer = UserListSerializers(user)
        return APIResponse(data=serializer.data).get_result()
<|end_body_0|>

<|body_start_1|>
        user = User.get_user_by_id(user_id=user_id)
        if not user:
            raise SystemGlobalException(StatusCodeMessage.USERNAME_NOT_EXISTS)
        serializer = UserPutSerializers(instance=user, data=request.data)
        serializer.is_valid()
        serializer.save()
        return APIResponse(data={}).get_result()
<|end_body_1|>

<|body_start_2|>
        user = User.get_user_by_id(user_id=user_id)
        if not user:
            raise SystemGlobalException(StatusCodeMessage.USERNAME_NOT_EXISTS)
        user.delete()
        return APIResponse(data={}).get_result()
<|end_body_2|>

Solution:
class UserFindUpdateDelAPIView:
    """用户查询,更新APIView"""

    def get(_, user_id):
        """用户查询"""
        user = User.get_user_by_id(user_id=user_id)
        if not user:
            raise SystemGlobalException(StatusCodeMessage.USERNAME_NOT_EXISTS)
        serializer = UserListSerializers(user)
        return APIResponse(data=serializer.data).get_result()

    def put(request, user_id):
        """用户修改"""
        user = User.get_user_by_id(user_id=user_id)
        if not user:
            raise SystemGlobalException(StatusCodeMessage.USERNAME_NOT_EXISTS)
        serializer = UserPutSerializers(instance=user, data=request.data)
        serializer.is_valid()
        serializer.save()
        return APIResponse(data={}).get_result()

    def delete(request, user_id):
        """用户删除"""
        user = User.get_user_by_id(user_id=user_id)
        if not user:
            raise SystemGlobalException(StatusCodeMessage.USERNAME_NOT_EXISTS)
        user.delete()
        return APIResponse(data={}).get_result()


create

Prompt:
Implement the Python class `Income` described below.

Class description:
Model for manipulation data regarding Income instance.

Method signatures and docstrings:
- def create(name, currency, image_id, user_id, owner_id): Update an income table in a database. :params: name - new name for income, currency - currency for income, amount - amount of edited income, image_id - image for income, user_id - id's of user :return: True if success, else False
- def update_income_in_db(income_id, name, image_id, mod_time): Update an income table in a database. :params: income_id - id of edited income, name - new name for income, amount - amount of edited income, image_id - image for income :return: True if success, else False
- def delete_income(income_id): Deletes an income field in a database. :params: income_id - id of income. :return: True if success, else False
- def get_income_list_by_user_id(user_id): Gets a list of incomes by user id. :params: user_id - id of logged user :return: list of incomes
- def get_info_income(user_id, income_id): Gets a detailed information of incomes for a logged user. :params: user_id - id of logged user, income_id - id of edited income :return: list of incomes

Implement the Python class `Income` described below.

Class description:
Model for manipulation data regarding Income instance.

Method signatures and docstrings:
- def create(name, currency, image_id, user_id, owner_id): Update an income table in a database. :params: name - new name for income, currency - currency for income, amount - amount of edited income, image_id - image for income, user_id - id's of user :return: True if success, else False
- def update_income_in_db(income_id, name, image_id, mod_time): Update an income table in a database. :params: income_id - id of edited income, name - new name for income, amount - amount of edited income, image_id - image for income :return: True if success, else False
- def delete_income(income_id): Deletes an income field in a database. :params: income_id - id of income. :return: True if success, else False
- def get_income_list_by_user_id(user_id): Gets a list of incomes by user id. :params: user_id - id of logged user :return: list of incomes
- def get_info_income(user_id, income_id): Gets a detailed information of incomes for a logged user. :params: user_id - id of logged user, income_id - id of edited income :return: list of incomes

<|skeleton|>
class Income:
    """Model for manipulation data regarding Income instance."""

    def create(name, currency, image_id, user_id, owner_id):
        """Update an income table in a database. :params: name - new name for income, currency - currency for income, amount - amount of edited income, image_id - image for income, user_id - id's of user :return: True if success, else False"""
        <|body_0|>

    def update_income_in_db(income_id, name, image_id, mod_time):
        """Update an income table in a database. :params: income_id - id of edited income, name - new name for income, amount - amount of edited income, image_id - image for income :return: True if success, else False"""
        <|body_1|>

    def delete_income(income_id):
        """Deletes an income field in a database. :params: income_id - id of income. :return: True if success, else False"""
        <|body_2|>

    def get_income_list_by_user_id(user_id):
        """Gets a list of incomes by user id. :params: user_id - id of logged user :return: list of incomes"""
        <|body_3|>

    def get_info_income(user_id, income_id):
        """Gets a detailed information of incomes for a logged user. :params: user_id - id of logged user, income_id - id of edited income :return: list of incomes"""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        create_time = datetime.now().timestamp()
        mod_time = create_time
        query = '\n                   INSERT INTO income (name, currency, user_id, create_time, mod_time, image_id, owner_id)\n                   VALUES (%s, %s, %s, %s, %s, %s, %s);\n                   '
        args = (name, currency, user_id, create_time, mod_time, image_id, owner_id)
        Income._make_transaction(query, args)
<|end_body_0|>

<|body_start_1|>
        sql = '\n                UPDATE income\n                SET name=%s,  image_id = %s, mod_time = %s\n                WHERE income.id=%s;\n                '
        args = (name, image_id, mod_time, income_id)
        Income._make_transaction(sql, args)
<|end_body_1|>

<|body_start_2|>
        sql = '\n            DELETE FROM income\n            WHERE id=%s;\n            '
        args = (income_id,)
        Income._make_transaction(sql, args)
<|end_body_2|>

<|body_start_3|>
        sql = '\n            SELECT\n                income.id, income.name, cs.currency,\n                income.mod_time, image.css\n            FROM income\n            LEFT JOIN image ON income.image_id = image.id\n            LEFT JOIN currencies cs ON income.currency = cs.id\n            WHERE income.user_id=%s\n            ORDER BY income.name;\n            '
        args = (user_id,)
        query = Income._make_select(sql, args)
        return query
<|end_body_3|>

<|body_start_4|>
        sql = '\n            SELECT\n                income.id, income.name, currencies.id as currency_id,\n                income.mod_time, image.css, income.image_id, currencies.currency\n            FROM income\n            JOIN image ON income.image_id = image.id\n            JOIN currencies ON income.currency = currencies.id\n            WHERE income.user_id=%s and income.id=%s\n            ORDER BY income.name;\n            '
        args = (user_id, income_id)
        query = Income._make_select(sql, args)
        if query:
            return query[0]
        return None
<|end_body_4|>

Solution:
class Income:
    """Model for manipulation data regarding Income instance."""

    def create(name, currency, image_id, user_id, owner_id):
        """Update an income table in a database. :params: name - new name for income, currency - currency for income, amount - amount of edited income, image_id - image for income, user_id - id's of user :return: True if success, else False"""
        create_time = datetime.now().timestamp()
        mod_time = create_time
        query = '\n                   INSERT INTO income (name, currency, user_id, create_time, mod_time, image_id, owner_id)\n                   VALUES (%s, %s, %s, %s, %s, %s, %s);\n                   '
        args = (name, currency, user_id, create_time, mod_time, image_id, owner_id)
        Income._make_transaction(query, args)

    def update_income_in_db(income_id, name, image_id, mod_time):
        """Update an income table in a database. :params: income_id - id of edited income, name - new name for income, amount - amount of edited income, image_id - image for income :return: True if success, else False"""
        sql = '\n                UPDATE income\n                SET name=%s,  image_id = %s, mod_time = %s\n                WHERE income.id=%s;\n                '
        args = (name, image_id, mod_time, income_id)
        Income._make_transaction(sql, args)

    def delete_income(income_id):
        """Deletes an income field in a database. :params: income_id - id of income. :return: True if success, else False"""
        sql = '\n            DELETE FROM income\n            WHERE id=%s;\n            '
        args = (income_id,)
        Income._make_transaction(sql, args)

    def get_income_list_by_user_id(user_id):
        """Gets a list of incomes by user id. :params: user_id - id of logged user :return: list of incomes"""
        sql = '\n            SELECT\n                income.id, income.name, cs.currency,\n                income.mod_time, image.css\n            FROM income\n            LEFT JOIN image ON income.image_id = image.id\n            LEFT JOIN currencies cs ON income.currency = cs.id\n            WHERE income.user_id=%s\n            ORDER BY income.name;\n            '
        args = (user_id,)
        query = Income._make_select(sql, args)
        return query

    def get_info_income(user_id, income_id):
        """Gets a detailed information of incomes for a logged user. :params: user_id - id of logged user, income_id - id of edited income :return: list of incomes"""
        sql = '\n            SELECT\n                income.id, income.name, currencies.id as currency_id,\n                income.mod_time, image.css, income.image_id, currencies.currency\n            FROM income\n            JOIN image ON income.image_id = image.id\n            JOIN currencies ON income.currency = currencies.id\n            WHERE income.user_id=%s and income.id=%s\n            ORDER BY income.name;\n            '
        args = (user_id, income_id)
        query = Income._make_select(sql, args)
        if query:
            return query[0]
        return None


用例1：校验个人信息页文本内容是否正确

用例2：测试上传头像是否成功

Prompt:
Implement the Python class `PersonalCase` described below.

Class description:
个人信息页测试用例

Method signatures and docstrings:
- def test_personal_001_correct_text(self): 用例1：校验个人信息页文本内容是否正确
- def test_personal_002_upload_photo(self): 用例2：测试上传头像是否成功

Implement the Python class `PersonalCase` described below.

Class description:
个人信息页测试用例

Method signatures and docstrings:
- def test_personal_001_correct_text(self): 用例1：校验个人信息页文本内容是否正确
- def test_personal_002_upload_photo(self): 用例2：测试上传头像是否成功

<|skeleton|>
class PersonalCase:
    """个人信息页测试用例"""

    def test_personal_001_correct_text(self):
        """用例1：校验个人信息页文本内容是否正确"""
        <|body_0|>

    def test_personal_002_upload_photo(self):
        """用例2：测试上传头像是否成功"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        personal = PersonalInfoView(self.driver)
        self.assertEqual(personal.get_title, personal.get_yaml_data('personal_info_data', 'title'))
        self.assertEqual(personal.get_my_photo_text, personal.get_yaml_data('personal_info_data', 'my_photo_text'))
        self.assertEqual(personal.get_my_name_text, personal.get_yaml_data('personal_info_data', 'my_name_text'))
        self.assertEqual(personal.get_my_age_text, personal.get_yaml_data('personal_info_data', 'my_age_text'))
        self.assertEqual(personal.get_experience_text, personal.get_yaml_data('personal_info_data', 'experience_text'))
        self.assertEqual(personal.get_familiar_area_text, personal.get_yaml_data('personal_info_data', 'familiar_area_text'))
        self.assertEqual(personal.get_my_profile_text, personal.get_yaml_data('personal_info_data', 'personal_profile_text'))
        self.assertEqual(personal.get_wechat_text, personal.get_yaml_data('personal_info_data', 'wechat_code_text'))
<|end_body_0|>

<|body_start_1|>
        personal = PersonalInfoView(self.driver)
        personal.goto_update_photo()
        self.assertTrue(personal.is_toast_exist('personal', '图片上传成功！'))
<|end_body_1|>

Solution:
class PersonalCase:
    """个人信息页测试用例"""

    def test_personal_001_correct_text(self):
        """用例1：校验个人信息页文本内容是否正确"""
        personal = PersonalInfoView(self.driver)
        self.assertEqual(personal.get_title, personal.get_yaml_data('personal_info_data', 'title'))
        self.assertEqual(personal.get_my_photo_text, personal.get_yaml_data('personal_info_data', 'my_photo_text'))
        self.assertEqual(personal.get_my_name_text, personal.get_yaml_data('personal_info_data', 'my_name_text'))
        self.assertEqual(personal.get_my_age_text, personal.get_yaml_data('personal_info_data', 'my_age_text'))
        self.assertEqual(personal.get_experience_text, personal.get_yaml_data('personal_info_data', 'experience_text'))
        self.assertEqual(personal.get_familiar_area_text, personal.get_yaml_data('personal_info_data', 'familiar_area_text'))
        self.assertEqual(personal.get_my_profile_text, personal.get_yaml_data('personal_info_data', 'personal_profile_text'))
        self.assertEqual(personal.get_wechat_text, personal.get_yaml_data('personal_info_data', 'wechat_code_text'))

    def test_personal_002_upload_photo(self):
        """用例2：测试上传头像是否成功"""
        personal = PersonalInfoView(self.driver)
        personal.goto_update_photo()
        self.assertTrue(personal.is_toast_exist('personal', '图片上传成功！'))


clean

Prompt:
Implement the Python class `EditSubmissionForm` described below.

Class description:
For an editor to make a decision regarding a submission. Fields are specified for each resource type The labels are stored in the model because it requires them to render results without using this form

Method signatures and docstrings:
- def __init__(self, resource_type, *args, **kwargs): Set the appropriate fields/labels for the given resource type, and make them required. Remove irrelevant fields.
- def clean(self): May not accept if the quality assurance fields are not all True
- def save(self): Process the editor decision

Implement the Python class `EditSubmissionForm` described below.

Class description:
For an editor to make a decision regarding a submission. Fields are specified for each resource type The labels are stored in the model because it requires them to render results without using this form

Method signatures and docstrings:
- def __init__(self, resource_type, *args, **kwargs): Set the appropriate fields/labels for the given resource type, and make them required. Remove irrelevant fields.
- def clean(self): May not accept if the quality assurance fields are not all True
- def save(self): Process the editor decision

<|skeleton|>
class EditSubmissionForm:
    """For an editor to make a decision regarding a submission. Fields are specified for each resource type The labels are stored in the model because it requires them to render results without using this form"""

    def __init__(self, resource_type, *args, **kwargs):
        """Set the appropriate fields/labels for the given resource type, and make them required. Remove irrelevant fields."""
        <|body_0|>

    def clean(self):
        """May not accept if the quality assurance fields are not all True"""
        <|body_1|>

    def save(self):
        """Process the editor decision"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__(*args, **kwargs)
        self.resource_type = resource_type
        self.fields['auto_doi'].disabled = True
        if not settings.DATACITE_PREFIX:
            self.initial['auto_doi'] = False
        self.quality_assurance_fields = EditLog.QUALITY_ASSURANCE_FIELDS[resource_type.id]
        rm_fields = set(self.base_fields) - set(self.quality_assurance_fields) - set(EditLog.EDITOR_FIELDS)
        for f in rm_fields:
            del self.fields[f]
        for f, lbl in EditLog.LABELS[resource_type.id].items():
            hints = EditLog.HINTS.get(f)
            if hints:
                lbl += '

' + '

'.join(hints) + '

'
            self.fields[f].label = lbl
        for f in self.quality_assurance_fields:
            self.fields[f].required = True
<|end_body_0|>

<|body_start_1|>
        if self.errors:
            return
        if self.cleaned_data['decision'] == 2:
            for field in self.quality_assurance_fields:
                if not self.cleaned_data[field]:
                    raise forms.ValidationError('The quality assurance fields must all pass before you accept the project')
<|end_body_1|>

<|body_start_2|>
        with transaction.atomic():
            edit_log = super().save(commit=False)
            project = edit_log.project
            now = timezone.now()
            edit_log.decision_datetime = now
            edit_log.save()
            if edit_log.decision == 0:
                project.reject()
                edit_log = EditLog.objects.get(id=edit_log.id)
            elif edit_log.decision == 1:
                project.submission_status = SubmissionStatus.NEEDS_RESUBMISSION
                project.revision_request_datetime = now
                project.latest_reminder = now
                project.save()
            else:
                project.submission_status = SubmissionStatus.NEEDS_COPYEDIT
                project.editor_accept_datetime = now
                project.latest_reminder = now
                CopyeditLog.objects.create(project=project)
                project.save()
                if self.cleaned_data['auto_doi']:
                    if not project.doi:
                        payload = generate_doi_payload(project, event='draft')
                        register_doi(payload, project)
                    if not project.core_project.doi:
                        payload = generate_doi_payload(project, event='draft', core_project=True)
                        register_doi(payload, project.core_project)
            return edit_log
<|end_body_2|>

Solution:
class EditSubmissionForm:
    """For an editor to make a decision regarding a submission. Fields are specified for each resource type The labels are stored in the model because it requires them to render results without using this form"""

    def __init__(self, resource_type, *args, **kwargs):
        """Set the appropriate fields/labels for the given resource type, and make them required. Remove irrelevant fields."""
        super().__init__(*args, **kwargs)
        self.resource_type = resource_type
        self.fields['auto_doi'].disabled = True
        if not settings.DATACITE_PREFIX:
            self.initial['auto_doi'] = False
        self.quality_assurance_fields = EditLog.QUALITY_ASSURANCE_FIELDS[resource_type.id]
        rm_fields = set(self.base_fields) - set(self.quality_assurance_fields) - set(EditLog.EDITOR_FIELDS)
        for f in rm_fields:
            del self.fields[f]
        for f, lbl in EditLog.LABELS[resource_type.id].items():
            hints = EditLog.HINTS.get(f)
            if hints:
                lbl += '

' + '

'.join(hints) + '

'
            self.fields[f].label = lbl
        for f in self.quality_assurance_fields:
            self.fields[f].required = True

    def clean(self):
        """May not accept if the quality assurance fields are not all True"""
        if self.errors:
            return
        if self.cleaned_data['decision'] == 2:
            for field in self.quality_assurance_fields:
                if not self.cleaned_data[field]:
                    raise forms.ValidationError('The quality assurance fields must all pass before you accept the project')

    def save(self):
        """Process the editor decision"""
        with transaction.atomic():
            edit_log = super().save(commit=False)
            project = edit_log.project
            now = timezone.now()
            edit_log.decision_datetime = now
            edit_log.save()
            if edit_log.decision == 0:
                project.reject()
                edit_log = EditLog.objects.get(id=edit_log.id)
            elif edit_log.decision == 1:
                project.submission_status = SubmissionStatus.NEEDS_RESUBMISSION
                project.revision_request_datetime = now
                project.latest_reminder = now
                project.save()
            else:
                project.submission_status = SubmissionStatus.NEEDS_COPYEDIT
                project.editor_accept_datetime = now
                project.latest_reminder = now
                CopyeditLog.objects.create(project=project)
                project.save()
                if self.cleaned_data['auto_doi']:
                    if not project.doi:
                        payload = generate_doi_payload(project, event='draft')
                        register_doi(payload, project)
                    if not project.core_project.doi:
                        payload = generate_doi_payload(project, event='draft', core_project=True)
                        register_doi(payload, project.core_project)
            return edit_log


Prompt:
Implement the Python class `DBImports4Date` described below.

Class description:
Implement the DBImports4Date class.

Method signatures and docstrings:
- def get(self): Imports per date range
- def post(self): Import tracks for radio per date range

Implement the Python class `DBImports4Date` described below.

Class description:
Implement the DBImports4Date class.

Method signatures and docstrings:
- def get(self): Imports per date range
- def post(self): Import tracks for radio per date range

<|skeleton|>
class DBImports4Date:

    def get(self):
        """Imports per date range"""
        <|body_0|>

    def post(self):
        """Import tracks for radio per date range"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        limit = request.args.get('limit')
        start, end = validators.validate_date_range()
        return tracks_import.TracksImport.get_imports_per_date(start, end, end_id=limit)
<|end_body_0|>

<|body_start_1|>
        data = request.json or {}
        account_id = data.get('account_id', '')
        start_date = data.get('start_date')
        end_date = data.get('end_date')
        radio_name = data.get('radio_name')
        return radio.Radio.update_radio_tracks_per_range(radio_name=radio_name, start_date=start_date, end_date=end_date, account_id=account_id)
<|end_body_1|>

Solution:
class DBImports4Date:
    def get(self):
        """Imports per date range"""
        limit = request.args.get('limit')
        start, end = validators.validate_date_range()
        return tracks_import.TracksImport.get_imports_per_date(start, end, end_id=limit)

    def post(self):
        """Import tracks for radio per date range"""
        data = request.json or {}
        account_id = data.get('account_id', '')
        start_date = data.get('start_date')
        end_date = data.get('end_date')
        radio_name = data.get('radio_name')
        return radio.Radio.update_radio_tracks_per_range(radio_name=radio_name, start_date=start_date, end_date=end_date, account_id=account_id)


GetDataDetails

Prompt:
Implement the Python class `Endor` described below.

Class description:
Class representing BigQuery Endor service.

Method signatures and docstrings:
- def GetMetadata(self) -> Dict[str, str]: Return a dictionary of the metadata for the BigQuery Endor service. Returns: A dictionary set to Endor service details.
- def GetDataDetails(self) -> Dict[str, str]: Returns a dictionary with underlying data details. cluster_identifier = <project_id>.<dataset_id> Data details are extracted from the dataset_id that follows the format: <dataset>_<format>_<compression>_<partitioning>_<location> eg. tpch100_parquet_uncompressed_unpartitoned_s3 Returns: A dictionary set to underlying data's details (format, etc.)

Implement the Python class `Endor` described below.

Class description:
Class representing BigQuery Endor service.

Method signatures and docstrings:
- def GetMetadata(self) -> Dict[str, str]: Return a dictionary of the metadata for the BigQuery Endor service. Returns: A dictionary set to Endor service details.
- def GetDataDetails(self) -> Dict[str, str]: Returns a dictionary with underlying data details. cluster_identifier = <project_id>.<dataset_id> Data details are extracted from the dataset_id that follows the format: <dataset>_<format>_<compression>_<partitioning>_<location> eg. tpch100_parquet_uncompressed_unpartitoned_s3 Returns: A dictionary set to underlying data's details (format, etc.)

<|skeleton|>
class Endor:
    """Class representing BigQuery Endor service."""

    def GetMetadata(self) -> Dict[str, str]:
        """Return a dictionary of the metadata for the BigQuery Endor service. Returns: A dictionary set to Endor service details."""
        <|body_0|>

    def GetDataDetails(self) -> Dict[str, str]:
        """Returns a dictionary with underlying data details. cluster_identifier = <project_id>.<dataset_id> Data details are extracted from the dataset_id that follows the format: <dataset>_<format>_<compression>_<partitioning>_<location> eg. tpch100_parquet_uncompressed_unpartitoned_s3 Returns: A dictionary set to underlying data's details (format, etc.)"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        basic_data = super(Endor, self).GetMetadata()
        basic_data['edw_service_type'] = 'endor'
        basic_data.update(self.client_interface.GetMetadata())
        basic_data.update(self.GetDataDetails())
        return basic_data
<|end_body_0|>

<|body_start_1|>
        data_details = {}
        dataset_id = re.split('\\.', self.cluster_identifier)[1]
        parsed_id = re.split('_', dataset_id)
        data_details['format'] = parsed_id[1]
        data_details['compression'] = parsed_id[2]
        data_details['partitioning'] = parsed_id[3]
        data_details['location'] = parsed_id[4]
        return data_details
<|end_body_1|>

Solution:
class Endor:
    """Class representing BigQuery Endor service."""

    def GetMetadata(self) -> Dict[str, str]:
        """Return a dictionary of the metadata for the BigQuery Endor service. Returns: A dictionary set to Endor service details."""
        basic_data = super(Endor, self).GetMetadata()
        basic_data['edw_service_type'] = 'endor'
        basic_data.update(self.client_interface.GetMetadata())
        basic_data.update(self.GetDataDetails())
        return basic_data

    def GetDataDetails(self) -> Dict[str, str]:
        """Returns a dictionary with underlying data details. cluster_identifier = <project_id>.<dataset_id> Data details are extracted from the dataset_id that follows the format: <dataset>_<format>_<compression>_<partitioning>_<location> eg. tpch100_parquet_uncompressed_unpartitoned_s3 Returns: A dictionary set to underlying data's details (format, etc.)"""
        data_details = {}
        dataset_id = re.split('\\.', self.cluster_identifier)[1]
        parsed_id = re.split('_', dataset_id)
        data_details['format'] = parsed_id[1]
        data_details['compression'] = parsed_id[2]
        data_details['partitioning'] = parsed_id[3]
        data_details['location'] = parsed_id[4]
        return data_details


revert

Prompt:
Implement the Python class `ListenersUpdate` described below.

Class description:
Task to update amphora with all specified listeners' configurations.

Method signatures and docstrings:
- def execute(self, loadbalancer_id): Execute updates per listener for an amphora.
- def revert(self, loadbalancer_id, *args, **kwargs): Handle failed listeners updates.

Implement the Python class `ListenersUpdate` described below.

Class description:
Task to update amphora with all specified listeners' configurations.

Method signatures and docstrings:
- def execute(self, loadbalancer_id): Execute updates per listener for an amphora.
- def revert(self, loadbalancer_id, *args, **kwargs): Handle failed listeners updates.

<|skeleton|>
class ListenersUpdate:
    """Task to update amphora with all specified listeners' configurations."""

    def execute(self, loadbalancer_id):
        """Execute updates per listener for an amphora."""
        <|body_0|>

    def revert(self, loadbalancer_id, *args, **kwargs):
        """Handle failed listeners updates."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        session = db_apis.get_session()
        with session.begin():
            loadbalancer = self.loadbalancer_repo.get(session, id=loadbalancer_id)
        if loadbalancer:
            self.amphora_driver.update(loadbalancer)
        else:
            LOG.error('Load balancer %s for listeners update not found. Skipping update.', loadbalancer_id)
<|end_body_0|>

<|body_start_1|>
        LOG.warning('Reverting listeners updates.')
        session = db_apis.get_session()
        with session.begin():
            loadbalancer = self.loadbalancer_repo.get(session, id=loadbalancer_id)
        for listener in loadbalancer.listeners:
            self.task_utils.mark_listener_prov_status_error(listener.id)
<|end_body_1|>

Solution:
class ListenersUpdate:
    """Task to update amphora with all specified listeners' configurations."""

    def execute(self, loadbalancer_id):
        """Execute updates per listener for an amphora."""
        session = db_apis.get_session()
        with session.begin():
            loadbalancer = self.loadbalancer_repo.get(session, id=loadbalancer_id)
        if loadbalancer:
            self.amphora_driver.update(loadbalancer)
        else:
            LOG.error('Load balancer %s for listeners update not found. Skipping update.', loadbalancer_id)

    def revert(self, loadbalancer_id, *args, **kwargs):
        """Handle failed listeners updates."""
        LOG.warning('Reverting listeners updates.')
        session = db_apis.get_session()
        with session.begin():
            loadbalancer = self.loadbalancer_repo.get(session, id=loadbalancer_id)
        for listener in loadbalancer.listeners:
            self.task_utils.mark_listener_prov_status_error(listener.id)