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

Class description:
Provides services for the execution of algorithms. FacadeExecution.factory is an instance of FactoryExecAlgo, which must be used to instantiate separately executable algorithms Typical use of this facade: 1) Simplest use: my_exec_algo, exec_status = FacadeExecution.execute( ... ) 2) Separating steps : initializing algo, connecting data sources and executing algo # It is useful to have a separate step connecting data sources, and receivers # create disconnected algo my_algo = FacadeExecution.factory.get_algo(...) # connect missing data sources and receivers my_algo.set_data_source( ...) ... my_algo.set_data_receiver( ...) ... # execute exec_status = FacadeExecution.execute_algo( my_algo )

Method signatures and docstrings:
- def __eval_exec_engine_class(cls, str_plugin_path, str_plugin): private class method evaluate the configured engine from module+plugin :param cls: :type cls: :param str_plugin_path: :type str_plugin_path: :param str_plugin: :type str_plugin: :return: subclass of ExecEngine (!!! not an instance !!!)
- def execute_algo_without_custom(implem, input_arg_names, input_data_sources, output_arg_names, output_data_receivers, exec_algo_db_id=None, run_debug=False, dao_managed=True): Firstly build the ExecutableAlgo: initialized without customized parameters in database (Custom DB is ignored) Secondly run the service FacadeExecution.execute_algo on created algo. :param implem: executed implementation :type implem: Implementation :param input_arg_names: complete list of input names :type input_arg_names: list :param input_data_sources: complete list of input values (either explicit values or DataSource subclasses) :type input_data_sources: list :param output_arg_names: complete list of output names :type output_arg_names: list :param output_data_receivers: complete list of output receivers: same length than output_arg_names: each element is either None or instance of Data
- def execute_algo(executable_algo, debug=False, dao_managed=False): Execute the algorithm according to configured plugin - Retrieves the ExecEngine subclass, - Intanciates the engine for the executable_algo - Execute the engine :param executable_algo: executable algorithm :type executable_algo: apps.algo.execute.models.business.algo.ExecutableAlgo :param debug: optional (default False): flag activating debug traces :type debug: boolean :param dao_managed: optional(default False): flag: when True: activates the persistence of ExecutableAlgo + setting of process_id :type dao_managed: boolean

Implement the Python class `FacadeExecution` described below.

Class description:
Provides services for the execution of algorithms. FacadeExecution.factory is an instance of FactoryExecAlgo, which must be used to instantiate separately executable algorithms Typical use of this facade: 1) Simplest use: my_exec_algo, exec_status = FacadeExecution.execute( ... ) 2) Separating steps : initializing algo, connecting data sources and executing algo # It is useful to have a separate step connecting data sources, and receivers # create disconnected algo my_algo = FacadeExecution.factory.get_algo(...) # connect missing data sources and receivers my_algo.set_data_source( ...) ... my_algo.set_data_receiver( ...) ... # execute exec_status = FacadeExecution.execute_algo( my_algo )

Method signatures and docstrings:
- def __eval_exec_engine_class(cls, str_plugin_path, str_plugin): private class method evaluate the configured engine from module+plugin :param cls: :type cls: :param str_plugin_path: :type str_plugin_path: :param str_plugin: :type str_plugin: :return: subclass of ExecEngine (!!! not an instance !!!)
- def execute_algo_without_custom(implem, input_arg_names, input_data_sources, output_arg_names, output_data_receivers, exec_algo_db_id=None, run_debug=False, dao_managed=True): Firstly build the ExecutableAlgo: initialized without customized parameters in database (Custom DB is ignored) Secondly run the service FacadeExecution.execute_algo on created algo. :param implem: executed implementation :type implem: Implementation :param input_arg_names: complete list of input names :type input_arg_names: list :param input_data_sources: complete list of input values (either explicit values or DataSource subclasses) :type input_data_sources: list :param output_arg_names: complete list of output names :type output_arg_names: list :param output_data_receivers: complete list of output receivers: same length than output_arg_names: each element is either None or instance of Data
- def execute_algo(executable_algo, debug=False, dao_managed=False): Execute the algorithm according to configured plugin - Retrieves the ExecEngine subclass, - Intanciates the engine for the executable_algo - Execute the engine :param executable_algo: executable algorithm :type executable_algo: apps.algo.execute.models.business.algo.ExecutableAlgo :param debug: optional (default False): flag activating debug traces :type debug: boolean :param dao_managed: optional(default False): flag: when True: activates the persistence of ExecutableAlgo + setting of process_id :type dao_managed: boolean

<|skeleton|>
class FacadeExecution:
    """Provides services for the execution of algorithms. FacadeExecution.factory is an instance of FactoryExecAlgo, which must be used to instantiate separately executable algorithms Typical use of this facade: 1) Simplest use: my_exec_algo, exec_status = FacadeExecution.execute( ... ) 2) Separating steps : initializing algo, connecting data sources and executing algo # It is useful to have a separate step connecting data sources, and receivers # create disconnected algo my_algo = FacadeExecution.factory.get_algo(...) # connect missing data sources and receivers my_algo.set_data_source( ...) ... my_algo.set_data_receiver( ...) ... # execute exec_status = FacadeExecution.execute_algo( my_algo )"""

    def __eval_exec_engine_class(cls, str_plugin_path, str_plugin):
        """private class method evaluate the configured engine from module+plugin :param cls: :type cls: :param str_plugin_path: :type str_plugin_path: :param str_plugin: :type str_plugin: :return: subclass of ExecEngine (!!! not an instance !!!)"""
        <|body_0|>

    def execute_algo_without_custom(implem, input_arg_names, input_data_sources, output_arg_names, output_data_receivers, exec_algo_db_id=None, run_debug=False, dao_managed=True):
        """Firstly build the ExecutableAlgo: initialized without customized parameters in database (Custom DB is ignored) Secondly run the service FacadeExecution.execute_algo on created algo. :param implem: executed implementation :type implem: Implementation :param input_arg_names: complete list of input names :type input_arg_names: list :param input_data_sources: complete list of input values (either explicit values or DataSource subclasses) :type input_data_sources: list :param output_arg_names: complete list of output names :type output_arg_names: list :param output_data_receivers: complete list of output receivers: same length than output_arg_names: each element is either None or instance of Data"""
        <|body_1|>

    def execute_algo(executable_algo, debug=False, dao_managed=False):
        """Execute the algorithm according to configured plugin - Retrieves the ExecEngine subclass, - Intanciates the engine for the executable_algo - Execute the engine :param executable_algo: executable algorithm :type executable_algo: apps.algo.execute.models.business.algo.ExecutableAlgo :param debug: optional (default False): flag activating debug traces :type debug: boolean :param dao_managed: optional(default False): flag: when True: activates the persistence of ExecutableAlgo + setting of process_id :type dao_managed: boolean"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        my_module_path = str_plugin_path
        my_plugin = str_plugin
        try:
            my_module = importlib.import_module(my_module_path)
            evaluated_plugin_str = 'my_module.%s' % my_plugin
            my_class = eval(evaluated_plugin_str)
        except Exception:
            raise Exception('Failed to evaluate ExecEngine plugin %s.%s' % (str_plugin_path, str_plugin))
        return my_class
<|end_body_0|>

<|body_start_1|>
        if isinstance(implem, str):
            my_implementation = ImplementationDao.find_business_elem_with_key(implem)
        else:
            my_implementation = implem
        my_exec_algo = FacadeExecution.factory.build_exec_algo_without_custom(implementation=my_implementation, input_names=input_arg_names, input_values_or_sources=input_data_sources, output_names=output_arg_names, output_receivers=output_data_receivers)
        if exec_algo_db_id is not None:
            my_exec_algo.set_process_id(exec_algo_db_id)
        return FacadeExecution.execute_algo(executable_algo=my_exec_algo, debug=run_debug, dao_managed=dao_managed)
<|end_body_1|>

<|body_start_2|>
        parsed_plugin = executable_algo.get_execution_plugin().split('::')
        module_path = parsed_plugin[0]
        plugin_class_name = parsed_plugin[1]
        my_plugin_class = FacadeExecution.__eval_exec_engine_class(module_path, plugin_class_name)
        my_engine = my_plugin_class(executable_algo, debug, dao_managed)
        my_status = my_engine.execute()
        return (my_engine.get_executable_algo(), my_status)
<|end_body_2|>

Solution:
class FacadeExecution:
    """Provides services for the execution of algorithms. FacadeExecution.factory is an instance of FactoryExecAlgo, which must be used to instantiate separately executable algorithms Typical use of this facade: 1) Simplest use: my_exec_algo, exec_status = FacadeExecution.execute( ... ) 2) Separating steps : initializing algo, connecting data sources and executing algo # It is useful to have a separate step connecting data sources, and receivers # create disconnected algo my_algo = FacadeExecution.factory.get_algo(...) # connect missing data sources and receivers my_algo.set_data_source( ...) ... my_algo.set_data_receiver( ...) ... # execute exec_status = FacadeExecution.execute_algo( my_algo )"""

    def __eval_exec_engine_class(cls, str_plugin_path, str_plugin):
        """private class method evaluate the configured engine from module+plugin :param cls: :type cls: :param str_plugin_path: :type str_plugin_path: :param str_plugin: :type str_plugin: :return: subclass of ExecEngine (!!! not an instance !!!)"""
        my_module_path = str_plugin_path
        my_plugin = str_plugin
        try:
            my_module = importlib.import_module(my_module_path)
            evaluated_plugin_str = 'my_module.%s' % my_plugin
            my_class = eval(evaluated_plugin_str)
        except Exception:
            raise Exception('Failed to evaluate ExecEngine plugin %s.%s' % (str_plugin_path, str_plugin))
        return my_class

    def execute_algo_without_custom(implem, input_arg_names, input_data_sources, output_arg_names, output_data_receivers, exec_algo_db_id=None, run_debug=False, dao_managed=True):
        """Firstly build the ExecutableAlgo: initialized without customized parameters in database (Custom DB is ignored) Secondly run the service FacadeExecution.execute_algo on created algo. :param implem: executed implementation :type implem: Implementation :param input_arg_names: complete list of input names :type input_arg_names: list :param input_data_sources: complete list of input values (either explicit values or DataSource subclasses) :type input_data_sources: list :param output_arg_names: complete list of output names :type output_arg_names: list :param output_data_receivers: complete list of output receivers: same length than output_arg_names: each element is either None or instance of Data"""
        if isinstance(implem, str):
            my_implementation = ImplementationDao.find_business_elem_with_key(implem)
        else:
            my_implementation = implem
        my_exec_algo = FacadeExecution.factory.build_exec_algo_without_custom(implementation=my_implementation, input_names=input_arg_names, input_values_or_sources=input_data_sources, output_names=output_arg_names, output_receivers=output_data_receivers)
        if exec_algo_db_id is not None:
            my_exec_algo.set_process_id(exec_algo_db_id)
        return FacadeExecution.execute_algo(executable_algo=my_exec_algo, debug=run_debug, dao_managed=dao_managed)

    def execute_algo(executable_algo, debug=False, dao_managed=False):
        """Execute the algorithm according to configured plugin - Retrieves the ExecEngine subclass, - Intanciates the engine for the executable_algo - Execute the engine :param executable_algo: executable algorithm :type executable_algo: apps.algo.execute.models.business.algo.ExecutableAlgo :param debug: optional (default False): flag activating debug traces :type debug: boolean :param dao_managed: optional(default False): flag: when True: activates the persistence of ExecutableAlgo + setting of process_id :type dao_managed: boolean"""
        parsed_plugin = executable_algo.get_execution_plugin().split('::')
        module_path = parsed_plugin[0]
        plugin_class_name = parsed_plugin[1]
        my_plugin_class = FacadeExecution.__eval_exec_engine_class(module_path, plugin_class_name)
        my_engine = my_plugin_class(executable_algo, debug, dao_managed)
        my_status = my_engine.execute()
        return (my_engine.get_executable_algo(), my_status)


post

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

Class description:
Resource for investigative question conclusion.

Method signatures and docstrings:
- def get(self, sketch_id, question_id): Handles GET request to the resource. Returns: A list of JSON representations of the conclusions.
- def post(self, sketch_id, question_id): Handles POST request to the resource. Adds or edits a conclusion. Returns: A JSON representation of the conclusion.

Implement the Python class `QuestionConclusionListResource` described below.

Class description:
Resource for investigative question conclusion.

Method signatures and docstrings:
- def get(self, sketch_id, question_id): Handles GET request to the resource. Returns: A list of JSON representations of the conclusions.
- def post(self, sketch_id, question_id): Handles POST request to the resource. Adds or edits a conclusion. Returns: A JSON representation of the conclusion.

<|skeleton|>
class QuestionConclusionListResource:
    """Resource for investigative question conclusion."""

    def get(self, sketch_id, question_id):
        """Handles GET request to the resource. Returns: A list of JSON representations of the conclusions."""
        <|body_0|>

    def post(self, sketch_id, question_id):
        """Handles POST request to the resource. Adds or edits a conclusion. Returns: A JSON representation of the conclusion."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        sketch = Sketch.query.get_with_acl(sketch_id)
        if not sketch:
            abort(HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID')
        question = InvestigativeQuestion.query.get(question_id)
        if not question:
            abort(HTTP_STATUS_CODE_NOT_FOUND, 'No question found with this ID')
        conclusions = InvestigativeQuestionConclusion.filter_by(investigativequestion=question).all()
        return self.to_json(conclusions)
<|end_body_0|>

<|body_start_1|>
        sketch = Sketch.query.get_with_acl(sketch_id)
        if not sketch:
            abort(HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID')
        question = InvestigativeQuestion.query.get(question_id)
        if not question:
            abort(HTTP_STATUS_CODE_NOT_FOUND, 'No question found with this ID')
        conclusion = InvestigativeQuestionConclusion.get_or_create(user=current_user, investigativequestion=question)
        form = request.json
        if not form:
            form = request.data
        conclusion_text = form.get('conclusionText')
        if conclusion_text:
            conclusion.conclusion = conclusion_text
            db_session.add(conclusion)
            db_session.commit()
        return self.to_json(conclusion)
<|end_body_1|>

Solution:
class QuestionConclusionListResource:
    """Resource for investigative question conclusion."""

    def get(self, sketch_id, question_id):
        """Handles GET request to the resource. Returns: A list of JSON representations of the conclusions."""
        sketch = Sketch.query.get_with_acl(sketch_id)
        if not sketch:
            abort(HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID')
        question = InvestigativeQuestion.query.get(question_id)
        if not question:
            abort(HTTP_STATUS_CODE_NOT_FOUND, 'No question found with this ID')
        conclusions = InvestigativeQuestionConclusion.filter_by(investigativequestion=question).all()
        return self.to_json(conclusions)

    def post(self, sketch_id, question_id):
        """Handles POST request to the resource. Adds or edits a conclusion. Returns: A JSON representation of the conclusion."""
        sketch = Sketch.query.get_with_acl(sketch_id)
        if not sketch:
            abort(HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID')
        question = InvestigativeQuestion.query.get(question_id)
        if not question:
            abort(HTTP_STATUS_CODE_NOT_FOUND, 'No question found with this ID')
        conclusion = InvestigativeQuestionConclusion.get_or_create(user=current_user, investigativequestion=question)
        form = request.json
        if not form:
            form = request.data
        conclusion_text = form.get('conclusionText')
        if conclusion_text:
            conclusion.conclusion = conclusion_text
            db_session.add(conclusion)
            db_session.commit()
        return self.to_json(conclusion)


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

Class description:
Implement the ClassifierNetworkTests class.

Method signatures and docstrings:
- def test_layer_creation(self): Tests the creation of a default layer preconditions: No layer has been created postconditions: layer with default placeholder has been created
- def test_loss_creation(self): Tests the creation of a loss function preconditions: no loss function has been created postconditions: A loss function has been created and exists
- def test_optimizer_creation(self): Tests the creation of an optimizer for the tests preconditions: an optmizer hasn't been created postconditions: an optimizer has been created
- def test_classifier_creation(self): Tests the creation of a full FC graph preconditions: a FC graph hasn't been created postconditions: a FC graph has been created covering all functions

Implement the Python class `ClassifierNetworkTests` described below.

Class description:
Implement the ClassifierNetworkTests class.

Method signatures and docstrings:
- def test_layer_creation(self): Tests the creation of a default layer preconditions: No layer has been created postconditions: layer with default placeholder has been created
- def test_loss_creation(self): Tests the creation of a loss function preconditions: no loss function has been created postconditions: A loss function has been created and exists
- def test_optimizer_creation(self): Tests the creation of an optimizer for the tests preconditions: an optmizer hasn't been created postconditions: an optimizer has been created
- def test_classifier_creation(self): Tests the creation of a full FC graph preconditions: a FC graph hasn't been created postconditions: a FC graph has been created covering all functions

<|skeleton|>
class ClassifierNetworkTests:

    def test_layer_creation(self):
        """Tests the creation of a default layer preconditions: No layer has been created postconditions: layer with default placeholder has been created"""
        <|body_0|>

    def test_loss_creation(self):
        """Tests the creation of a loss function preconditions: no loss function has been created postconditions: A loss function has been created and exists"""
        <|body_1|>

    def test_optimizer_creation(self):
        """Tests the creation of an optimizer for the tests preconditions: an optmizer hasn't been created postconditions: an optimizer has been created"""
        <|body_2|>

    def test_classifier_creation(self):
        """Tests the creation of a full FC graph preconditions: a FC graph hasn't been created postconditions: a FC graph has been created covering all functions"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        bsscs = BSSCS_CLASSIFIER(l2_reg=tf.contrib.layers.l2_regularizer(scale=0.001), learning_rate=0.001, steps=250, batch=250)
        self.assertTrue(bsscs != None)
        single_layer = bsscs.create_layer(512, activation=tf.nn.relu)
        self.assertTrue(single_layer != None)
<|end_body_0|>

<|body_start_1|>
        bsscs = BSSCS_CLASSIFIER(l2_reg=tf.contrib.layers.l2_regularizer(scale=0.001), learning_rate=0.001, steps=250, batch=250)
        self.assertTrue(bsscs != None)
        input_ph = tf.placeholder(tf.float32, shape=[None, 512, 512])
        labels_ph = tf.placeholder(tf.float32, shape=[None, 2])
        loss_function = bsscs.create_loss_function(input=input_ph, labels=labels_ph)
        self.assertTrue(loss_function != None)
        loss_function_var = bsscs.get_loss()
        self.assertTrue(loss_function_var == loss_function)
<|end_body_1|>

<|body_start_2|>
        bsscs = BSSCS_CLASSIFIER(l2_reg=tf.contrib.layers.l2_regularizer(scale=0.001), learning_rate=0.001, steps=250, batch=250)
        self.assertTrue(bsscs != None)
        optimizer = bsscs.create_optimizer()
        self.assertTrue(optimizer != None)
        optimizer_var = bsscs.get_optimizer()
        self.assertTrue(optimizer == optimizer_var)
<|end_body_2|>

<|body_start_3|>
        bsscs = BSSCS_CLASSIFIER(l2_reg=tf.contrib.layers.l2_regularizer(scale=0.001), learning_rate=0.001, steps=250, batch=250)
        self.assertTrue(bsscs != None)
        classifier = bsscs.create_classifier([125, 12])
        self.assertTrue(classifier != None)
<|end_body_3|>

Solution:
class ClassifierNetworkTests:
    def test_layer_creation(self):
        """Tests the creation of a default layer preconditions: No layer has been created postconditions: layer with default placeholder has been created"""
        bsscs = BSSCS_CLASSIFIER(l2_reg=tf.contrib.layers.l2_regularizer(scale=0.001), learning_rate=0.001, steps=250, batch=250)
        self.assertTrue(bsscs != None)
        single_layer = bsscs.create_layer(512, activation=tf.nn.relu)
        self.assertTrue(single_layer != None)

    def test_loss_creation(self):
        """Tests the creation of a loss function preconditions: no loss function has been created postconditions: A loss function has been created and exists"""
        bsscs = BSSCS_CLASSIFIER(l2_reg=tf.contrib.layers.l2_regularizer(scale=0.001), learning_rate=0.001, steps=250, batch=250)
        self.assertTrue(bsscs != None)
        input_ph = tf.placeholder(tf.float32, shape=[None, 512, 512])
        labels_ph = tf.placeholder(tf.float32, shape=[None, 2])
        loss_function = bsscs.create_loss_function(input=input_ph, labels=labels_ph)
        self.assertTrue(loss_function != None)
        loss_function_var = bsscs.get_loss()
        self.assertTrue(loss_function_var == loss_function)

    def test_optimizer_creation(self):
        """Tests the creation of an optimizer for the tests preconditions: an optmizer hasn't been created postconditions: an optimizer has been created"""
        bsscs = BSSCS_CLASSIFIER(l2_reg=tf.contrib.layers.l2_regularizer(scale=0.001), learning_rate=0.001, steps=250, batch=250)
        self.assertTrue(bsscs != None)
        optimizer = bsscs.create_optimizer()
        self.assertTrue(optimizer != None)
        optimizer_var = bsscs.get_optimizer()
        self.assertTrue(optimizer == optimizer_var)

    def test_classifier_creation(self):
        """Tests the creation of a full FC graph preconditions: a FC graph hasn't been created postconditions: a FC graph has been created covering all functions"""
        bsscs = BSSCS_CLASSIFIER(l2_reg=tf.contrib.layers.l2_regularizer(scale=0.001), learning_rate=0.001, steps=250, batch=250)
        self.assertTrue(bsscs != None)
        classifier = bsscs.create_classifier([125, 12])
        self.assertTrue(classifier != None)


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

Class description:
Simple class for data parsed from data/all_non_ref_hg19/yuaker folder, or other samples

Method signatures and docstrings:
- def __init__(self, data_dir, sample_name): Parses exome and ann files in data_dir for this sample to make {} of paired tumor/normal call data
- def get_inherited_somatic_mutations(self, quality_cutoff, coverage_cutoff): Return chrpos and ref, normal, cancer alleles for in inherited and somatic {}
- def write_mutations(self, quality_cutoff, coverage_cutoff, exome_type, somatic_or_inherited, afile): Write mutations for file
- def mk_MU2A_input(exome_type, quality_cutoff, coverage_cutoff, inherited_output_file, somatic_output_file): Write input for MU2A for inherited and somatic mutations. This is broken b/c of the function above

Implement the Python class `calls` described below.

Class description:
Simple class for data parsed from data/all_non_ref_hg19/yuaker folder, or other samples

Method signatures and docstrings:
- def __init__(self, data_dir, sample_name): Parses exome and ann files in data_dir for this sample to make {} of paired tumor/normal call data
- def get_inherited_somatic_mutations(self, quality_cutoff, coverage_cutoff): Return chrpos and ref, normal, cancer alleles for in inherited and somatic {}
- def write_mutations(self, quality_cutoff, coverage_cutoff, exome_type, somatic_or_inherited, afile): Write mutations for file
- def mk_MU2A_input(exome_type, quality_cutoff, coverage_cutoff, inherited_output_file, somatic_output_file): Write input for MU2A for inherited and somatic mutations. This is broken b/c of the function above

<|skeleton|>
class calls:
    """Simple class for data parsed from data/all_non_ref_hg19/yuaker folder, or other samples"""

    def __init__(self, data_dir, sample_name):
        """Parses exome and ann files in data_dir for this sample to make {} of paired tumor/normal call data"""
        <|body_0|>

    def get_inherited_somatic_mutations(self, quality_cutoff, coverage_cutoff):
        """Return chrpos and ref, normal, cancer alleles for in inherited and somatic {}"""
        <|body_1|>

    def write_mutations(self, quality_cutoff, coverage_cutoff, exome_type, somatic_or_inherited, afile):
        """Write mutations for file"""
        <|body_2|>

    def mk_MU2A_input(exome_type, quality_cutoff, coverage_cutoff, inherited_output_file, somatic_output_file):
        """Write input for MU2A for inherited and somatic mutations. This is broken b/c of the function above"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        self.data = {}
        cancer_ann_file = os.path.join(data_dir, sample_name + 'T.ann')
        normal_ann_file = os.path.join(data_dir, sample_name + 'N.ann')
        cancer_consensus_qualities = get_consensus_qualities(cancer_ann_file)
        normal_consensus_qualities = get_consensus_qualities(normal_ann_file)
        consensus_qualities = {}
        consensus_qualities[sample_name + 'T'] = cancer_consensus_qualities
        consensus_qualities[sample_name + 'N'] = normal_consensus_qualities
        for exome_type in global_settings.exome_types:
            call_file = os.path.join(data_dir, exome_type)
            self.data[exome_type] = parse_call_file(call_file, consensus_qualities)
<|end_body_0|>

<|body_start_1|>
        inherited = defaultdict(dict)
        somatic = defaultdict(dict)
        for exome_type in self.data:
            for chrpos in self.data[exome_type]:
                if self.data[exome_type][chrpos]['N']['consensus_quality'] > quality_cutoff and self.data[exome_type][chrpos]['T']['consensus_quality'] > quality_cutoff and (self.data[exome_type][chrpos]['N']['coverage'] >= coverage_cutoff) and (self.data[exome_type][chrpos]['T']['coverage'] >= coverage_cutoff) and (max((self.data[exome_type][chrpos]['N']['snp_quality'], self.data[exome_type][chrpos]['T']['snp_quality'])) > quality_cutoff):
                    mutation_type = self.data[exome_type][chrpos]['mutation_type']
                    m1, m2 = mutation_type.split(':')
                    if mutation_type in ('BB:BB', 'AB:AB'):
                        inherited[exome_type][chrpos] = (mutation_type, self.data[exome_type][chrpos]['N']['call'], self.data[exome_type][chrpos]['T']['call'], self.data[exome_type][chrpos]['ref_allele'])
                    elif mutation_type not in ('AB:AA', 'AB:BB') and m1 != m2:
                        somatic[exome_type][chrpos] = (mutation_type, self.data[exome_type][chrpos]['N']['call'], self.data[exome_type][chrpos]['T']['call'], self.data[exome_type][chrpos]['ref_allele'])
        return (inherited, somatic)
<|end_body_1|>

<|body_start_2|>
        inherited, somatic = self.get_somatic_inherited_mutations(quality_cutoff, coverage_cutoff)
        if somatic_or_inherited == 'somatic':
            use_muts = somatic
        else:
            use_muts = inherited
        with open(afile, 'w') as f:
            for chrpos in inherited[exome_type]:
                f.write(chrpos + '\n')
<|end_body_2|>

<|body_start_3|>
        inherited, somatic = self.get_somatic_inherited_mutations(quality_cutoff, coverage_cutoff)
        write_MU2A_input(inherited[exome_type], inherited_output_file, 'inherited')
        write_MU2A_input(somatic[exome_type], somatic_output_file, 'somatic')
<|end_body_3|>

Solution:
class calls:
    """Simple class for data parsed from data/all_non_ref_hg19/yuaker folder, or other samples"""

    def __init__(self, data_dir, sample_name):
        """Parses exome and ann files in data_dir for this sample to make {} of paired tumor/normal call data"""
        self.data = {}
        cancer_ann_file = os.path.join(data_dir, sample_name + 'T.ann')
        normal_ann_file = os.path.join(data_dir, sample_name + 'N.ann')
        cancer_consensus_qualities = get_consensus_qualities(cancer_ann_file)
        normal_consensus_qualities = get_consensus_qualities(normal_ann_file)
        consensus_qualities = {}
        consensus_qualities[sample_name + 'T'] = cancer_consensus_qualities
        consensus_qualities[sample_name + 'N'] = normal_consensus_qualities
        for exome_type in global_settings.exome_types:
            call_file = os.path.join(data_dir, exome_type)
            self.data[exome_type] = parse_call_file(call_file, consensus_qualities)

    def get_inherited_somatic_mutations(self, quality_cutoff, coverage_cutoff):
        """Return chrpos and ref, normal, cancer alleles for in inherited and somatic {}"""
        inherited = defaultdict(dict)
        somatic = defaultdict(dict)
        for exome_type in self.data:
            for chrpos in self.data[exome_type]:
                if self.data[exome_type][chrpos]['N']['consensus_quality'] > quality_cutoff and self.data[exome_type][chrpos]['T']['consensus_quality'] > quality_cutoff and (self.data[exome_type][chrpos]['N']['coverage'] >= coverage_cutoff) and (self.data[exome_type][chrpos]['T']['coverage'] >= coverage_cutoff) and (max((self.data[exome_type][chrpos]['N']['snp_quality'], self.data[exome_type][chrpos]['T']['snp_quality'])) > quality_cutoff):
                    mutation_type = self.data[exome_type][chrpos]['mutation_type']
                    m1, m2 = mutation_type.split(':')
                    if mutation_type in ('BB:BB', 'AB:AB'):
                        inherited[exome_type][chrpos] = (mutation_type, self.data[exome_type][chrpos]['N']['call'], self.data[exome_type][chrpos]['T']['call'], self.data[exome_type][chrpos]['ref_allele'])
                    elif mutation_type not in ('AB:AA', 'AB:BB') and m1 != m2:
                        somatic[exome_type][chrpos] = (mutation_type, self.data[exome_type][chrpos]['N']['call'], self.data[exome_type][chrpos]['T']['call'], self.data[exome_type][chrpos]['ref_allele'])
        return (inherited, somatic)

    def write_mutations(self, quality_cutoff, coverage_cutoff, exome_type, somatic_or_inherited, afile):
        """Write mutations for file"""
        inherited, somatic = self.get_somatic_inherited_mutations(quality_cutoff, coverage_cutoff)
        if somatic_or_inherited == 'somatic':
            use_muts = somatic
        else:
            use_muts = inherited
        with open(afile, 'w') as f:
            for chrpos in inherited[exome_type]:
                f.write(chrpos + '\n')

    def mk_MU2A_input(exome_type, quality_cutoff, coverage_cutoff, inherited_output_file, somatic_output_file):
        """Write input for MU2A for inherited and somatic mutations. This is broken b/c of the function above"""
        inherited, somatic = self.get_somatic_inherited_mutations(quality_cutoff, coverage_cutoff)
        write_MU2A_input(inherited[exome_type], inherited_output_file, 'inherited')
        write_MU2A_input(somatic[exome_type], somatic_output_file, 'somatic')


postorder

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def postorder(self, root: 'Node') -> List[int]: 递归
- def postorder1(self, root: 'Node') -> List[int]: 迭代

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def postorder(self, root: 'Node') -> List[int]: 递归
- def postorder1(self, root: 'Node') -> List[int]: 迭代

<|skeleton|>
class Solution:

    def postorder(self, root: 'Node') -> List[int]:
        """递归"""
        <|body_0|>

    def postorder1(self, root: 'Node') -> List[int]:
        """迭代"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if not root:
            return []
        res = []

        def digui(root):
            if root:
                for i in root.children:
                    digui(i)
                res.append(root.val)
        digui(root)
        return res
<|end_body_0|>

<|body_start_1|>
        if not root:
            return []
        res = []
        stack = [root]
        while stack:
            node = stack.pop()
            for i in node.children:
                stack.append(i)
            res.append(node.val)
        return res[::-1]
<|end_body_1|>

Solution:
class Solution:
    def postorder(self, root: 'Node') -> List[int]:
        """递归"""
        if not root:
            return []
        res = []

        def digui(root):
            if root:
                for i in root.children:
                    digui(i)
                res.append(root.val)
        digui(root)
        return res

    def postorder1(self, root: 'Node') -> List[int]:
        """迭代"""
        if not root:
            return []
        res = []
        stack = [root]
        while stack:
            node = stack.pop()
            for i in node.children:
                stack.append(i)
            res.append(node.val)
        return res[::-1]


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

Class description:
Applies AutoContrast to 'img'. The AutoContrast operation maximizes the the image contrast, by making the darkest pixel black and lightest pixel white. :param level: Strength of the operation specified as an Integer from [0, 'PARAMETER_MAX']. :type level: int

Method signatures and docstrings:
- def __init__(self, num=2, magnitude=9, prob=0.5, magnitude_std=0.5): Construct the AutoContrast class.
- def __call__(self, img): Call function of AutoContrast. :param img: input image :type img: numpy or tensor :return: the image after transform :rtype: numpy or tensor

Implement the Python class `AutoAugment` described below.

Class description:
Applies AutoContrast to 'img'. The AutoContrast operation maximizes the the image contrast, by making the darkest pixel black and lightest pixel white. :param level: Strength of the operation specified as an Integer from [0, 'PARAMETER_MAX']. :type level: int

Method signatures and docstrings:
- def __init__(self, num=2, magnitude=9, prob=0.5, magnitude_std=0.5): Construct the AutoContrast class.
- def __call__(self, img): Call function of AutoContrast. :param img: input image :type img: numpy or tensor :return: the image after transform :rtype: numpy or tensor

<|skeleton|>
class AutoAugment:
    """Applies AutoContrast to 'img'. The AutoContrast operation maximizes the the image contrast, by making the darkest pixel black and lightest pixel white. :param level: Strength of the operation specified as an Integer from [0, 'PARAMETER_MAX']. :type level: int"""

    def __init__(self, num=2, magnitude=9, prob=0.5, magnitude_std=0.5):
        """Construct the AutoContrast class."""
        <|body_0|>

    def __call__(self, img):
        """Call function of AutoContrast. :param img: input image :type img: numpy or tensor :return: the image after transform :rtype: numpy or tensor"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.num = num
        self.magnitude = magnitude
        self.prob = prob
        self.magnitude_std = magnitude_std
<|end_body_0|>

<|body_start_1|>
        transforms = []
        if self.prob < 1.0 and random.random() > self.prob:
            return img
        for name in self._RAND_TRANSFORMS.keys():
            if ClassFactory.is_exists(ClassType.TRANSFORM, self._RAND_TRANSFORMS[name]):
                transforms.append(ClassFactory.get_cls(ClassType.TRANSFORM, self._RAND_TRANSFORMS[name]))
        ops = np.random.choice(transforms, self.num)
        for op in ops:
            if self.magnitude_std and self.magnitude_std > 0:
                magnitude = random.gauss(self.magnitude, self.magnitude_std)
            magnitude = min(10, max(0, magnitude))
            img = op(magnitude)(img)
        return img
<|end_body_1|>

Solution:
class AutoAugment:
    """Applies AutoContrast to 'img'. The AutoContrast operation maximizes the the image contrast, by making the darkest pixel black and lightest pixel white. :param level: Strength of the operation specified as an Integer from [0, 'PARAMETER_MAX']. :type level: int"""

    def __init__(self, num=2, magnitude=9, prob=0.5, magnitude_std=0.5):
        """Construct the AutoContrast class."""
        self.num = num
        self.magnitude = magnitude
        self.prob = prob
        self.magnitude_std = magnitude_std

    def __call__(self, img):
        """Call function of AutoContrast. :param img: input image :type img: numpy or tensor :return: the image after transform :rtype: numpy or tensor"""
        transforms = []
        if self.prob < 1.0 and random.random() > self.prob:
            return img
        for name in self._RAND_TRANSFORMS.keys():
            if ClassFactory.is_exists(ClassType.TRANSFORM, self._RAND_TRANSFORMS[name]):
                transforms.append(ClassFactory.get_cls(ClassType.TRANSFORM, self._RAND_TRANSFORMS[name]))
        ops = np.random.choice(transforms, self.num)
        for op in ops:
            if self.magnitude_std and self.magnitude_std > 0:
                magnitude = random.gauss(self.magnitude, self.magnitude_std)
            magnitude = min(10, max(0, magnitude))
            img = op(magnitude)(img)
        return img


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

Class description:
Data from clump_XXXXX.txtYYYYY

Method signatures and docstrings:
- def __init__(self, par): par: params object
- def read_clumpdata(self, par): Reads in the clump data. Only for the z = 0 directory. par: params object
- def cleanup_clumpdata(self, par, mtd): The particle unbinding can remove entire clumps from the catalogue. If the option isn't set in the namelist, the clumpfinder output will still be made not based on the clumpfinder. If that is the case, the clumpfinder catalogue will contain clumps which the mergertree data doesn't have, leading to problems. So remove those here. mtd: mergertree data object
- def find_children(self, clumpid): Find the children for given clump ID. clumpid: clump ID for which to work for returns: children: list of children IDs of clumpid
- def write_children(self, par, clumpid, children): Write the children to file. par: parameters object clumpid: ID of clump for which we're working children: list of children

Implement the Python class `clumpdata` described below.

Class description:
Data from clump_XXXXX.txtYYYYY

Method signatures and docstrings:
- def __init__(self, par): par: params object
- def read_clumpdata(self, par): Reads in the clump data. Only for the z = 0 directory. par: params object
- def cleanup_clumpdata(self, par, mtd): The particle unbinding can remove entire clumps from the catalogue. If the option isn't set in the namelist, the clumpfinder output will still be made not based on the clumpfinder. If that is the case, the clumpfinder catalogue will contain clumps which the mergertree data doesn't have, leading to problems. So remove those here. mtd: mergertree data object
- def find_children(self, clumpid): Find the children for given clump ID. clumpid: clump ID for which to work for returns: children: list of children IDs of clumpid
- def write_children(self, par, clumpid, children): Write the children to file. par: parameters object clumpid: ID of clump for which we're working children: list of children

<|skeleton|>
class clumpdata:
    """Data from clump_XXXXX.txtYYYYY"""

    def __init__(self, par):
        """par: params object"""
        <|body_0|>

    def read_clumpdata(self, par):
        """Reads in the clump data. Only for the z = 0 directory. par: params object"""
        <|body_1|>

    def cleanup_clumpdata(self, par, mtd):
        """The particle unbinding can remove entire clumps from the catalogue. If the option isn't set in the namelist, the clumpfinder output will still be made not based on the clumpfinder. If that is the case, the clumpfinder catalogue will contain clumps which the mergertree data doesn't have, leading to problems. So remove those here. mtd: mergertree data object"""
        <|body_2|>

    def find_children(self, clumpid):
        """Find the children for given clump ID. clumpid: clump ID for which to work for returns: children: list of children IDs of clumpid"""
        <|body_3|>

    def write_children(self, par, clumpid, children):
        """Write the children to file. par: parameters object clumpid: ID of clump for which we're working children: list of children"""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        self.clumpids = np.zeros(1)
        self.parent = np.zeros(1)
        self.level = np.zeros(1)
        return
<|end_body_0|>

<|body_start_1|>
        if par.verbose:
            print('Reading clump data.')
        out = p.z0
        raw_data = [None for i in range(par.ncpu)]
        dirnrstr = str(par.outputnrs[out]).zfill(5)
        dirname = 'output_' + dirnrstr
        i = 0
        for cpu in range(par.ncpu):
            fname = os.path.join(dirname, 'clump_' + dirnrstr + '.txt' + str(cpu + 1).zfill(5))
            new_data = np.loadtxt(fname, dtype='int', skiprows=1, usecols=[0, 1, 2])
            if new_data.ndim == 2:
                raw_data[i] = new_data
                i += 1
            elif new_data.shape[0] == 3:
                raw_data[i] = np.atleast_2d(new_data)
                i += 1
        fulldata = np.concatenate(raw_data[:i], axis=0)
        self.clumpids = fulldata[:, 0]
        self.level = fulldata[:, 1]
        self.parent = fulldata[:, 2]
        return
<|end_body_1|>

<|body_start_2|>
        for i, c in enumerate(self.clumpids):
            if c not in mtd.descendants[par.z0]:
                self.clumpids[i] = 0
                self.level[i] = 0
                self.parent[i] = -1
        return
<|end_body_2|>

<|body_start_3|>
        children = []
        last_added = [clumpid]
        loopcounter = 0
        while True:
            loopcounter += 1
            this_level_parents = copy.copy(last_added)
            children += this_level_parents
            last_added = []
            for i, cid in enumerate(self.clumpids):
                if self.parent[i] in this_level_parents and cid != clumpid:
                    last_added.append(cid)
            if len(last_added) == 0:
                break
            if loopcounter == 100:
                print("Finished 100 iterations, we shouldn't be this deep")
                break
        return children[1:]
<|end_body_3|>

<|body_start_4|>
        hfile = ''.join([par.halofilename, '-', str(clumpid), '.txt'])
        f = open(hfile, 'w')
        f.write('# {0:>18} {1:>18} {2:>18}\n'.format('halo', 'nr_of_children', 'children'))
        nc = len(children)
        dumpstring = '  {0:18d} {1:18d}'.format(clumpid, nc)
        dumpstring = ''.join([dumpstring] + [' {0:18d}'.format(c) for c in children] + ['\n'])
        f.write(dumpstring)
        f.close()
        return
<|end_body_4|>

Solution:
class clumpdata:
    """Data from clump_XXXXX.txtYYYYY"""

    def __init__(self, par):
        """par: params object"""
        self.clumpids = np.zeros(1)
        self.parent = np.zeros(1)
        self.level = np.zeros(1)
        return

    def read_clumpdata(self, par):
        """Reads in the clump data. Only for the z = 0 directory. par: params object"""
        if par.verbose:
            print('Reading clump data.')
        out = p.z0
        raw_data = [None for i in range(par.ncpu)]
        dirnrstr = str(par.outputnrs[out]).zfill(5)
        dirname = 'output_' + dirnrstr
        i = 0
        for cpu in range(par.ncpu):
            fname = os.path.join(dirname, 'clump_' + dirnrstr + '.txt' + str(cpu + 1).zfill(5))
            new_data = np.loadtxt(fname, dtype='int', skiprows=1, usecols=[0, 1, 2])
            if new_data.ndim == 2:
                raw_data[i] = new_data
                i += 1
            elif new_data.shape[0] == 3:
                raw_data[i] = np.atleast_2d(new_data)
                i += 1
        fulldata = np.concatenate(raw_data[:i], axis=0)
        self.clumpids = fulldata[:, 0]
        self.level = fulldata[:, 1]
        self.parent = fulldata[:, 2]
        return

    def cleanup_clumpdata(self, par, mtd):
        """The particle unbinding can remove entire clumps from the catalogue. If the option isn't set in the namelist, the clumpfinder output will still be made not based on the clumpfinder. If that is the case, the clumpfinder catalogue will contain clumps which the mergertree data doesn't have, leading to problems. So remove those here. mtd: mergertree data object"""
        for i, c in enumerate(self.clumpids):
            if c not in mtd.descendants[par.z0]:
                self.clumpids[i] = 0
                self.level[i] = 0
                self.parent[i] = -1
        return

    def find_children(self, clumpid):
        """Find the children for given clump ID. clumpid: clump ID for which to work for returns: children: list of children IDs of clumpid"""
        children = []
        last_added = [clumpid]
        loopcounter = 0
        while True:
            loopcounter += 1
            this_level_parents = copy.copy(last_added)
            children += this_level_parents
            last_added = []
            for i, cid in enumerate(self.clumpids):
                if self.parent[i] in this_level_parents and cid != clumpid:
                    last_added.append(cid)
            if len(last_added) == 0:
                break
            if loopcounter == 100:
                print("Finished 100 iterations, we shouldn't be this deep")
                break
        return children[1:]

    def write_children(self, par, clumpid, children):
        """Write the children to file. par: parameters object clumpid: ID of clump for which we're working children: list of children"""
        hfile = ''.join([par.halofilename, '-', str(clumpid), '.txt'])
        f = open(hfile, 'w')
        f.write('# {0:>18} {1:>18} {2:>18}\n'.format('halo', 'nr_of_children', 'children'))
        nc = len(children)
        dumpstring = '  {0:18d} {1:18d}'.format(clumpid, nc)
        dumpstring = ''.join([dumpstring] + [' {0:18d}'.format(c) for c in children] + ['\n'])
        f.write(dumpstring)
        f.close()
        return


消息队列的生产者:主要是通过短信和邮件获得验证码

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

Class description:
消息队列的生产者:主要是通过短信和邮件获得验证码

Method signatures and docstrings:
- def __init__(self, target, code, template, ip=None, **kwargs): :param target: mobile email 平台的发送目标 e.g: mobile:139xx99 email:16xx3@qq.com :param code: 自定义发送内容 e.g: mobile:8888 :param template: 指定平台的发送信息的模板样式,同时也是队列的路由关键字 e.g: mobile:sms_register email:email_info :param ip: :param kwargs:
- def verification_target(self): 鉴别target是否有效 :return:
- def send(self): 生产者产生消息

Implement the Python class `Product` described below.

Class description:
消息队列的生产者:主要是通过短信和邮件获得验证码

Method signatures and docstrings:
- def __init__(self, target, code, template, ip=None, **kwargs): :param target: mobile email 平台的发送目标 e.g: mobile:139xx99 email:16xx3@qq.com :param code: 自定义发送内容 e.g: mobile:8888 :param template: 指定平台的发送信息的模板样式,同时也是队列的路由关键字 e.g: mobile:sms_register email:email_info :param ip: :param kwargs:
- def verification_target(self): 鉴别target是否有效 :return:
- def send(self): 生产者产生消息

<|skeleton|>
class Product:
    """消息队列的生产者:主要是通过短信和邮件获得验证码"""

    def __init__(self, target, code, template, ip=None, **kwargs):
        """:param target: mobile email 平台的发送目标 e.g: mobile:139xx99 email:16xx3@qq.com :param code: 自定义发送内容 e.g: mobile:8888 :param template: 指定平台的发送信息的模板样式,同时也是队列的路由关键字 e.g: mobile:sms_register email:email_info :param ip: :param kwargs:"""
        <|body_0|>

    def verification_target(self):
        """鉴别target是否有效 :return:"""
        <|body_1|>

    def send(self):
        """生产者产生消息"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        self.target = target
        self.code = code
        self.routing_key = template
<|end_body_0|>

<|body_start_1|>
        email_com = re.compile('(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)')
        emailmatch = email_com.match(self.target)
        if emailmatch:
            return True
        mobile_com = re.compile('^(?:\\+?86)?1(?:3\\d{3}|5[^4\\D]\\d{2}|8\\d{3}|7(?:[01356789]\\d{2}|4(?:0\\d|1[0-2]|9\\d))|9[189]\\d{2}|6[567]\\d{2}|4[579]\\d{2})\\d{6}$')
        mobilematch = mobile_com.match(self.target)
        if mobilematch:
            return True
        return False
<|end_body_1|>

<|body_start_2|>
        body = {'target': self.target, 'code': self.code, 'routing_key': self.routing_key}
        body_json = json.dumps(body).encode('utf8')
        connection, channel = get_mq_channel()
        channel.exchange_declare(exchange=MQEXCHANGE, exchange_type=MQEXCHANGETYPE)
        channel.basic_publish(exchange=MQEXCHANGE, routing_key=self.routing_key, body=body_json)
        print(' [x] Sent %r:%r' % (self.routing_key, self.code))
        connection.close()
<|end_body_2|>

Solution:
class Product:
    """消息队列的生产者:主要是通过短信和邮件获得验证码"""

    def __init__(self, target, code, template, ip=None, **kwargs):
        """:param target: mobile email 平台的发送目标 e.g: mobile:139xx99 email:16xx3@qq.com :param code: 自定义发送内容 e.g: mobile:8888 :param template: 指定平台的发送信息的模板样式,同时也是队列的路由关键字 e.g: mobile:sms_register email:email_info :param ip: :param kwargs:"""
        self.target = target
        self.code = code
        self.routing_key = template

    def verification_target(self):
        """鉴别target是否有效 :return:"""
        email_com = re.compile('(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)')
        emailmatch = email_com.match(self.target)
        if emailmatch:
            return True
        mobile_com = re.compile('^(?:\\+?86)?1(?:3\\d{3}|5[^4\\D]\\d{2}|8\\d{3}|7(?:[01356789]\\d{2}|4(?:0\\d|1[0-2]|9\\d))|9[189]\\d{2}|6[567]\\d{2}|4[579]\\d{2})\\d{6}$')
        mobilematch = mobile_com.match(self.target)
        if mobilematch:
            return True
        return False

    def send(self):
        """生产者产生消息"""
        body = {'target': self.target, 'code': self.code, 'routing_key': self.routing_key}
        body_json = json.dumps(body).encode('utf8')
        connection, channel = get_mq_channel()
        channel.exchange_declare(exchange=MQEXCHANGE, exchange_type=MQEXCHANGETYPE)
        channel.basic_publish(exchange=MQEXCHANGE, routing_key=self.routing_key, body=body_json)
        print(' [x] Sent %r:%r' % (self.routing_key, self.code))
        connection.close()


permute

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

Class description:
Implement the Solution_B2 class.

Method signatures and docstrings:
- def permute(self, nums: List[int]) -> List[List[int]]: Version B2 Non-proxy, recursive method, but direct handle elements in nums This only works for when sample is a collection of distinct numbers
- def next_permute(self, nums: List[int]) -> List[int]: Herlper for B1, B2 From Leetcode LC031: next permutation, modified to return a new permute list instead in-place calculate the next permuatation, with integers 0 to N-1 (as idx proxy) this will both modify idx_list and return the updated idx_list

Implement the Python class `Solution_B2` described below.

Class description:
Implement the Solution_B2 class.

Method signatures and docstrings:
- def permute(self, nums: List[int]) -> List[List[int]]: Version B2 Non-proxy, recursive method, but direct handle elements in nums This only works for when sample is a collection of distinct numbers
- def next_permute(self, nums: List[int]) -> List[int]: Herlper for B1, B2 From Leetcode LC031: next permutation, modified to return a new permute list instead in-place calculate the next permuatation, with integers 0 to N-1 (as idx proxy) this will both modify idx_list and return the updated idx_list

<|skeleton|>
class Solution_B2:

    def permute(self, nums: List[int]) -> List[List[int]]:
        """Version B2 Non-proxy, recursive method, but direct handle elements in nums This only works for when sample is a collection of distinct numbers"""
        <|body_0|>

    def next_permute(self, nums: List[int]) -> List[int]:
        """Herlper for B1, B2 From Leetcode LC031: next permutation, modified to return a new permute list instead in-place calculate the next permuatation, with integers 0 to N-1 (as idx proxy) this will both modify idx_list and return the updated idx_list"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        total_n = factorial(len(nums))
        result = []
        for i in range(total_n):
            result.append(nums[:])
            nums = self.next_permute(nums)
        return result
<|end_body_0|>

<|body_start_1|>
        first_idx = len(nums) - 2
        second_idx = len(nums) - 1
        while first_idx >= 0 and nums[first_idx] >= nums[first_idx + 1]:
            first_idx -= 1
        if first_idx == -1:
            return nums[:][::-1]
        else:
            ans = nums[:]
            while ans[second_idx] <= ans[first_idx]:
                second_idx -= 1
            ans[first_idx], ans[second_idx] = (ans[second_idx], ans[first_idx])
            ans[first_idx + 1:] = ans[first_idx + 1:][::-1]
            return ans
<|end_body_1|>

Solution:
class Solution_B2:
    def permute(self, nums: List[int]) -> List[List[int]]:
        """Version B2 Non-proxy, recursive method, but direct handle elements in nums This only works for when sample is a collection of distinct numbers"""
        total_n = factorial(len(nums))
        result = []
        for i in range(total_n):
            result.append(nums[:])
            nums = self.next_permute(nums)
        return result

    def next_permute(self, nums: List[int]) -> List[int]:
        """Herlper for B1, B2 From Leetcode LC031: next permutation, modified to return a new permute list instead in-place calculate the next permuatation, with integers 0 to N-1 (as idx proxy) this will both modify idx_list and return the updated idx_list"""
        first_idx = len(nums) - 2
        second_idx = len(nums) - 1
        while first_idx >= 0 and nums[first_idx] >= nums[first_idx + 1]:
            first_idx -= 1
        if first_idx == -1:
            return nums[:][::-1]
        else:
            ans = nums[:]
            while ans[second_idx] <= ans[first_idx]:
                second_idx -= 1
            ans[first_idx], ans[second_idx] = (ans[second_idx], ans[first_idx])
            ans[first_idx + 1:] = ans[first_idx + 1:][::-1]
            return ans


post

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

Class description:
Delete an existing Theme

Method signatures and docstrings:
- def __init__(self) -> None: Set required arguments for POST request
- def post(self) -> ({str: str}, HTTPStatus): Delete an existing Theme. :param name: name of Theme to delete. :param id: id of Theme to delete. :type name: str :type id: str :returns: A no content with a http status code of 204, otherwise a JSON of the error details and the appropriate http status code

Implement the Python class `DeleteTheme` described below.

Class description:
Delete an existing Theme

Method signatures and docstrings:
- def __init__(self) -> None: Set required arguments for POST request
- def post(self) -> ({str: str}, HTTPStatus): Delete an existing Theme. :param name: name of Theme to delete. :param id: id of Theme to delete. :type name: str :type id: str :returns: A no content with a http status code of 204, otherwise a JSON of the error details and the appropriate http status code

<|skeleton|>
class DeleteTheme:
    """Delete an existing Theme"""

    def __init__(self) -> None:
        """Set required arguments for POST request"""
        <|body_0|>

    def post(self) -> ({str: str}, HTTPStatus):
        """Delete an existing Theme. :param name: name of Theme to delete. :param id: id of Theme to delete. :type name: str :type id: str :returns: A no content with a http status code of 204, otherwise a JSON of the error details and the appropriate http status code"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.reqparser = reqparse.RequestParser()
        self.reqparser.add_argument('name', required=False, store_missing=False, type=str, location=['form', 'json'])
        self.reqparser.add_argument('id', required=False, store_missing=False, type=str, location=['form', 'json'])
<|end_body_0|>

<|body_start_1|>
        if not get_jwt_claims()['admin']:
            return ({'error': 'administration privileges required'}, HTTPStatus.FORBIDDEN)
        args = self.reqparser.parse_args()
        theme = Theme.get_by_name(args['name']) if 'name' in args else Theme.get_by_id(args['id'])
        if not theme:
            return ({'error': 'Theme does not exists.', 'id': ' ', 'name': args['name']}, HTTPStatus.BAD_REQUEST)
        sub_themes = SubTheme.get_by_theme_id(theme.id)
        for sub_theme in sub_themes:
            sub_theme.delete()
            sub_theme.commit()
        theme.delete()
        theme.commit()
        return ('', HTTPStatus.NO_CONTENT)
<|end_body_1|>

Solution:
class DeleteTheme:
    """Delete an existing Theme"""

    def __init__(self) -> None:
        """Set required arguments for POST request"""
        self.reqparser = reqparse.RequestParser()
        self.reqparser.add_argument('name', required=False, store_missing=False, type=str, location=['form', 'json'])
        self.reqparser.add_argument('id', required=False, store_missing=False, type=str, location=['form', 'json'])

    def post(self) -> ({str: str}, HTTPStatus):
        """Delete an existing Theme. :param name: name of Theme to delete. :param id: id of Theme to delete. :type name: str :type id: str :returns: A no content with a http status code of 204, otherwise a JSON of the error details and the appropriate http status code"""
        if not get_jwt_claims()['admin']:
            return ({'error': 'administration privileges required'}, HTTPStatus.FORBIDDEN)
        args = self.reqparser.parse_args()
        theme = Theme.get_by_name(args['name']) if 'name' in args else Theme.get_by_id(args['id'])
        if not theme:
            return ({'error': 'Theme does not exists.', 'id': ' ', 'name': args['name']}, HTTPStatus.BAD_REQUEST)
        sub_themes = SubTheme.get_by_theme_id(theme.id)
        for sub_theme in sub_themes:
            sub_theme.delete()
            sub_theme.commit()
        theme.delete()
        theme.commit()
        return ('', HTTPStatus.NO_CONTENT)


ready

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

Class description:
App configuration class for the 'label' app

Method signatures and docstrings:
- def ready(self): This function is called whenever the label app is loaded.
- def create_labels(self): Create all default templates.
- def create_labels_category(self, model, ref_name, labels): Create folder and database entries for the default templates, if they do not already exist.
- def create_template_label(self, model, src_dir, ref_name, label): Ensure a label template is in place.

Implement the Python class `LabelConfig` described below.

Class description:
App configuration class for the 'label' app

Method signatures and docstrings:
- def ready(self): This function is called whenever the label app is loaded.
- def create_labels(self): Create all default templates.
- def create_labels_category(self, model, ref_name, labels): Create folder and database entries for the default templates, if they do not already exist.
- def create_template_label(self, model, src_dir, ref_name, label): Ensure a label template is in place.

<|skeleton|>
class LabelConfig:
    """App configuration class for the 'label' app"""

    def ready(self):
        """This function is called whenever the label app is loaded."""
        <|body_0|>

    def create_labels(self):
        """Create all default templates."""
        <|body_1|>

    def create_labels_category(self, model, ref_name, labels):
        """Create folder and database entries for the default templates, if they do not already exist."""
        <|body_2|>

    def create_template_label(self, model, src_dir, ref_name, label):
        """Ensure a label template is in place."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        if not isPluginRegistryLoaded() or not isInMainThread():
            return
        if canAppAccessDatabase(allow_test=False):
            try:
                self.create_labels()
            except (AppRegistryNotReady, OperationalError):
                warnings.warn('Database was not ready for creating labels', stacklevel=2)
<|end_body_0|>

<|body_start_1|>
        import label.models
        assert bool(label.models.StockLocationLabel is not None)
        self.create_labels_category(label.models.StockItemLabel, 'stockitem', [{'file': 'qr.html', 'name': 'QR Code', 'description': 'Simple QR code label', 'width': 24, 'height': 24}])
        self.create_labels_category(label.models.StockLocationLabel, 'stocklocation', [{'file': 'qr.html', 'name': 'QR Code', 'description': 'Simple QR code label', 'width': 24, 'height': 24}, {'file': 'qr_and_text.html', 'name': 'QR and text', 'description': 'Label with QR code and name of location', 'width': 50, 'height': 24}])
        self.create_labels_category(label.models.PartLabel, 'part', [{'file': 'part_label.html', 'name': 'Part Label', 'description': 'Simple part label', 'width': 70, 'height': 24}, {'file': 'part_label_code128.html', 'name': 'Barcode Part Label', 'description': 'Simple part label with Code128 barcode', 'width': 70, 'height': 24}])
        self.create_labels_category(label.models.BuildLineLabel, 'buildline', [{'file': 'buildline_label.html', 'name': 'Build Line Label', 'description': 'Example build line label', 'width': 125, 'height': 48}])
<|end_body_1|>

<|body_start_2|>
        src_dir = Path(__file__).parent.joinpath('templates', 'label', ref_name)
        dst_dir = settings.MEDIA_ROOT.joinpath('label', 'inventree', ref_name)
        if not dst_dir.exists():
            logger.info(f"Creating required directory: '{dst_dir}'")
            dst_dir.mkdir(parents=True, exist_ok=True)
        for label in labels:
            self.create_template_label(model, src_dir, ref_name, label)
<|end_body_2|>

<|body_start_3|>
        filename = os.path.join('label', 'inventree', ref_name, label['file'])
        src_file = src_dir.joinpath(label['file'])
        dst_file = settings.MEDIA_ROOT.joinpath(filename)
        to_copy = False
        if dst_file.exists():
            if hashFile(dst_file) != hashFile(src_file):
                logger.info(f"Hash differs for '{filename}'")
                to_copy = True
        else:
            logger.info(f"Label template '{filename}' is not present")
            to_copy = True
        if to_copy:
            logger.info(f"Copying label template '{dst_file}'")
            dst_file.parent.mkdir(parents=True, exist_ok=True)
            shutil.copyfile(src_file, dst_file)
        if model.objects.filter(label=filename).exists():
            return
        logger.info(f"Creating entry for {model} '{label['name']}'")
        try:
            model.objects.create(name=label['name'], description=label['description'], label=filename, filters='', enabled=True, width=label['width'], height=label['height'])
        except Exception:
            logger.warning(f"Failed to create label '{label['name']}'")
<|end_body_3|>

Solution:
class LabelConfig:
    """App configuration class for the 'label' app"""

    def ready(self):
        """This function is called whenever the label app is loaded."""
        if not isPluginRegistryLoaded() or not isInMainThread():
            return
        if canAppAccessDatabase(allow_test=False):
            try:
                self.create_labels()
            except (AppRegistryNotReady, OperationalError):
                warnings.warn('Database was not ready for creating labels', stacklevel=2)

    def create_labels(self):
        """Create all default templates."""
        import label.models
        assert bool(label.models.StockLocationLabel is not None)
        self.create_labels_category(label.models.StockItemLabel, 'stockitem', [{'file': 'qr.html', 'name': 'QR Code', 'description': 'Simple QR code label', 'width': 24, 'height': 24}])
        self.create_labels_category(label.models.StockLocationLabel, 'stocklocation', [{'file': 'qr.html', 'name': 'QR Code', 'description': 'Simple QR code label', 'width': 24, 'height': 24}, {'file': 'qr_and_text.html', 'name': 'QR and text', 'description': 'Label with QR code and name of location', 'width': 50, 'height': 24}])
        self.create_labels_category(label.models.PartLabel, 'part', [{'file': 'part_label.html', 'name': 'Part Label', 'description': 'Simple part label', 'width': 70, 'height': 24}, {'file': 'part_label_code128.html', 'name': 'Barcode Part Label', 'description': 'Simple part label with Code128 barcode', 'width': 70, 'height': 24}])
        self.create_labels_category(label.models.BuildLineLabel, 'buildline', [{'file': 'buildline_label.html', 'name': 'Build Line Label', 'description': 'Example build line label', 'width': 125, 'height': 48}])

    def create_labels_category(self, model, ref_name, labels):
        """Create folder and database entries for the default templates, if they do not already exist."""
        src_dir = Path(__file__).parent.joinpath('templates', 'label', ref_name)
        dst_dir = settings.MEDIA_ROOT.joinpath('label', 'inventree', ref_name)
        if not dst_dir.exists():
            logger.info(f"Creating required directory: '{dst_dir}'")
            dst_dir.mkdir(parents=True, exist_ok=True)
        for label in labels:
            self.create_template_label(model, src_dir, ref_name, label)

    def create_template_label(self, model, src_dir, ref_name, label):
        """Ensure a label template is in place."""
        filename = os.path.join('label', 'inventree', ref_name, label['file'])
        src_file = src_dir.joinpath(label['file'])
        dst_file = settings.MEDIA_ROOT.joinpath(filename)
        to_copy = False
        if dst_file.exists():
            if hashFile(dst_file) != hashFile(src_file):
                logger.info(f"Hash differs for '{filename}'")
                to_copy = True
        else:
            logger.info(f"Label template '{filename}' is not present")
            to_copy = True
        if to_copy:
            logger.info(f"Copying label template '{dst_file}'")
            dst_file.parent.mkdir(parents=True, exist_ok=True)
            shutil.copyfile(src_file, dst_file)
        if model.objects.filter(label=filename).exists():
            return
        logger.info(f"Creating entry for {model} '{label['name']}'")
        try:
            model.objects.create(name=label['name'], description=label['description'], label=filename, filters='', enabled=True, width=label['width'], height=label['height'])
        except Exception:
            logger.warning(f"Failed to create label '{label['name']}'")


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

Class description:
Represents result of loading a `.env` file or just content. Attributes ---------- file_path : `str` Path to the loaded file. parser_failure_info : `None`, ``ParserFailureInfo`` Failure info if parsing failed. variables : `dict<str, None | str>` The loaded environmental variables.

Method signatures and docstrings:
- def __new__(cls, variables, parser_failure_info, file_path): Creates a new dot-env result. Parameters ---------- variables : `dict<str, None | str>` The loaded environmental variables. parser_failure_info : `None`, ``ParserFailureInfo`` Failure info if parsing failed. file_path : `str` Path to the loaded file.
- def insert_to_environmental_variables(self): Inserts the parsed variables into the environmental ones. If the variable already exists, will not overwrite it. Returns ------- self : `instance<type<self>>`
- def raise_if_failed(self): Raises an exception with a reason why loading failed. Returns ------- self : `instance<type<self>>` Raises ------ SyntaxError
- def __repr__(self): Returns the dot env result's representation.

Implement the Python class `DotEnvResult` described below.

Class description:
Represents result of loading a `.env` file or just content. Attributes ---------- file_path : `str` Path to the loaded file. parser_failure_info : `None`, ``ParserFailureInfo`` Failure info if parsing failed. variables : `dict<str, None | str>` The loaded environmental variables.

Method signatures and docstrings:
- def __new__(cls, variables, parser_failure_info, file_path): Creates a new dot-env result. Parameters ---------- variables : `dict<str, None | str>` The loaded environmental variables. parser_failure_info : `None`, ``ParserFailureInfo`` Failure info if parsing failed. file_path : `str` Path to the loaded file.
- def insert_to_environmental_variables(self): Inserts the parsed variables into the environmental ones. If the variable already exists, will not overwrite it. Returns ------- self : `instance<type<self>>`
- def raise_if_failed(self): Raises an exception with a reason why loading failed. Returns ------- self : `instance<type<self>>` Raises ------ SyntaxError
- def __repr__(self): Returns the dot env result's representation.

<|skeleton|>
class DotEnvResult:
    """Represents result of loading a `.env` file or just content. Attributes ---------- file_path : `str` Path to the loaded file. parser_failure_info : `None`, ``ParserFailureInfo`` Failure info if parsing failed. variables : `dict<str, None | str>` The loaded environmental variables."""

    def __new__(cls, variables, parser_failure_info, file_path):
        """Creates a new dot-env result. Parameters ---------- variables : `dict<str, None | str>` The loaded environmental variables. parser_failure_info : `None`, ``ParserFailureInfo`` Failure info if parsing failed. file_path : `str` Path to the loaded file."""
        <|body_0|>

    def insert_to_environmental_variables(self):
        """Inserts the parsed variables into the environmental ones. If the variable already exists, will not overwrite it. Returns ------- self : `instance<type<self>>`"""
        <|body_1|>

    def raise_if_failed(self):
        """Raises an exception with a reason why loading failed. Returns ------- self : `instance<type<self>>` Raises ------ SyntaxError"""
        <|body_2|>

    def __repr__(self):
        """Returns the dot env result's representation."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        self = object.__new__(cls)
        self.variables = variables
        self.parser_failure_info = parser_failure_info
        self.file_path = file_path
        return self
<|end_body_0|>

<|body_start_1|>
        for key, value in self.variables.items():
            if value is None:
                value = ''
            environmental_variables.setdefault(key, value)
            if environmental_variables_binary is not None:
                environmental_variables_binary.setdefault(key.encode(), value.encode())
        return self
<|end_body_1|>

<|body_start_2|>
        parser_failure_info = self.parser_failure_info
        if parser_failure_info is not None:
            raise SyntaxError(parser_failure_info.get_error_message(), (self.file_path, parser_failure_info.line_index + 1, parser_failure_info.index + 1, parser_failure_info.line))
        return self
<|end_body_2|>

<|body_start_3|>
        repr_parts = ['<', self.__class__.__name__]
        repr_parts.append(' variables: ')
        repr_parts.append(repr(len(self.variables)))
        parser_failure_info = self.parser_failure_info
        if parser_failure_info is not None:
            repr_parts.append(', parser_failure_info = ')
            repr_parts.append(repr(parser_failure_info))
        file_path = self.file_path
        if file_path is not None:
            repr_parts.append(' file_path = ')
            repr_parts.append(repr(file_path))
        repr_parts.append('>')
        return ''.join(repr_parts)
<|end_body_3|>

Solution:
class DotEnvResult:
    """Represents result of loading a `.env` file or just content. Attributes ---------- file_path : `str` Path to the loaded file. parser_failure_info : `None`, ``ParserFailureInfo`` Failure info if parsing failed. variables : `dict<str, None | str>` The loaded environmental variables."""

    def __new__(cls, variables, parser_failure_info, file_path):
        """Creates a new dot-env result. Parameters ---------- variables : `dict<str, None | str>` The loaded environmental variables. parser_failure_info : `None`, ``ParserFailureInfo`` Failure info if parsing failed. file_path : `str` Path to the loaded file."""
        self = object.__new__(cls)
        self.variables = variables
        self.parser_failure_info = parser_failure_info
        self.file_path = file_path
        return self

    def insert_to_environmental_variables(self):
        """Inserts the parsed variables into the environmental ones. If the variable already exists, will not overwrite it. Returns ------- self : `instance<type<self>>`"""
        for key, value in self.variables.items():
            if value is None:
                value = ''
            environmental_variables.setdefault(key, value)
            if environmental_variables_binary is not None:
                environmental_variables_binary.setdefault(key.encode(), value.encode())
        return self

    def raise_if_failed(self):
        """Raises an exception with a reason why loading failed. Returns ------- self : `instance<type<self>>` Raises ------ SyntaxError"""
        parser_failure_info = self.parser_failure_info
        if parser_failure_info is not None:
            raise SyntaxError(parser_failure_info.get_error_message(), (self.file_path, parser_failure_info.line_index + 1, parser_failure_info.index + 1, parser_failure_info.line))
        return self

    def __repr__(self):
        """Returns the dot env result's representation."""
        repr_parts = ['<', self.__class__.__name__]
        repr_parts.append(' variables: ')
        repr_parts.append(repr(len(self.variables)))
        parser_failure_info = self.parser_failure_info
        if parser_failure_info is not None:
            repr_parts.append(', parser_failure_info = ')
            repr_parts.append(repr(parser_failure_info))
        file_path = self.file_path
        if file_path is not None:
            repr_parts.append(' file_path = ')
            repr_parts.append(repr(file_path))
        repr_parts.append('>')
        return ''.join(repr_parts)


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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def maxAreaBrute(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def maxAreaBrute(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int

<|skeleton|>
class Solution:

    def maxAreaBrute(self, height):
        """:type height: List[int] :rtype: int"""
        <|body_0|>

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

<|end_skeleton|>

<|body_start_0|>
        l = height
        size = 0
        for i in range(len(l)):
            for j in range(i, len(l)):
                print(l[i], l[j])
                if l[i] < l[j]:
                    size = max(size, l[i] * (j - i))
                else:
                    size = max(size, l[j] * (j - i))
        return size
<|end_body_0|>

<|body_start_1|>
        head = 0
        tail = len(height) - 1
        size = 0
        while head < tail:
            size = max(size, min(height[head], height[tail]) * (tail - head))
            if height[head] < height[tail]:
                head += 1
            else:
                tail -= 1
        return size
<|end_body_1|>

Solution:
class Solution:
    def maxAreaBrute(self, height):
        """:type height: List[int] :rtype: int"""
        l = height
        size = 0
        for i in range(len(l)):
            for j in range(i, len(l)):
                print(l[i], l[j])
                if l[i] < l[j]:
                    size = max(size, l[i] * (j - i))
                else:
                    size = max(size, l[j] * (j - i))
        return size

    def maxArea(self, height):
        """:type height: List[int] :rtype: int"""
        head = 0
        tail = len(height) - 1
        size = 0
        while head < tail:
            size = max(size, min(height[head], height[tail]) * (tail - head))
            if height[head] < height[tail]:
                head += 1
            else:
                tail -= 1
        return size


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

Class description:
Implement the NovelUpdatesCC class.

Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return as clean html format.

Implement the Python class `NovelUpdatesCC` described below.

Class description:
Implement the NovelUpdatesCC class.

Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return as clean html format.

<|skeleton|>
class NovelUpdatesCC:

    def read_novel_info(self):
        """Get novel title, autor, cover etc"""
        <|body_0|>

    def download_chapter_body(self, chapter):
        """Download body of a single chapter and return as clean html format."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        logger.debug('Visiting %s', self.novel_url)
        soup = self.get_soup(self.novel_url)
        self.novel_title = soup.select_one('div.book-name').text.strip()
        logger.info('Novel title: %s', self.novel_title)
        self.novel_author = soup.select_one('div.author span.name').text.strip()
        logger.info('Novel author: %s', self.novel_author)
        self.novel_cover = self.absolute_url(soup.select_one('div.book-img img')['src'])
        logger.info('Novel cover: %s', self.novel_cover)
        chapters = soup.select('ul.chapter-list a')
        for a in chapters:
            chap_id = len(self.chapters) + 1
            if len(self.chapters) % 100 == 0:
                vol_id = chap_id // 100 + 1
                vol_title = 'Volume ' + str(vol_id)
                self.volumes.append({'id': vol_id, 'title': vol_title})
            self.chapters.append({'id': chap_id, 'volume': vol_id, 'url': self.absolute_url(a['href']), 'title': a.select_one('p.chapter-name').text.strip() or 'Chapter %d' % chap_id})
        logger.info('%d chapters and %d volumes found', len(self.chapters), len(self.volumes))
<|end_body_0|>

<|body_start_1|>
        logger.info('Downloading %s', chapter['url'])
        soup = self.get_soup(chapter['url'])
        chapter['title'] = soup.select_one('h1.chapter-title').text.strip()
        self.blacklist_patterns = ['^translat(ed by|or)', '(volume|chapter) .?\\d+']
        body_parts = soup.select_one('div.chapter-entity')
        for br in body_parts.select('br'):
            br.decompose()
        body = self.extract_contents(body_parts)
        return '
' + '

'.join(body) + '
'
<|end_body_1|>

Solution:
class NovelUpdatesCC:
    def read_novel_info(self):
        """Get novel title, autor, cover etc"""
        logger.debug('Visiting %s', self.novel_url)
        soup = self.get_soup(self.novel_url)
        self.novel_title = soup.select_one('div.book-name').text.strip()
        logger.info('Novel title: %s', self.novel_title)
        self.novel_author = soup.select_one('div.author span.name').text.strip()
        logger.info('Novel author: %s', self.novel_author)
        self.novel_cover = self.absolute_url(soup.select_one('div.book-img img')['src'])
        logger.info('Novel cover: %s', self.novel_cover)
        chapters = soup.select('ul.chapter-list a')
        for a in chapters:
            chap_id = len(self.chapters) + 1
            if len(self.chapters) % 100 == 0:
                vol_id = chap_id // 100 + 1
                vol_title = 'Volume ' + str(vol_id)
                self.volumes.append({'id': vol_id, 'title': vol_title})
            self.chapters.append({'id': chap_id, 'volume': vol_id, 'url': self.absolute_url(a['href']), 'title': a.select_one('p.chapter-name').text.strip() or 'Chapter %d' % chap_id})
        logger.info('%d chapters and %d volumes found', len(self.chapters), len(self.volumes))

    def download_chapter_body(self, chapter):
        """Download body of a single chapter and return as clean html format."""
        logger.info('Downloading %s', chapter['url'])
        soup = self.get_soup(chapter['url'])
        chapter['title'] = soup.select_one('h1.chapter-title').text.strip()
        self.blacklist_patterns = ['^translat(ed by|or)', '(volume|chapter) .?\\d+']
        body_parts = soup.select_one('div.chapter-entity')
        for br in body_parts.select('br'):
            br.decompose()
        body = self.extract_contents(body_parts)
        return '
' + '

'.join(body) + '
'


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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def rotate_1(self, nums: List[int], k: int) -> None: Do not return anything, modify nums in-place instead.
- def rotate_2(self, nums: List[int], k: int) -> None: Do not return anything, modify nums in-place instead.

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def rotate_1(self, nums: List[int], k: int) -> None: Do not return anything, modify nums in-place instead.
- def rotate_2(self, nums: List[int], k: int) -> None: Do not return anything, modify nums in-place instead.

<|skeleton|>
class Solution:

    def rotate_1(self, nums: List[int], k: int) -> None:
        """Do not return anything, modify nums in-place instead."""
        <|body_0|>

    def rotate_2(self, nums: List[int], k: int) -> None:
        """Do not return anything, modify nums in-place instead."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        k = k % len(nums)
        for i in range(k):
            last = nums[-1]
            for j in range(len(nums) - 1, 0, -1):
                nums[j] = nums[j - 1]
            nums[0] = last
<|end_body_0|>

<|body_start_1|>
        k = k % len(nums)

        def reverse(nums, left, right):
            while left < right:
                nums[left], nums[right] = (nums[right], nums[left])
                left += 1
                right -= 1
        reverse(nums, 0, len(nums) - 1)
        reverse(nums, 0, k - 1)
        reverse(nums, k, len(nums) - 1)
<|end_body_1|>

Solution:
class Solution:
    def rotate_1(self, nums: List[int], k: int) -> None:
        """Do not return anything, modify nums in-place instead."""
        k = k % len(nums)
        for i in range(k):
            last = nums[-1]
            for j in range(len(nums) - 1, 0, -1):
                nums[j] = nums[j - 1]
            nums[0] = last

    def rotate_2(self, nums: List[int], k: int) -> None:
        """Do not return anything, modify nums in-place instead."""
        k = k % len(nums)

        def reverse(nums, left, right):
            while left < right:
                nums[left], nums[right] = (nums[right], nums[left])
                left += 1
                right -= 1
        reverse(nums, 0, len(nums) - 1)
        reverse(nums, 0, k - 1)
        reverse(nums, k, len(nums) - 1)


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

Class description:
Implement the TimelineSegment class.

Method signatures and docstrings:
- def __init__(self, timeline_files, timeline_props, timestep, frequency, name): :param timeline_files: tml files :param timeline_props: tml files properties :param timestep: md timestep :param frequency: md trajectory save frequency
- def __contains__(self, residue): :param residue: check if residue present in timeline :return: true if present
- def get_resi(self, residue): :param residue: selected residue :return: get residue from timeline
- def parse_tml(self): parse tml file
- def get_prop(self, prop): :param prop: :return:
- def print_prop(self, props): :param props: properties to plot

Implement the Python class `TimelineSegment` described below.

Class description:
Implement the TimelineSegment class.

Method signatures and docstrings:
- def __init__(self, timeline_files, timeline_props, timestep, frequency, name): :param timeline_files: tml files :param timeline_props: tml files properties :param timestep: md timestep :param frequency: md trajectory save frequency
- def __contains__(self, residue): :param residue: check if residue present in timeline :return: true if present
- def get_resi(self, residue): :param residue: selected residue :return: get residue from timeline
- def parse_tml(self): parse tml file
- def get_prop(self, prop): :param prop: :return:
- def print_prop(self, props): :param props: properties to plot

<|skeleton|>
class TimelineSegment:

    def __init__(self, timeline_files, timeline_props, timestep, frequency, name):
        """:param timeline_files: tml files :param timeline_props: tml files properties :param timestep: md timestep :param frequency: md trajectory save frequency"""
        <|body_0|>

    def __contains__(self, residue):
        """:param residue: check if residue present in timeline :return: true if present"""
        <|body_1|>

    def get_resi(self, residue):
        """:param residue: selected residue :return: get residue from timeline"""
        <|body_2|>

    def parse_tml(self):
        """parse tml file"""
        <|body_3|>

    def get_prop(self, prop):
        """:param prop: :return:"""
        <|body_4|>

    def print_prop(self, props):
        """:param props: properties to plot"""
        <|body_5|>

<|end_skeleton|>

<|body_start_0|>
        self.name = name
        self.timeline_files = timeline_files
        self.timeline_props = timeline_props
        self.timeframe = timestep * frequency * 1e-06
        self.residues = []
        self.parse_tml()
<|end_body_0|>

<|body_start_1|>
        for resi in self.residues:
            if residue.resid == resi.resid and residue.segname == resi.segname:
                return True
        return False
<|end_body_1|>

<|body_start_2|>
        for resi in self.residues:
            if residue.resid == resi.resid and residue.segname == resi.segname:
                return resi
<|end_body_2|>

<|body_start_3|>
        for file, prop in zip(self.timeline_files, self.timeline_props):
            with open(file) as fl:
                timeline = [line.rstrip('\n').split() for line in fl.readlines() if '#' not in line]
                timeline = [[int(line[0]), line[2], float(line[3]) * self.timeframe, float(line[4])] for line in timeline]
                for line in timeline:
                    new_residue = TimelineResidue(line[0], line[1])
                    new_residue.add_property(prop, [line[2:4]])
                    if new_residue not in self:
                        self.residues.append(new_residue)
                    else:
                        self.get_resi(new_residue).properties[prop].append(line[2:4])
                for resi in self.residues:
                    resi.mean_property(prop)
<|end_body_3|>

<|body_start_4|>
        resids = [resi.resid for resi in self.residues]
        prop_values = [[resi.means[prop] for resi in self.residues]]
        return np.array(list(zip(resids, *prop_values)))
<|end_body_4|>

<|body_start_5|>
        resids = [resi.resid for resi in self.residues]
        prop_values = []
        for prop in props:
            prop_values.append([resi.means[prop] for resi in self.residues])
        dataseries = [np.array(list(zip(resids, *prop_values)))]
        mmplt.plot_simple_multiple_numpy(dataseries, 'Residue position', prop, [self.name], self.name, sizex=2.5, sizey=1.5)
<|end_body_5|>

Solution:
class TimelineSegment:
    def __init__(self, timeline_files, timeline_props, timestep, frequency, name):
        """:param timeline_files: tml files :param timeline_props: tml files properties :param timestep: md timestep :param frequency: md trajectory save frequency"""
        self.name = name
        self.timeline_files = timeline_files
        self.timeline_props = timeline_props
        self.timeframe = timestep * frequency * 1e-06
        self.residues = []
        self.parse_tml()

    def __contains__(self, residue):
        """:param residue: check if residue present in timeline :return: true if present"""
        for resi in self.residues:
            if residue.resid == resi.resid and residue.segname == resi.segname:
                return True
        return False

    def get_resi(self, residue):
        """:param residue: selected residue :return: get residue from timeline"""
        for resi in self.residues:
            if residue.resid == resi.resid and residue.segname == resi.segname:
                return resi

    def parse_tml(self):
        """parse tml file"""
        for file, prop in zip(self.timeline_files, self.timeline_props):
            with open(file) as fl:
                timeline = [line.rstrip('\n').split() for line in fl.readlines() if '#' not in line]
                timeline = [[int(line[0]), line[2], float(line[3]) * self.timeframe, float(line[4])] for line in timeline]
                for line in timeline:
                    new_residue = TimelineResidue(line[0], line[1])
                    new_residue.add_property(prop, [line[2:4]])
                    if new_residue not in self:
                        self.residues.append(new_residue)
                    else:
                        self.get_resi(new_residue).properties[prop].append(line[2:4])
                for resi in self.residues:
                    resi.mean_property(prop)

    def get_prop(self, prop):
        """:param prop: :return:"""
        resids = [resi.resid for resi in self.residues]
        prop_values = [[resi.means[prop] for resi in self.residues]]
        return np.array(list(zip(resids, *prop_values)))

    def print_prop(self, props):
        """:param props: properties to plot"""
        resids = [resi.resid for resi in self.residues]
        prop_values = []
        for prop in props:
            prop_values.append([resi.means[prop] for resi in self.residues])
        dataseries = [np.array(list(zip(resids, *prop_values)))]
        mmplt.plot_simple_multiple_numpy(dataseries, 'Residue position', prop, [self.name], self.name, sizex=2.5, sizey=1.5)


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

Class description:
AoC 2015 Day 21

Method signatures and docstrings:
- def part1(_filename: str) -> int: Given a filename, solve 2015 day 21 part 1
- def part2(_filename: str) -> int: Given a filename, solve 2015 day 21 part 2

Implement the Python class `Day21` described below.

Class description:
AoC 2015 Day 21

Method signatures and docstrings:
- def part1(_filename: str) -> int: Given a filename, solve 2015 day 21 part 1
- def part2(_filename: str) -> int: Given a filename, solve 2015 day 21 part 2

<|skeleton|>
class Day21:
    """AoC 2015 Day 21"""

    def part1(_filename: str) -> int:
        """Given a filename, solve 2015 day 21 part 1"""
        <|body_0|>

    def part2(_filename: str) -> int:
        """Given a filename, solve 2015 day 21 part 2"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        sets = collections()
        boss = Char(104, 8, 1)
        return part1(sets, boss)
<|end_body_0|>

<|body_start_1|>
        sets = collections()
        boss = Char(104, 8, 1)
        return part2(sets, boss)
<|end_body_1|>

Solution:
class Day21:
    """AoC 2015 Day 21"""

    def part1(_filename: str) -> int:
        """Given a filename, solve 2015 day 21 part 1"""
        sets = collections()
        boss = Char(104, 8, 1)
        return part1(sets, boss)

    def part2(_filename: str) -> int:
        """Given a filename, solve 2015 day 21 part 2"""
        sets = collections()
        boss = Char(104, 8, 1)
        return part2(sets, boss)


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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def longestUnivaluePath(self, root): Args: root: TreeNode Return: int
- def dfs(self, root): Args: root: TreeNode Return: int

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def longestUnivaluePath(self, root): Args: root: TreeNode Return: int
- def dfs(self, root): Args: root: TreeNode Return: int

<|skeleton|>
class Solution:

    def longestUnivaluePath(self, root):
        """Args: root: TreeNode Return: int"""
        <|body_0|>

    def dfs(self, root):
        """Args: root: TreeNode Return: int"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.res = 0
        self.dfs(root)
        return self.res
<|end_body_0|>

<|body_start_1|>
        if not root:
            return 0
        left = self.dfs(root.left)
        right = self.dfs(root.right)
        if root.left and root.left.val == root.val:
            left += 1
        else:
            left = 0
        if root.right and root.right.val == root.val:
            right += 1
        else:
            right = 0
        self.res = max(self.res, left + right)
        return max(left, right)
<|end_body_1|>

Solution:
class Solution:
    def longestUnivaluePath(self, root):
        """Args: root: TreeNode Return: int"""
        self.res = 0
        self.dfs(root)
        return self.res

    def dfs(self, root):
        """Args: root: TreeNode Return: int"""
        if not root:
            return 0
        left = self.dfs(root.left)
        right = self.dfs(root.right)
        if root.left and root.left.val == root.val:
            left += 1
        else:
            left = 0
        if root.right and root.right.val == root.val:
            right += 1
        else:
            right = 0
        self.res = max(self.res, left + right)
        return max(left, right)