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

Class description:
Implement the Test040GetLogRecords class.

Method signatures and docstrings:
- def test_010_create_events(self): Event log contains the correct number of create events.
- def test_020_get_total_events(self): Get total number of events.
- def xevent_log_contains_create_events(self): Event log contains create events for all objects that are currently known. Timestamp slicing includes the correct object.

Implement the Python class `Test040GetLogRecords` described below.

Class description:
Implement the Test040GetLogRecords class.

Method signatures and docstrings:
- def test_010_create_events(self): Event log contains the correct number of create events.
- def test_020_get_total_events(self): Get total number of events.
- def xevent_log_contains_create_events(self): Event log contains create events for all objects that are currently known. Timestamp slicing includes the correct object.

<|skeleton|>
class Test040GetLogRecords:

    def test_010_create_events(self):
        """Event log contains the correct number of create events."""
        <|body_0|>

    def test_020_get_total_events(self):
        """Get total number of events."""
        <|body_1|>

    def xevent_log_contains_create_events(self):
        """Event log contains create events for all objects that are currently known. Timestamp slicing includes the correct object."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        client = test_client.TestClient(context.node['baseurl'])
        log_records = client.getLogRecords(context.TOKEN, datetime.datetime(1800, 1, 1), event='create')
        assert log_records.total == context.object_total
<|end_body_0|>

<|body_start_1|>
        client = test_client.TestClient(context.node['baseurl'])
        log_records = client.getLogRecords(context.TOKEN, datetime.datetime(1800, 1, 1))
        context.log_records_total = log_records.total
<|end_body_1|>

<|body_start_2|>
        dates = []
        for object_list in context.slices:
            for object_info in object_list.objectInfo:
                dates.append(object_info.dateSysMetadataModified)
        client = test_client.TestClient(context.node['baseurl'])
        logRecords = client.getLogRecords('<dummy token>', datetime.datetime(1800, 1, 1))
        assert len(logRecords.logEntry) == EVENTS_TOTAL
        found = False
        for o in logRecords.logEntry:
            if o.identifier.value() == 'hdl:10255/dryad.654/mets.xml' and o.event == 'create':
                found = True
                break
        assert found
<|end_body_2|>

Solution:
class Test040GetLogRecords:
    def test_010_create_events(self):
        """Event log contains the correct number of create events."""
        client = test_client.TestClient(context.node['baseurl'])
        log_records = client.getLogRecords(context.TOKEN, datetime.datetime(1800, 1, 1), event='create')
        assert log_records.total == context.object_total

    def test_020_get_total_events(self):
        """Get total number of events."""
        client = test_client.TestClient(context.node['baseurl'])
        log_records = client.getLogRecords(context.TOKEN, datetime.datetime(1800, 1, 1))
        context.log_records_total = log_records.total

    def xevent_log_contains_create_events(self):
        """Event log contains create events for all objects that are currently known. Timestamp slicing includes the correct object."""
        dates = []
        for object_list in context.slices:
            for object_info in object_list.objectInfo:
                dates.append(object_info.dateSysMetadataModified)
        client = test_client.TestClient(context.node['baseurl'])
        logRecords = client.getLogRecords('<dummy token>', datetime.datetime(1800, 1, 1))
        assert len(logRecords.logEntry) == EVENTS_TOTAL
        found = False
        for o in logRecords.logEntry:
            if o.identifier.value() == 'hdl:10255/dryad.654/mets.xml' and o.event == 'create':
                found = True
                break
        assert found


createAgent

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

Class description:
Missing associated documentation comment in .proto file.

Method signatures and docstrings:
- def createAgent(self, request, context): Missing associated documentation comment in .proto file.
- def updateAgent(self, request, context): Missing associated documentation comment in .proto file.
- def deleteAgent(self, request, context): Missing associated documentation comment in .proto file.
- def getAgent(self, request, context): Missing associated documentation comment in .proto file.

Implement the Python class `AgentProfileServiceServicer` described below.

Class description:
Missing associated documentation comment in .proto file.

Method signatures and docstrings:
- def createAgent(self, request, context): Missing associated documentation comment in .proto file.
- def updateAgent(self, request, context): Missing associated documentation comment in .proto file.
- def deleteAgent(self, request, context): Missing associated documentation comment in .proto file.
- def getAgent(self, request, context): Missing associated documentation comment in .proto file.

<|skeleton|>
class AgentProfileServiceServicer:
    """Missing associated documentation comment in .proto file."""

    def createAgent(self, request, context):
        """Missing associated documentation comment in .proto file."""
        <|body_0|>

    def updateAgent(self, request, context):
        """Missing associated documentation comment in .proto file."""
        <|body_1|>

    def deleteAgent(self, request, context):
        """Missing associated documentation comment in .proto file."""
        <|body_2|>

    def getAgent(self, request, context):
        """Missing associated documentation comment in .proto file."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')
<|end_body_0|>

<|body_start_1|>
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')
<|end_body_1|>

<|body_start_2|>
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')
<|end_body_2|>

<|body_start_3|>
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')
<|end_body_3|>

Solution:
class AgentProfileServiceServicer:
    """Missing associated documentation comment in .proto file."""

    def createAgent(self, request, context):
        """Missing associated documentation comment in .proto file."""
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')

    def updateAgent(self, request, context):
        """Missing associated documentation comment in .proto file."""
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')

    def deleteAgent(self, request, context):
        """Missing associated documentation comment in .proto file."""
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')

    def getAgent(self, request, context):
        """Missing associated documentation comment in .proto file."""
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')


get

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

Class description:
Implement the TemplateVersionManager class.

Method signatures and docstrings:
- def list(self, response_key=True, **kwargs): Get a list of template versions. :rtype: list of :class:`TemplateVersion`
- def get(self, template_version, response_key=True, **kwargs): Get a list of functions for a specific resource_type. :param template_version: template version to get the functions for

Implement the Python class `TemplateVersionManager` described below.

Class description:
Implement the TemplateVersionManager class.

Method signatures and docstrings:
- def list(self, response_key=True, **kwargs): Get a list of template versions. :rtype: list of :class:`TemplateVersion`
- def get(self, template_version, response_key=True, **kwargs): Get a list of functions for a specific resource_type. :param template_version: template version to get the functions for

<|skeleton|>
class TemplateVersionManager:

    def list(self, response_key=True, **kwargs):
        """Get a list of template versions. :rtype: list of :class:`TemplateVersion`"""
        <|body_0|>

    def get(self, template_version, response_key=True, **kwargs):
        """Get a list of functions for a specific resource_type. :param template_version: template version to get the functions for"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        url = '/template_versions'
        if response_key:
            return self._get(url, 'template_versions', **kwargs)
        else:
            return self._get(url, **kwargs)
<|end_body_0|>

<|body_start_1|>
        url = '/template_versions/%s/functions' % template_version
        if response_key:
            return self._get(url, 'template_functions', **kwargs)
        else:
            return self._get(url, **kwargs)
<|end_body_1|>

Solution:
class TemplateVersionManager:
    def list(self, response_key=True, **kwargs):
        """Get a list of template versions. :rtype: list of :class:`TemplateVersion`"""
        url = '/template_versions'
        if response_key:
            return self._get(url, 'template_versions', **kwargs)
        else:
            return self._get(url, **kwargs)

    def get(self, template_version, response_key=True, **kwargs):
        """Get a list of functions for a specific resource_type. :param template_version: template version to get the functions for"""
        url = '/template_versions/%s/functions' % template_version
        if response_key:
            return self._get(url, 'template_functions', **kwargs)
        else:
            return self._get(url, **kwargs)


Start

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

Class description:
Builds the complete task list for the installation.

Method signatures and docstrings:
- def Start(self, out_file, in_path, in_file='build.yaml'): Start parsing configuration files. Args: out_file: The location to store the compiled config data. in_path: The path to the root configuration file. in_file: The root configuration file name.
- def _Start(self, conf_path, conf_file): Pull and process a config file. Args: conf_path: The path to the config below root. conf_file: A named config file, normally build.yaml.
- def _MatchPin(self, pins): Check all pin entries for a mismatch. Pins can mismatch either by the matching setting being omitted or by matching an exclusion (!). Example: pins: ['os', ['win7', 'win8']] * Will match os = win7 or os = win8. * Will fail to match os = '2012r2'. * Will match model = 'vmware' (because model is not pinned). Example 2: pins: ['os', ['!win7']] * Will match os = win8 or os = 2012r2. * Will fail to match os = 'win7'. * Will match model = 'vmware' (because model is not pinned). Args: pins: a list of all applicable pin names and acceptable values Returns: True if this host passes all pin checks. False if the host fails a match.
- def _StoreControls(self, control, templates): Process all of the possible sub-sections of a main control section. Args: control: The data from this control subsection. templates: Any templates declared in the current config. Raises: UnknownActionError: Attempt to process an unknown command element.

Implement the Python class `ConfigBuilder` described below.

Class description:
Builds the complete task list for the installation.

Method signatures and docstrings:
- def Start(self, out_file, in_path, in_file='build.yaml'): Start parsing configuration files. Args: out_file: The location to store the compiled config data. in_path: The path to the root configuration file. in_file: The root configuration file name.
- def _Start(self, conf_path, conf_file): Pull and process a config file. Args: conf_path: The path to the config below root. conf_file: A named config file, normally build.yaml.
- def _MatchPin(self, pins): Check all pin entries for a mismatch. Pins can mismatch either by the matching setting being omitted or by matching an exclusion (!). Example: pins: ['os', ['win7', 'win8']] * Will match os = win7 or os = win8. * Will fail to match os = '2012r2'. * Will match model = 'vmware' (because model is not pinned). Example 2: pins: ['os', ['!win7']] * Will match os = win8 or os = 2012r2. * Will fail to match os = 'win7'. * Will match model = 'vmware' (because model is not pinned). Args: pins: a list of all applicable pin names and acceptable values Returns: True if this host passes all pin checks. False if the host fails a match.
- def _StoreControls(self, control, templates): Process all of the possible sub-sections of a main control section. Args: control: The data from this control subsection. templates: Any templates declared in the current config. Raises: UnknownActionError: Attempt to process an unknown command element.

<|skeleton|>
class ConfigBuilder:
    """Builds the complete task list for the installation."""

    def Start(self, out_file, in_path, in_file='build.yaml'):
        """Start parsing configuration files. Args: out_file: The location to store the compiled config data. in_path: The path to the root configuration file. in_file: The root configuration file name."""
        <|body_0|>

    def _Start(self, conf_path, conf_file):
        """Pull and process a config file. Args: conf_path: The path to the config below root. conf_file: A named config file, normally build.yaml."""
        <|body_1|>

    def _MatchPin(self, pins):
        """Check all pin entries for a mismatch. Pins can mismatch either by the matching setting being omitted or by matching an exclusion (!). Example: pins: ['os', ['win7', 'win8']] * Will match os = win7 or os = win8. * Will fail to match os = '2012r2'. * Will match model = 'vmware' (because model is not pinned). Example 2: pins: ['os', ['!win7']] * Will match os = win8 or os = 2012r2. * Will fail to match os = 'win7'. * Will match model = 'vmware' (because model is not pinned). Args: pins: a list of all applicable pin names and acceptable values Returns: True if this host passes all pin checks. False if the host fails a match."""
        <|body_2|>

    def _StoreControls(self, control, templates):
        """Process all of the possible sub-sections of a main control section. Args: control: The data from this control subsection. templates: Any templates declared in the current config. Raises: UnknownActionError: Attempt to process an unknown command element."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        self._task_list = []
        while True:
            try:
                self._Start(in_path, in_file)
                break
            except actions.ServerChangeEvent:
                in_path = ''
        try:
            files.Dump(out_file, self._task_list, mode='a')
        except files.Error as e:
            raise ConfigBuilderError() from e
<|end_body_0|>

<|body_start_1|>
        self._build_info.ActiveConfigPath(append=conf_path.rstrip('/'))
        try:
            path = download.PathCompile(self._build_info, file_name=conf_file)
            yaml_config = files.Read(path)
        except (files.Error, buildinfo.Error) as e:
            raise ConfigBuilderError() from e
        timer_start = 'start_{}_{}'.format(conf_path.rstrip('/'), conf_file)
        active_path = copy.deepcopy(self._build_info.ActiveConfigPath())
        self._task_list.append({'path': active_path, 'data': {'SetTimer': [timer_start]}})
        controls = yaml_config['controls']
        try:
            for control in controls:
                if 'pin' not in control or self._MatchPin(control['pin']):
                    self._StoreControls(control, yaml_config.get('templates'))
        finally:
            timer_stop = 'stop_{}_{}'.format(conf_path.rstrip('/'), conf_file)
            self._task_list.append({'path': active_path, 'data': {'SetTimer': [timer_stop]}})
        self._build_info.ActiveConfigPath(pop=True)
<|end_body_1|>

<|body_start_2|>
        for pin in pins:
            try:
                if not self._build_info.BuildPinMatch(pin, pins[pin]):
                    return False
            except buildinfo.Error as e:
                raise SysInfoError() from e
        return True
<|end_body_2|>

<|body_start_3|>
        for element in control:
            if element == 'pin':
                continue
            elif element == 'template':
                for template in control['template']:
                    self._StoreControls(templates[template], templates)
            elif element == 'include':
                for sub_inc in control['include']:
                    self._Start(conf_path=sub_inc[0], conf_file=sub_inc[1])
            elif element in _ALLOW_IN_CONTROL:
                if self._IsRealtimeAction(element, control[element]):
                    self._ProcessAction(element, control[element])
                else:
                    self._task_list.append({'path': copy.deepcopy(self._build_info.ActiveConfigPath()), 'data': {element: control[element]}})
            else:
                raise UnknownActionError(str(element))
<|end_body_3|>

Solution:
class ConfigBuilder:
    """Builds the complete task list for the installation."""

    def Start(self, out_file, in_path, in_file='build.yaml'):
        """Start parsing configuration files. Args: out_file: The location to store the compiled config data. in_path: The path to the root configuration file. in_file: The root configuration file name."""
        self._task_list = []
        while True:
            try:
                self._Start(in_path, in_file)
                break
            except actions.ServerChangeEvent:
                in_path = ''
        try:
            files.Dump(out_file, self._task_list, mode='a')
        except files.Error as e:
            raise ConfigBuilderError() from e

    def _Start(self, conf_path, conf_file):
        """Pull and process a config file. Args: conf_path: The path to the config below root. conf_file: A named config file, normally build.yaml."""
        self._build_info.ActiveConfigPath(append=conf_path.rstrip('/'))
        try:
            path = download.PathCompile(self._build_info, file_name=conf_file)
            yaml_config = files.Read(path)
        except (files.Error, buildinfo.Error) as e:
            raise ConfigBuilderError() from e
        timer_start = 'start_{}_{}'.format(conf_path.rstrip('/'), conf_file)
        active_path = copy.deepcopy(self._build_info.ActiveConfigPath())
        self._task_list.append({'path': active_path, 'data': {'SetTimer': [timer_start]}})
        controls = yaml_config['controls']
        try:
            for control in controls:
                if 'pin' not in control or self._MatchPin(control['pin']):
                    self._StoreControls(control, yaml_config.get('templates'))
        finally:
            timer_stop = 'stop_{}_{}'.format(conf_path.rstrip('/'), conf_file)
            self._task_list.append({'path': active_path, 'data': {'SetTimer': [timer_stop]}})
        self._build_info.ActiveConfigPath(pop=True)

    def _MatchPin(self, pins):
        """Check all pin entries for a mismatch. Pins can mismatch either by the matching setting being omitted or by matching an exclusion (!). Example: pins: ['os', ['win7', 'win8']] * Will match os = win7 or os = win8. * Will fail to match os = '2012r2'. * Will match model = 'vmware' (because model is not pinned). Example 2: pins: ['os', ['!win7']] * Will match os = win8 or os = 2012r2. * Will fail to match os = 'win7'. * Will match model = 'vmware' (because model is not pinned). Args: pins: a list of all applicable pin names and acceptable values Returns: True if this host passes all pin checks. False if the host fails a match."""
        for pin in pins:
            try:
                if not self._build_info.BuildPinMatch(pin, pins[pin]):
                    return False
            except buildinfo.Error as e:
                raise SysInfoError() from e
        return True

    def _StoreControls(self, control, templates):
        """Process all of the possible sub-sections of a main control section. Args: control: The data from this control subsection. templates: Any templates declared in the current config. Raises: UnknownActionError: Attempt to process an unknown command element."""
        for element in control:
            if element == 'pin':
                continue
            elif element == 'template':
                for template in control['template']:
                    self._StoreControls(templates[template], templates)
            elif element == 'include':
                for sub_inc in control['include']:
                    self._Start(conf_path=sub_inc[0], conf_file=sub_inc[1])
            elif element in _ALLOW_IN_CONTROL:
                if self._IsRealtimeAction(element, control[element]):
                    self._ProcessAction(element, control[element])
                else:
                    self._task_list.append({'path': copy.deepcopy(self._build_info.ActiveConfigPath()), 'data': {element: control[element]}})
            else:
                raise UnknownActionError(str(element))


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

Class description:
Responsible for parsing bug bucket logs

Method signatures and docstrings:
- def __init__(self, path): BugLogParser constructor @param path: The path to the bug log file @type path: Str
- def diff_log(self, other): Diffs a BugLogParser's bug list with this object's bug list @param other: The parser to compare to this one @type other: BugLogParser @return: True if the bug lists match @rtype : Bool
- def _parse(self): Parses the bug log to populate the bug list @return: None @rtype : None

Implement the Python class `BugLogParser` described below.

Class description:
Responsible for parsing bug bucket logs

Method signatures and docstrings:
- def __init__(self, path): BugLogParser constructor @param path: The path to the bug log file @type path: Str
- def diff_log(self, other): Diffs a BugLogParser's bug list with this object's bug list @param other: The parser to compare to this one @type other: BugLogParser @return: True if the bug lists match @rtype : Bool
- def _parse(self): Parses the bug log to populate the bug list @return: None @rtype : None

<|skeleton|>
class BugLogParser:
    """Responsible for parsing bug bucket logs"""

    def __init__(self, path):
        """BugLogParser constructor @param path: The path to the bug log file @type path: Str"""
        <|body_0|>

    def diff_log(self, other):
        """Diffs a BugLogParser's bug list with this object's bug list @param other: The parser to compare to this one @type other: BugLogParser @return: True if the bug lists match @rtype : Bool"""
        <|body_1|>

    def _parse(self):
        """Parses the bug log to populate the bug list @return: None @rtype : None"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__(path)
        self._bug_list = dict()
        self._parse()
<|end_body_0|>

<|body_start_1|>
        if self._bug_list != other._bug_list:
            print('Bug lists do not match.')
            return False
        return True
<|end_body_1|>

<|body_start_2|>
        with open(self._path, 'r') as file:
            try:
                line = file.readline()
                while line:
                    if line.startswith(BUG_START):
                        line = file.readline()
                        if line:
                            bug_type = line.split(' ', 1)[0]
                            if bug_type not in self._bug_list:
                                self._bug_list[bug_type] = []
                            reproduced = 'Bug was reproduced' in line
                            line = file.readline()
                            if line.startswith('Attempted'):
                                line = file.readline()
                            bug_hash = line.split(' ')[-1].rstrip()
                            line = file.readline()
                            seq = ParsedSequence([])
                            while line and (not line.startswith(BUG_START)):
                                seq += self._get_request(line)
                                line = file.readline()
                            self._bug_list[bug_type].append((seq, reproduced, bug_hash))
                    else:
                        line = file.readline()
            except Exception as err:
                print(f'Failed to read bug log. Log was not a complete test log.\n{err!s}')
                raise TestFailedException
<|end_body_2|>

Solution:
class BugLogParser:
    """Responsible for parsing bug bucket logs"""

    def __init__(self, path):
        """BugLogParser constructor @param path: The path to the bug log file @type path: Str"""
        super().__init__(path)
        self._bug_list = dict()
        self._parse()

    def diff_log(self, other):
        """Diffs a BugLogParser's bug list with this object's bug list @param other: The parser to compare to this one @type other: BugLogParser @return: True if the bug lists match @rtype : Bool"""
        if self._bug_list != other._bug_list:
            print('Bug lists do not match.')
            return False
        return True

    def _parse(self):
        """Parses the bug log to populate the bug list @return: None @rtype : None"""
        with open(self._path, 'r') as file:
            try:
                line = file.readline()
                while line:
                    if line.startswith(BUG_START):
                        line = file.readline()
                        if line:
                            bug_type = line.split(' ', 1)[0]
                            if bug_type not in self._bug_list:
                                self._bug_list[bug_type] = []
                            reproduced = 'Bug was reproduced' in line
                            line = file.readline()
                            if line.startswith('Attempted'):
                                line = file.readline()
                            bug_hash = line.split(' ')[-1].rstrip()
                            line = file.readline()
                            seq = ParsedSequence([])
                            while line and (not line.startswith(BUG_START)):
                                seq += self._get_request(line)
                                line = file.readline()
                            self._bug_list[bug_type].append((seq, reproduced, bug_hash))
                    else:
                        line = file.readline()
            except Exception as err:
                print(f'Failed to read bug log. Log was not a complete test log.\n{err!s}')
                raise TestFailedException


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

Class description:
An immutable pydantic model to validate FERC XBRL to SQLite settings. Args: ferc1_dbf_to_sqlite_settings: Settings for converting FERC 1 DBF data to SQLite. ferc1_xbrl_to_sqlite_settings: Settings for converting FERC 1 XBRL data to SQLite. other_xbrl_forms: List of non-FERC1 forms to convert from XBRL to SQLite.

Method signatures and docstrings:
- def default_load_all(cls, values): If no datasets are specified default to all. Args: values (Dict[str, BaseModel]): dataset settings. Returns: values (Dict[str, BaseModel]): dataset settings.
- def get_xbrl_dataset_settings(self, form_number: XbrlFormNumber) -> FercGenericXbrlToSqliteSettings: Return a list with all requested FERC XBRL to SQLite datasets. Args: form_number: Get settings by FERC form number.

Implement the Python class `FercToSqliteSettings` described below.

Class description:
An immutable pydantic model to validate FERC XBRL to SQLite settings. Args: ferc1_dbf_to_sqlite_settings: Settings for converting FERC 1 DBF data to SQLite. ferc1_xbrl_to_sqlite_settings: Settings for converting FERC 1 XBRL data to SQLite. other_xbrl_forms: List of non-FERC1 forms to convert from XBRL to SQLite.

Method signatures and docstrings:
- def default_load_all(cls, values): If no datasets are specified default to all. Args: values (Dict[str, BaseModel]): dataset settings. Returns: values (Dict[str, BaseModel]): dataset settings.
- def get_xbrl_dataset_settings(self, form_number: XbrlFormNumber) -> FercGenericXbrlToSqliteSettings: Return a list with all requested FERC XBRL to SQLite datasets. Args: form_number: Get settings by FERC form number.

<|skeleton|>
class FercToSqliteSettings:
    """An immutable pydantic model to validate FERC XBRL to SQLite settings. Args: ferc1_dbf_to_sqlite_settings: Settings for converting FERC 1 DBF data to SQLite. ferc1_xbrl_to_sqlite_settings: Settings for converting FERC 1 XBRL data to SQLite. other_xbrl_forms: List of non-FERC1 forms to convert from XBRL to SQLite."""

    def default_load_all(cls, values):
        """If no datasets are specified default to all. Args: values (Dict[str, BaseModel]): dataset settings. Returns: values (Dict[str, BaseModel]): dataset settings."""
        <|body_0|>

    def get_xbrl_dataset_settings(self, form_number: XbrlFormNumber) -> FercGenericXbrlToSqliteSettings:
        """Return a list with all requested FERC XBRL to SQLite datasets. Args: form_number: Get settings by FERC form number."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if not any(values.values()):
            values['ferc1_dbf_to_sqlite_settings'] = Ferc1DbfToSqliteSettings()
            values['ferc1_xbrl_to_sqlite_settings'] = Ferc1XbrlToSqliteSettings()
            values['ferc2_dbf_to_sqlite_settings'] = Ferc2DbfToSqliteSettings()
            values['ferc2_xbrl_to_sqlite_settings'] = Ferc2XbrlToSqliteSettings()
            values['ferc6_dbf_to_sqlite_settings'] = Ferc6DbfToSqliteSettings()
            values['ferc6_xbrl_to_sqlite_settings'] = Ferc6XbrlToSqliteSettings()
            values['ferc60_dbf_to_sqlite_settings'] = Ferc60DbfToSqliteSettings()
            values['ferc60_xbrl_to_sqlite_settings'] = Ferc60XbrlToSqliteSettings()
            values['ferc714_xbrl_to_sqlite_settings'] = Ferc714XbrlToSqliteSettings()
        return values
<|end_body_0|>

<|body_start_1|>
        match form_number:
            case XbrlFormNumber.FORM1:
                settings = self.ferc1_xbrl_to_sqlite_settings
            case XbrlFormNumber.FORM2:
                settings = self.ferc2_xbrl_to_sqlite_settings
            case XbrlFormNumber.FORM6:
                settings = self.ferc6_xbrl_to_sqlite_settings
            case XbrlFormNumber.FORM60:
                settings = self.ferc60_xbrl_to_sqlite_settings
            case XbrlFormNumber.FORM714:
                settings = self.ferc714_xbrl_to_sqlite_settings
        return settings
<|end_body_1|>

Solution:
class FercToSqliteSettings:
    """An immutable pydantic model to validate FERC XBRL to SQLite settings. Args: ferc1_dbf_to_sqlite_settings: Settings for converting FERC 1 DBF data to SQLite. ferc1_xbrl_to_sqlite_settings: Settings for converting FERC 1 XBRL data to SQLite. other_xbrl_forms: List of non-FERC1 forms to convert from XBRL to SQLite."""

    def default_load_all(cls, values):
        """If no datasets are specified default to all. Args: values (Dict[str, BaseModel]): dataset settings. Returns: values (Dict[str, BaseModel]): dataset settings."""
        if not any(values.values()):
            values['ferc1_dbf_to_sqlite_settings'] = Ferc1DbfToSqliteSettings()
            values['ferc1_xbrl_to_sqlite_settings'] = Ferc1XbrlToSqliteSettings()
            values['ferc2_dbf_to_sqlite_settings'] = Ferc2DbfToSqliteSettings()
            values['ferc2_xbrl_to_sqlite_settings'] = Ferc2XbrlToSqliteSettings()
            values['ferc6_dbf_to_sqlite_settings'] = Ferc6DbfToSqliteSettings()
            values['ferc6_xbrl_to_sqlite_settings'] = Ferc6XbrlToSqliteSettings()
            values['ferc60_dbf_to_sqlite_settings'] = Ferc60DbfToSqliteSettings()
            values['ferc60_xbrl_to_sqlite_settings'] = Ferc60XbrlToSqliteSettings()
            values['ferc714_xbrl_to_sqlite_settings'] = Ferc714XbrlToSqliteSettings()
        return values

    def get_xbrl_dataset_settings(self, form_number: XbrlFormNumber) -> FercGenericXbrlToSqliteSettings:
        """Return a list with all requested FERC XBRL to SQLite datasets. Args: form_number: Get settings by FERC form number."""
        match form_number:
            case XbrlFormNumber.FORM1:
                settings = self.ferc1_xbrl_to_sqlite_settings
            case XbrlFormNumber.FORM2:
                settings = self.ferc2_xbrl_to_sqlite_settings
            case XbrlFormNumber.FORM6:
                settings = self.ferc6_xbrl_to_sqlite_settings
            case XbrlFormNumber.FORM60:
                settings = self.ferc60_xbrl_to_sqlite_settings
            case XbrlFormNumber.FORM714:
                settings = self.ferc714_xbrl_to_sqlite_settings
        return settings


list

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

Class description:
This view is the endpoint for retrieving the list of all ingests.

Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API
- def list(self, request): Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user
- def list_impl(self, request): Retrieves the list of all ingests and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user

Implement the Python class `IngestsView` described below.

Class description:
This view is the endpoint for retrieving the list of all ingests.

Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API
- def list(self, request): Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user
- def list_impl(self, request): Retrieves the list of all ingests and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user

<|skeleton|>
class IngestsView:
    """This view is the endpoint for retrieving the list of all ingests."""

    def get_serializer_class(self):
        """Returns the appropriate serializer based off the requests version of the REST API"""
        <|body_0|>

    def list(self, request):
        """Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user"""
        <|body_1|>

    def list_impl(self, request):
        """Retrieves the list of all ingests and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        if self.request.version == 'v6':
            return IngestSerializerV6
        elif self.request.version == 'v7':
            return IngestSerializerV6
<|end_body_0|>

<|body_start_1|>
        if request.version == 'v6':
            return self.list_impl(request)
        elif request.version == 'v7':
            return self.list_impl(request)
        raise Http404()
<|end_body_1|>

<|body_start_2|>
        started = rest_util.parse_timestamp(request, 'started', required=False)
        ended = rest_util.parse_timestamp(request, 'ended', required=False)
        rest_util.check_time_range(started, ended)
        ingest_statuses = rest_util.parse_string_list(request, 'status', required=False)
        strike_ids = rest_util.parse_int_list(request, 'strike_id', required=False)
        scan_ids = rest_util.parse_int_list(request, 'scan_id', required=False)
        file_name = rest_util.parse_string(request, 'file_name', required=False)
        order = rest_util.parse_string_list(request, 'order', required=False)
        ingests = Ingest.objects.get_ingests(started=started, ended=ended, statuses=ingest_statuses, scan_ids=scan_ids, strike_ids=strike_ids, file_name=file_name, order=order)
        page = self.paginate_queryset(ingests)
        serializer = self.get_serializer(page, many=True)
        return self.get_paginated_response(serializer.data)
<|end_body_2|>

Solution:
class IngestsView:
    """This view is the endpoint for retrieving the list of all ingests."""

    def get_serializer_class(self):
        """Returns the appropriate serializer based off the requests version of the REST API"""
        if self.request.version == 'v6':
            return IngestSerializerV6
        elif self.request.version == 'v7':
            return IngestSerializerV6

    def list(self, request):
        """Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user"""
        if request.version == 'v6':
            return self.list_impl(request)
        elif request.version == 'v7':
            return self.list_impl(request)
        raise Http404()

    def list_impl(self, request):
        """Retrieves the list of all ingests and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user"""
        started = rest_util.parse_timestamp(request, 'started', required=False)
        ended = rest_util.parse_timestamp(request, 'ended', required=False)
        rest_util.check_time_range(started, ended)
        ingest_statuses = rest_util.parse_string_list(request, 'status', required=False)
        strike_ids = rest_util.parse_int_list(request, 'strike_id', required=False)
        scan_ids = rest_util.parse_int_list(request, 'scan_id', required=False)
        file_name = rest_util.parse_string(request, 'file_name', required=False)
        order = rest_util.parse_string_list(request, 'order', required=False)
        ingests = Ingest.objects.get_ingests(started=started, ended=ended, statuses=ingest_statuses, scan_ids=scan_ids, strike_ids=strike_ids, file_name=file_name, order=order)
        page = self.paginate_queryset(ingests)
        serializer = self.get_serializer(page, many=True)
        return self.get_paginated_response(serializer.data)


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

Class description:
Convenience class for retrieving SavedWorkspace objects

Method signatures and docstrings:
- def __init__(self, **kwargs): Various keyword options: app_domain - as specified in configurations.models.DOMAIN_LIST session_key - django session key, stored in SavedWorkspace.session_key user - raven_auth.models.User data_source_type_id - workspaces.models.DataSourceType.id workspace_id - SavedWorkspace.id
- def list_workspaces_by_request(request, as_dict=False, **kwargs): Retrieve a list of all workspaces
- def list_workspaces_by_user(auth_user, as_dict=False, **kwargs): Retrieve a of workspaces for a user
- def get_by_id_and_request(ws_id, request, as_dict=False): Get SavedWorkspace by id
- def get_by_user_and_id(auth_user, ws_id, as_dict=False): Get SavedWorkspace by id

Implement the Python class `WorkspaceRetriever` described below.

Class description:
Convenience class for retrieving SavedWorkspace objects

Method signatures and docstrings:
- def __init__(self, **kwargs): Various keyword options: app_domain - as specified in configurations.models.DOMAIN_LIST session_key - django session key, stored in SavedWorkspace.session_key user - raven_auth.models.User data_source_type_id - workspaces.models.DataSourceType.id workspace_id - SavedWorkspace.id
- def list_workspaces_by_request(request, as_dict=False, **kwargs): Retrieve a list of all workspaces
- def list_workspaces_by_user(auth_user, as_dict=False, **kwargs): Retrieve a of workspaces for a user
- def get_by_id_and_request(ws_id, request, as_dict=False): Get SavedWorkspace by id
- def get_by_user_and_id(auth_user, ws_id, as_dict=False): Get SavedWorkspace by id

<|skeleton|>
class WorkspaceRetriever:
    """Convenience class for retrieving SavedWorkspace objects"""

    def __init__(self, **kwargs):
        """Various keyword options: app_domain - as specified in configurations.models.DOMAIN_LIST session_key - django session key, stored in SavedWorkspace.session_key user - raven_auth.models.User data_source_type_id - workspaces.models.DataSourceType.id workspace_id - SavedWorkspace.id"""
        <|body_0|>

    def list_workspaces_by_request(request, as_dict=False, **kwargs):
        """Retrieve a list of all workspaces"""
        <|body_1|>

    def list_workspaces_by_user(auth_user, as_dict=False, **kwargs):
        """Retrieve a of workspaces for a user"""
        <|body_2|>

    def get_by_id_and_request(ws_id, request, as_dict=False):
        """Get SavedWorkspace by id"""
        <|body_3|>

    def get_by_user_and_id(auth_user, ws_id, as_dict=False):
        """Get SavedWorkspace by id"""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        self.app_domain = kwargs.get('app_domain')
        self.session_key = kwargs.get('session_key')
        self.user = kwargs.get('user')
        self.data_source_type_id = kwargs.get('data_source_type_id')
        self.workspace_id = kwargs.get('workspace_id')
<|end_body_0|>

<|body_start_1|>
        success, user_or_err = get_authenticated_user(request)
        if not success:
            return (False, user_or_err)
        return WorkspaceRetriever.list_workspaces_by_user(user_or_err, as_dict, **kwargs)
<|end_body_1|>

<|body_start_2|>
        if not auth_user:
            return (False, ERR_AUTH_USER_IS_NONE)
        session_key = kwargs.get(KW_SESSION_KEY, None)
        ws_list = workspace_queryset_base().filter(user=auth_user)
        if not as_dict:
            return (True, ws_list)
        fmt_list = []
        for workspace in ws_list:
            ws_dict = workspace.as_dict_lite()
            ws_dict['is_current_session'] = bool(session_key and session_key == workspace.session_key)
            fmt_list.append(ws_dict)
        return (True, fmt_list)
<|end_body_2|>

<|body_start_3|>
        if ws_id is None:
            return (False, ERR_WORKSPACE_ID_IS_NONE)
        if request is None:
            return (False, ERR_REQUEST_OBJ_IS_NONE)
        success, user_or_err = get_authenticated_user(request)
        if not success:
            return (False, user_or_err)
        return WorkspaceRetriever.get_by_user_and_id(user_or_err, ws_id, as_dict)
<|end_body_3|>

<|body_start_4|>
        if not auth_user:
            return (False, ERR_AUTH_USER_IS_NONE)
        if not ws_id:
            return (False, ERR_WORKSPACE_ID_IS_NONE)
        qparams = dict(id=ws_id)
        if auth_user.is_active and auth_user.is_superuser:
            workspace = workspace_queryset_base().filter(**qparams).first()
        else:
            qparams['user'] = auth_user
            workspace = workspace_queryset_base().filter(**qparams).first()
        if workspace:
            if as_dict:
                return (True, workspace.as_dict())
            return (True, workspace)
        return (False, 'Workspace not found with user: [%s] and  id: [%s]' % (auth_user, ws_id))
<|end_body_4|>

Solution:
class WorkspaceRetriever:
    """Convenience class for retrieving SavedWorkspace objects"""

    def __init__(self, **kwargs):
        """Various keyword options: app_domain - as specified in configurations.models.DOMAIN_LIST session_key - django session key, stored in SavedWorkspace.session_key user - raven_auth.models.User data_source_type_id - workspaces.models.DataSourceType.id workspace_id - SavedWorkspace.id"""
        self.app_domain = kwargs.get('app_domain')
        self.session_key = kwargs.get('session_key')
        self.user = kwargs.get('user')
        self.data_source_type_id = kwargs.get('data_source_type_id')
        self.workspace_id = kwargs.get('workspace_id')

    def list_workspaces_by_request(request, as_dict=False, **kwargs):
        """Retrieve a list of all workspaces"""
        success, user_or_err = get_authenticated_user(request)
        if not success:
            return (False, user_or_err)
        return WorkspaceRetriever.list_workspaces_by_user(user_or_err, as_dict, **kwargs)

    def list_workspaces_by_user(auth_user, as_dict=False, **kwargs):
        """Retrieve a of workspaces for a user"""
        if not auth_user:
            return (False, ERR_AUTH_USER_IS_NONE)
        session_key = kwargs.get(KW_SESSION_KEY, None)
        ws_list = workspace_queryset_base().filter(user=auth_user)
        if not as_dict:
            return (True, ws_list)
        fmt_list = []
        for workspace in ws_list:
            ws_dict = workspace.as_dict_lite()
            ws_dict['is_current_session'] = bool(session_key and session_key == workspace.session_key)
            fmt_list.append(ws_dict)
        return (True, fmt_list)

    def get_by_id_and_request(ws_id, request, as_dict=False):
        """Get SavedWorkspace by id"""
        if ws_id is None:
            return (False, ERR_WORKSPACE_ID_IS_NONE)
        if request is None:
            return (False, ERR_REQUEST_OBJ_IS_NONE)
        success, user_or_err = get_authenticated_user(request)
        if not success:
            return (False, user_or_err)
        return WorkspaceRetriever.get_by_user_and_id(user_or_err, ws_id, as_dict)

    def get_by_user_and_id(auth_user, ws_id, as_dict=False):
        """Get SavedWorkspace by id"""
        if not auth_user:
            return (False, ERR_AUTH_USER_IS_NONE)
        if not ws_id:
            return (False, ERR_WORKSPACE_ID_IS_NONE)
        qparams = dict(id=ws_id)
        if auth_user.is_active and auth_user.is_superuser:
            workspace = workspace_queryset_base().filter(**qparams).first()
        else:
            qparams['user'] = auth_user
            workspace = workspace_queryset_base().filter(**qparams).first()
        if workspace:
            if as_dict:
                return (True, workspace.as_dict())
            return (True, workspace)
        return (False, 'Workspace not found with user: [%s] and  id: [%s]' % (auth_user, ws_id))


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

Class description:
Users may see the set of votes on a feature, and add their own, if allowed.

Method signatures and docstrings:
- def do_get(self, **kwargs) -> dict[str, list[dict[str, Any]]]: Return a list of all vote values for a given feature.
- def do_post(self, **kwargs) -> dict[str, str]: Set a user's vote value for the specified feature and gate.
- def require_permissions(self, user, feature, gate, new_state): Abort the request if the user lacks permission to set this vote.

Implement the Python class `VotesAPI` described below.

Class description:
Users may see the set of votes on a feature, and add their own, if allowed.

Method signatures and docstrings:
- def do_get(self, **kwargs) -> dict[str, list[dict[str, Any]]]: Return a list of all vote values for a given feature.
- def do_post(self, **kwargs) -> dict[str, str]: Set a user's vote value for the specified feature and gate.
- def require_permissions(self, user, feature, gate, new_state): Abort the request if the user lacks permission to set this vote.

<|skeleton|>
class VotesAPI:
    """Users may see the set of votes on a feature, and add their own, if allowed."""

    def do_get(self, **kwargs) -> dict[str, list[dict[str, Any]]]:
        """Return a list of all vote values for a given feature."""
        <|body_0|>

    def do_post(self, **kwargs) -> dict[str, str]:
        """Set a user's vote value for the specified feature and gate."""
        <|body_1|>

    def require_permissions(self, user, feature, gate, new_state):
        """Abort the request if the user lacks permission to set this vote."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        feature_id = kwargs['feature_id']
        gate_id = kwargs.get('gate_id', None)
        votes = Vote.get_votes(feature_id=feature_id, gate_id=gate_id)
        dicts = [converters.vote_value_to_json_dict(v) for v in votes]
        return {'votes': dicts}
<|end_body_0|>

<|body_start_1|>
        feature_id = kwargs['feature_id']
        gate_id = kwargs['gate_id']
        feature = self.get_specified_feature(feature_id=feature_id)
        new_state = self.get_int_param('state', validator=Vote.is_valid_state)
        user = self.get_current_user(required=True)
        gate = Gate.get_by_id(gate_id)
        if not gate:
            self.abort(404, msg='Gate not found')
        if gate.feature_id != feature_id:
            self.abort(400, msg='Mismatched feature and gate')
        old_state = gate.state
        self.require_permissions(user, feature, gate, new_state)
        approval_defs.set_vote(feature_id, None, new_state, user.email(), gate_id)
        if new_state == Vote.REVIEW_REQUESTED:
            notifier_helpers.notify_approvers_of_reviews(feature, gate)
        else:
            notifier_helpers.notify_subscribers_of_vote_changes(feature, gate, user.email(), new_state, old_state)
        return {'message': 'Done'}
<|end_body_1|>

<|body_start_2|>
        is_requesting_review = new_state == Vote.REVIEW_REQUESTED
        is_editor = permissions.can_edit_feature(user, feature.key.integer_id())
        approvers = approval_defs.get_approvers(gate.gate_type)
        is_approver = permissions.can_approve_feature(user, feature, approvers)
        if is_requesting_review and is_editor:
            return
        if is_approver:
            return
        if is_requesting_review:
            self.abort(403, msg='User may not request a review')
        else:
            self.abort(403, msg='User is not an approver')
<|end_body_2|>

Solution:
class VotesAPI:
    """Users may see the set of votes on a feature, and add their own, if allowed."""

    def do_get(self, **kwargs) -> dict[str, list[dict[str, Any]]]:
        """Return a list of all vote values for a given feature."""
        feature_id = kwargs['feature_id']
        gate_id = kwargs.get('gate_id', None)
        votes = Vote.get_votes(feature_id=feature_id, gate_id=gate_id)
        dicts = [converters.vote_value_to_json_dict(v) for v in votes]
        return {'votes': dicts}

    def do_post(self, **kwargs) -> dict[str, str]:
        """Set a user's vote value for the specified feature and gate."""
        feature_id = kwargs['feature_id']
        gate_id = kwargs['gate_id']
        feature = self.get_specified_feature(feature_id=feature_id)
        new_state = self.get_int_param('state', validator=Vote.is_valid_state)
        user = self.get_current_user(required=True)
        gate = Gate.get_by_id(gate_id)
        if not gate:
            self.abort(404, msg='Gate not found')
        if gate.feature_id != feature_id:
            self.abort(400, msg='Mismatched feature and gate')
        old_state = gate.state
        self.require_permissions(user, feature, gate, new_state)
        approval_defs.set_vote(feature_id, None, new_state, user.email(), gate_id)
        if new_state == Vote.REVIEW_REQUESTED:
            notifier_helpers.notify_approvers_of_reviews(feature, gate)
        else:
            notifier_helpers.notify_subscribers_of_vote_changes(feature, gate, user.email(), new_state, old_state)
        return {'message': 'Done'}

    def require_permissions(self, user, feature, gate, new_state):
        """Abort the request if the user lacks permission to set this vote."""
        is_requesting_review = new_state == Vote.REVIEW_REQUESTED
        is_editor = permissions.can_edit_feature(user, feature.key.integer_id())
        approvers = approval_defs.get_approvers(gate.gate_type)
        is_approver = permissions.can_approve_feature(user, feature, approvers)
        if is_requesting_review and is_editor:
            return
        if is_approver:
            return
        if is_requesting_review:
            self.abort(403, msg='User may not request a review')
        else:
            self.abort(403, msg='User is not an approver')


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

Class description:
View to create a new "share" user in the workflow.

Method signatures and docstrings:
- def get_form_kwargs(self) -> Dict: Store workflow and 'request.user' in kwargs
- def form_valid(self, form) -> http.JsonResponse: Store the new shared user

Implement the Python class `WorkflowShareCreateView` described below.

Class description:
View to create a new "share" user in the workflow.

Method signatures and docstrings:
- def get_form_kwargs(self) -> Dict: Store workflow and 'request.user' in kwargs
- def form_valid(self, form) -> http.JsonResponse: Store the new shared user

<|skeleton|>
class WorkflowShareCreateView:
    """View to create a new "share" user in the workflow."""

    def get_form_kwargs(self) -> Dict:
        """Store workflow and 'request.user' in kwargs"""
        <|body_0|>

    def form_valid(self, form) -> http.JsonResponse:
        """Store the new shared user"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        form_kwargs = super().get_form_kwargs()
        form_kwargs['workflow'] = self.workflow
        form_kwargs['user'] = self.request.user
        return form_kwargs
<|end_body_0|>

<|body_start_1|>
        self.workflow.shared.add(form.user_obj)
        self.workflow.save()
        self.workflow.log(self.request.user, models.Log.WORKFLOW_SHARE_ADD, share_email=form.user_obj.email)
        return http.JsonResponse({'html_redirect': ''})
<|end_body_1|>

Solution:
class WorkflowShareCreateView:
    """View to create a new "share" user in the workflow."""

    def get_form_kwargs(self) -> Dict:
        """Store workflow and 'request.user' in kwargs"""
        form_kwargs = super().get_form_kwargs()
        form_kwargs['workflow'] = self.workflow
        form_kwargs['user'] = self.request.user
        return form_kwargs

    def form_valid(self, form) -> http.JsonResponse:
        """Store the new shared user"""
        self.workflow.shared.add(form.user_obj)
        self.workflow.save()
        self.workflow.log(self.request.user, models.Log.WORKFLOW_SHARE_ADD, share_email=form.user_obj.email)
        return http.JsonResponse({'html_redirect': ''})


deserialize

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

Class description:
Implement the Codec class.

Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: TreeNode

Implement the Python class `Codec` described below.

Class description:
Implement the Codec class.

Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: TreeNode

<|skeleton|>
class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
        <|body_0|>

    def deserialize(self, data):
        """Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        ans = ''
        stack = [root]
        while stack:
            node = stack.pop()
            if not node:
                ans += '^$'
            else:
                ans += '^{}('.format(node.val)
                stack.append(node.right)
                stack.append(node.left)
        return ans
<|end_body_0|>

<|body_start_1|>
        def parse(i):
            assert data[i] == '^'
            i += 1
            if data[i] == '$':
                return (None, i + 1)
            j = i
            while data[i] != '(':
                i += 1
            val = int(data[j:i])
            i += 1
            left, i = parse(i)
            right, i = parse(i)
            root = TreeNode(val)
            root.left = left
            root.right = right
            return (root, i)
        return parse(0)[0]
<|end_body_1|>

Solution:
class Codec:
    def serialize(self, root):
        """Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
        ans = ''
        stack = [root]
        while stack:
            node = stack.pop()
            if not node:
                ans += '^$'
            else:
                ans += '^{}('.format(node.val)
                stack.append(node.right)
                stack.append(node.left)
        return ans

    def deserialize(self, data):
        """Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
        def parse(i):
            assert data[i] == '^'
            i += 1
            if data[i] == '$':
                return (None, i + 1)
            j = i
            while data[i] != '(':
                i += 1
            val = int(data[j:i])
            i += 1
            left, i = parse(i)
            right, i = parse(i)
            root = TreeNode(val)
            root.left = left
            root.right = right
            return (root, i)
        return parse(0)[0]


signup

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

Class description:
Customize django-allauth SignupForm to include tags.

Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a pretty crispy form.
- def signup(self, request, user): Provide custom signup step (saving tags).

Implement the Python class `CustomSignupForm` described below.

Class description:
Customize django-allauth SignupForm to include tags.

Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a pretty crispy form.
- def signup(self, request, user): Provide custom signup step (saving tags).

<|skeleton|>
class CustomSignupForm:
    """Customize django-allauth SignupForm to include tags."""

    def __init__(self, *args, **kwargs):
        """Create a pretty crispy form."""
        <|body_0|>

    def signup(self, request, user):
        """Provide custom signup step (saving tags)."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        logger.debug('Args: %s; kwargs: %s', args, kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'signup_form'
        self.helper.form_class = 'signup'
        self.helper.layout = Layout(Fieldset('Account Details', 'username', 'email', 'password1', 'password2'), Fieldset('My Profile', HTML('\n
You must select at least one tag.  These tags\n                     control which job postings will be shown to you and which\n                     will not.  Only those jobs that match these tags will be\n                     visible to you.  This can be changed later.
\n                '), 'tags'), ButtonHolder(Submit('submit', 'Sign Up »')))
        super(CustomSignupForm, self).__init__(*args, **kwargs)
<|end_body_0|>

<|body_start_1|>
        tags = self.cleaned_data['tags']
        logger.info('User Signup: %s; request: %s; tags: %s', user, request, tags)
        user.profile.tags.add(*self.cleaned_data['tags'])
        user.profile.save()
        create_userjobs_for(user)
<|end_body_1|>

Solution:
class CustomSignupForm:
    """Customize django-allauth SignupForm to include tags."""

    def __init__(self, *args, **kwargs):
        """Create a pretty crispy form."""
        logger.debug('Args: %s; kwargs: %s', args, kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'signup_form'
        self.helper.form_class = 'signup'
        self.helper.layout = Layout(Fieldset('Account Details', 'username', 'email', 'password1', 'password2'), Fieldset('My Profile', HTML('\n
You must select at least one tag.  These tags\n                     control which job postings will be shown to you and which\n                     will not.  Only those jobs that match these tags will be\n                     visible to you.  This can be changed later.
\n                '), 'tags'), ButtonHolder(Submit('submit', 'Sign Up »')))
        super(CustomSignupForm, self).__init__(*args, **kwargs)

    def signup(self, request, user):
        """Provide custom signup step (saving tags)."""
        tags = self.cleaned_data['tags']
        logger.info('User Signup: %s; request: %s; tags: %s', user, request, tags)
        user.profile.tags.add(*self.cleaned_data['tags'])
        user.profile.save()
        create_userjobs_for(user)


hasCycle

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def hasCycle(self, head): :type head: ListNode :rtype: bool https://leetcode.com/problems/linked-list-cycle/solution/ 提供了两种解决方法,hash 和两个快慢指针
- def hasCycle1(self, head): :type head: ListNode :rtype: bool
- def detectCycle(self, head): :type head: ListNode :rtype: ListNode
- def detectCycle1(self, head): :type head: ListNode :rtype: ListNode
- def detectCycle2(self, head): :type head: ListNode :rtype: ListNode

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def hasCycle(self, head): :type head: ListNode :rtype: bool https://leetcode.com/problems/linked-list-cycle/solution/ 提供了两种解决方法,hash 和两个快慢指针
- def hasCycle1(self, head): :type head: ListNode :rtype: bool
- def detectCycle(self, head): :type head: ListNode :rtype: ListNode
- def detectCycle1(self, head): :type head: ListNode :rtype: ListNode
- def detectCycle2(self, head): :type head: ListNode :rtype: ListNode

<|skeleton|>
class Solution:

    def hasCycle(self, head):
        """:type head: ListNode :rtype: bool https://leetcode.com/problems/linked-list-cycle/solution/ 提供了两种解决方法,hash 和两个快慢指针"""
        <|body_0|>

    def hasCycle1(self, head):
        """:type head: ListNode :rtype: bool"""
        <|body_1|>

    def detectCycle(self, head):
        """:type head: ListNode :rtype: ListNode"""
        <|body_2|>

    def detectCycle1(self, head):
        """:type head: ListNode :rtype: ListNode"""
        <|body_3|>

    def detectCycle2(self, head):
        """:type head: ListNode :rtype: ListNode"""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        fast = slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                return True
        return False
<|end_body_0|>

<|body_start_1|>
        if not head:
            return False
        if not head.next:
            return False
        node_set = set()
        current = head
        while current:
            if current not in node_set:
                node_set.add(current)
                current = current.next
            else:
                return True
        return False
<|end_body_1|>

<|body_start_2|>
        if not (head and head.next):
            return
        node_set = set()
        current = head
        while current:
            if current not in node_set:
                node_set.add(current)
                current = current.next
            else:
                return current
        return
<|end_body_2|>

<|body_start_3|>
        if not (head and head.next):
            return
        fast = slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                break
        if not fast or not fast.next:
            return
        meet_point = slow
        fast = head
        while fast != meet_point:
            fast = fast.next
            meet_point = meet_point.next
        return meet_point
<|end_body_3|>

<|body_start_4|>
        if head is None or head.next is None:
            return
        fast = slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                fast = head
                while fast != slow:
                    fast = fast.next
                    slow = slow.next
                return slow
        return
<|end_body_4|>

Solution:
class Solution:
    def hasCycle(self, head):
        """:type head: ListNode :rtype: bool https://leetcode.com/problems/linked-list-cycle/solution/ 提供了两种解决方法,hash 和两个快慢指针"""
        fast = slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                return True
        return False

    def hasCycle1(self, head):
        """:type head: ListNode :rtype: bool"""
        if not head:
            return False
        if not head.next:
            return False
        node_set = set()
        current = head
        while current:
            if current not in node_set:
                node_set.add(current)
                current = current.next
            else:
                return True
        return False

    def detectCycle(self, head):
        """:type head: ListNode :rtype: ListNode"""
        if not (head and head.next):
            return
        node_set = set()
        current = head
        while current:
            if current not in node_set:
                node_set.add(current)
                current = current.next
            else:
                return current
        return

    def detectCycle1(self, head):
        """:type head: ListNode :rtype: ListNode"""
        if not (head and head.next):
            return
        fast = slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                break
        if not fast or not fast.next:
            return
        meet_point = slow
        fast = head
        while fast != meet_point:
            fast = fast.next
            meet_point = meet_point.next
        return meet_point

    def detectCycle2(self, head):
        """:type head: ListNode :rtype: ListNode"""
        if head is None or head.next is None:
            return
        fast = slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                fast = head
                while fast != slow:
                    fast = fast.next
                    slow = slow.next
                return slow
        return


get

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

Class description:
Implement the Config class.

Method signatures and docstrings:
- def __init__(self, cfg='config.conf'): @param file_name: file name without extension. @param cfg: configuration file path.
- def get(self, section): Get option. @param section: section to fetch. @return: option value.

Implement the Python class `Config` described below.

Class description:
Implement the Config class.

Method signatures and docstrings:
- def __init__(self, cfg='config.conf'): @param file_name: file name without extension. @param cfg: configuration file path.
- def get(self, section): Get option. @param section: section to fetch. @return: option value.

<|skeleton|>
class Config:

    def __init__(self, cfg='config.conf'):
        """@param file_name: file name without extension. @param cfg: configuration file path."""
        <|body_0|>

    def get(self, section):
        """Get option. @param section: section to fetch. @return: option value."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        config = ConfigParser.ConfigParser()
        config.read(cfg)
        for section in config.sections():
            setattr(self, section, Dictionary())
            for name, raw_value in config.items(section):
                try:
                    if config.get(section, name) in ['0', '1']:
                        raise ValueError
                    value = config.getboolean(section, name)
                except ValueError:
                    try:
                        value = config.getint(section, name)
                    except ValueError:
                        value = config.get(section, name)
                setattr(getattr(self, section), name, value)
<|end_body_0|>

<|body_start_1|>
        try:
            return getattr(self, section)
        except AttributeError as e:
            raise OperationalError('Option %s is not found in configuration, error: %s' % (section, e))
<|end_body_1|>

Solution:
class Config:
    def __init__(self, cfg='config.conf'):
        """@param file_name: file name without extension. @param cfg: configuration file path."""
        config = ConfigParser.ConfigParser()
        config.read(cfg)
        for section in config.sections():
            setattr(self, section, Dictionary())
            for name, raw_value in config.items(section):
                try:
                    if config.get(section, name) in ['0', '1']:
                        raise ValueError
                    value = config.getboolean(section, name)
                except ValueError:
                    try:
                        value = config.getint(section, name)
                    except ValueError:
                        value = config.get(section, name)
                setattr(getattr(self, section), name, value)

    def get(self, section):
        """Get option. @param section: section to fetch. @return: option value."""
        try:
            return getattr(self, section)
        except AttributeError as e:
            raise OperationalError('Option %s is not found in configuration, error: %s' % (section, e))


trap

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def trap(self, height): 08/06/2018 02:27
- def trap(self, height: List[int]) -> int: Time complexity: O(n) Space complexity: O(n)
- def trap(self, height: List[int]) -> int: Time complexity: O(n) Space complexity: O(1)
- def _trap(self, height: List[int]) -> int: 10/16/2022 16:16 Time complexity: O(n) Space complexity: O(n)

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def trap(self, height): 08/06/2018 02:27
- def trap(self, height: List[int]) -> int: Time complexity: O(n) Space complexity: O(n)
- def trap(self, height: List[int]) -> int: Time complexity: O(n) Space complexity: O(1)
- def _trap(self, height: List[int]) -> int: 10/16/2022 16:16 Time complexity: O(n) Space complexity: O(n)

<|skeleton|>
class Solution:

    def trap(self, height):
        """08/06/2018 02:27"""
        <|body_0|>

    def trap(self, height: List[int]) -> int:
        """Time complexity: O(n) Space complexity: O(n)"""
        <|body_1|>

    def trap(self, height: List[int]) -> int:
        """Time complexity: O(n) Space complexity: O(1)"""
        <|body_2|>

    def _trap(self, height: List[int]) -> int:
        """10/16/2022 16:16 Time complexity: O(n) Space complexity: O(n)"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        if not height:
            return 0
        max_right = [height[-1]]
        rheight = reversed(height)
        next(rheight)
        for i, h in enumerate(rheight):
            max_right.append(max(max_right[i], h))
        max_right.reverse()
        max_left = [height[0]]
        for i, h in enumerate(height[1:]):
            max_left.append(max(max_left[i], h))
        s = 0
        for h, l, r in zip(height, max_left, max_right):
            s += min(l, r) - h
        return s
<|end_body_0|>

<|body_start_1|>
        height = [0] + height + [0]
        n = len(height)
        left_highest = [0]
        for i in range(1, len(height)):
            left_highest.append(max(left_highest[i - 1], height[i - 1]))
        right_highest = [0]
        for i in range(1, len(height)):
            right_highest.append(max(right_highest[i - 1], height[len(height) - 1 - i]))
        right_highest.reverse()
        ret = 0
        for h, lh, rh in zip(height, left_highest, right_highest):
            ret += max(0, min(lh, rh) - h)
        return ret
<|end_body_1|>

<|body_start_2|>
        if not height:
            return 0
        ret = 0
        highest_idx = 0
        highest = height[highest_idx]
        water = 0
        for i in range(1, len(height)):
            h = height[i]
            if h < highest:
                water += highest - h
            else:
                highest = h
                highest_idx = i
                ret += water
                water = 0
        highest_idx_from_left = highest_idx
        highest_idx = len(height) - 1
        highest = height[highest_idx]
        water = 0
        for i in range(len(height) - 2, highest_idx_from_left - 1, -1):
            h = height[i]
            if h < highest:
                water += highest - h
            else:
                highest = h
                highest_idx = i
                ret += water
                water = 0
        return ret
<|end_body_2|>

<|body_start_3|>
        max_from_left = [0]
        max_from_right = [0]
        for h in height:
            max_from_left.append(max(max_from_left[-1], h))
        for h in reversed(height):
            max_from_right.append(max(max_from_right[-1], h))
        max_from_right.reverse()
        return sum((max(0, min(l, r) - height[i]) for i, (l, r) in enumerate(zip(max_from_left, max_from_right), -1)))
<|end_body_3|>

Solution:
class Solution:
    def trap(self, height):
        """08/06/2018 02:27"""
        if not height:
            return 0
        max_right = [height[-1]]
        rheight = reversed(height)
        next(rheight)
        for i, h in enumerate(rheight):
            max_right.append(max(max_right[i], h))
        max_right.reverse()
        max_left = [height[0]]
        for i, h in enumerate(height[1:]):
            max_left.append(max(max_left[i], h))
        s = 0
        for h, l, r in zip(height, max_left, max_right):
            s += min(l, r) - h
        return s

    def trap(self, height: List[int]) -> int:
        """Time complexity: O(n) Space complexity: O(n)"""
        height = [0] + height + [0]
        n = len(height)
        left_highest = [0]
        for i in range(1, len(height)):
            left_highest.append(max(left_highest[i - 1], height[i - 1]))
        right_highest = [0]
        for i in range(1, len(height)):
            right_highest.append(max(right_highest[i - 1], height[len(height) - 1 - i]))
        right_highest.reverse()
        ret = 0
        for h, lh, rh in zip(height, left_highest, right_highest):
            ret += max(0, min(lh, rh) - h)
        return ret

    def trap(self, height: List[int]) -> int:
        """Time complexity: O(n) Space complexity: O(1)"""
        if not height:
            return 0
        ret = 0
        highest_idx = 0
        highest = height[highest_idx]
        water = 0
        for i in range(1, len(height)):
            h = height[i]
            if h < highest:
                water += highest - h
            else:
                highest = h
                highest_idx = i
                ret += water
                water = 0
        highest_idx_from_left = highest_idx
        highest_idx = len(height) - 1
        highest = height[highest_idx]
        water = 0
        for i in range(len(height) - 2, highest_idx_from_left - 1, -1):
            h = height[i]
            if h < highest:
                water += highest - h
            else:
                highest = h
                highest_idx = i
                ret += water
                water = 0
        return ret

    def _trap(self, height: List[int]) -> int:
        """10/16/2022 16:16 Time complexity: O(n) Space complexity: O(n)"""
        max_from_left = [0]
        max_from_right = [0]
        for h in height:
            max_from_left.append(max(max_from_left[-1], h))
        for h in reversed(height):
            max_from_right.append(max(max_from_right[-1], h))
        max_from_right.reverse()
        return sum((max(0, min(l, r) - height[i]) for i, (l, r) in enumerate(zip(max_from_left, max_from_right), -1)))


get

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

Class description:
This table contains a mapping between a location string to the coordinates of that location. It contains static functions to convert a given city/state to the expected format and to 'get' coordinates (which will attempt to first retrieve from the table, then query the geolocator if not present). Locations are in the format: `X, Y USA` where X is the city name and Y is the state's 2 letter abbreviation.

Method signatures and docstrings:
- def to_location(city: str=None, state: str=None) -> str: Converts a city and state (both optional) to the key expected by this table.
- def get(city: str=None, state: str=None, fallback=True) -> Tuple[float, float]: Gets the coordinates for the given city and/or state. If fallback is true, it will attempt to get the closest matching result (just state if city cannot be found, otherwise just 'USA')

Implement the Python class `LocationCoordinates` described below.

Class description:
This table contains a mapping between a location string to the coordinates of that location. It contains static functions to convert a given city/state to the expected format and to 'get' coordinates (which will attempt to first retrieve from the table, then query the geolocator if not present). Locations are in the format: `X, Y USA` where X is the city name and Y is the state's 2 letter abbreviation.

Method signatures and docstrings:
- def to_location(city: str=None, state: str=None) -> str: Converts a city and state (both optional) to the key expected by this table.
- def get(city: str=None, state: str=None, fallback=True) -> Tuple[float, float]: Gets the coordinates for the given city and/or state. If fallback is true, it will attempt to get the closest matching result (just state if city cannot be found, otherwise just 'USA')

<|skeleton|>
class LocationCoordinates:
    """This table contains a mapping between a location string to the coordinates of that location. It contains static functions to convert a given city/state to the expected format and to 'get' coordinates (which will attempt to first retrieve from the table, then query the geolocator if not present). Locations are in the format: `X, Y USA` where X is the city name and Y is the state's 2 letter abbreviation."""

    def to_location(city: str=None, state: str=None) -> str:
        """Converts a city and state (both optional) to the key expected by this table."""
        <|body_0|>

    def get(city: str=None, state: str=None, fallback=True) -> Tuple[float, float]:
        """Gets the coordinates for the given city and/or state. If fallback is true, it will attempt to get the closest matching result (just state if city cannot be found, otherwise just 'USA')"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if city is None and state is None:
            return 'USA'
        elif city is None or state is None:
            return f"{city or ''}{state or ''}, USA"
        return f'{city}, {state} USA'
<|end_body_0|>

<|body_start_1|>
        loc_id = LocationCoordinates.to_location(city, state)
        row = LocationCoordinates.query.get(loc_id)
        if row is None:
            loc_obj = geolocator.geocode(loc_id)
            if loc_obj is None or loc_obj.latitude is None:
                if not fallback:
                    raise ValueError(f"Cannot be found: '{loc_id}' (city: {city}, state: {state})")
                if state is not None:
                    return LocationCoordinates.get(None, state, fallback)
                return (32.3078, -64.7505)
            row = LocationCoordinates(location=loc_id, latitude=loc_obj.latitude, longitude=loc_obj.longitude)
            db.session.add(row)
            db.session.commit()
        return (row.latitude, row.longitude)
<|end_body_1|>

Solution:
class LocationCoordinates:
    """This table contains a mapping between a location string to the coordinates of that location. It contains static functions to convert a given city/state to the expected format and to 'get' coordinates (which will attempt to first retrieve from the table, then query the geolocator if not present). Locations are in the format: `X, Y USA` where X is the city name and Y is the state's 2 letter abbreviation."""

    def to_location(city: str=None, state: str=None) -> str:
        """Converts a city and state (both optional) to the key expected by this table."""
        if city is None and state is None:
            return 'USA'
        elif city is None or state is None:
            return f"{city or ''}{state or ''}, USA"
        return f'{city}, {state} USA'

    def get(city: str=None, state: str=None, fallback=True) -> Tuple[float, float]:
        """Gets the coordinates for the given city and/or state. If fallback is true, it will attempt to get the closest matching result (just state if city cannot be found, otherwise just 'USA')"""
        loc_id = LocationCoordinates.to_location(city, state)
        row = LocationCoordinates.query.get(loc_id)
        if row is None:
            loc_obj = geolocator.geocode(loc_id)
            if loc_obj is None or loc_obj.latitude is None:
                if not fallback:
                    raise ValueError(f"Cannot be found: '{loc_id}' (city: {city}, state: {state})")
                if state is not None:
                    return LocationCoordinates.get(None, state, fallback)
                return (32.3078, -64.7505)
            row = LocationCoordinates(location=loc_id, latitude=loc_obj.latitude, longitude=loc_obj.longitude)
            db.session.add(row)
            db.session.commit()
        return (row.latitude, row.longitude)


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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: List[int] :rtype: int

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: List[int] :rtype: int

<|skeleton|>
class Solution:

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

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

<|end_skeleton|>

<|body_start_0|>
        if len(prices) == 0:
            return 0
        s0 = -prices[0]
        s1 = -2 ** 31
        for i in range(1, len(prices)):
            s0 = max(s0, -prices[i])
            s1 = max(s1, prices[i] + s0)
        return max(0, s1)
<|end_body_0|>

<|body_start_1|>
        maxNum = 0
        length = len(prices)
        for i in range(length):
            for j in range(i + 1, length):
                profit = prices[j] - prices[i]
                if profit > maxNum:
                    maxNum = profit
        return maxNum
<|end_body_1|>

Solution:
class Solution:
    def maxProfit(self, prices):
        """:type prices: List[int] :rtype: int"""
        if len(prices) == 0:
            return 0
        s0 = -prices[0]
        s1 = -2 ** 31
        for i in range(1, len(prices)):
            s0 = max(s0, -prices[i])
            s1 = max(s1, prices[i] + s0)
        return max(0, s1)

    def maxProfit(self, prices):
        """:type prices: List[int] :rtype: int"""
        maxNum = 0
        length = len(prices)
        for i in range(length):
            for j in range(i + 1, length):
                profit = prices[j] - prices[i]
                if profit > maxNum:
                    maxNum = profit
        return maxNum


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

Class description:
Implement the SessionMiddleware class.

Method signatures and docstrings:
- def __init__(self, api, exempt_routes=list(), exempt_methods=list()): Класс, содержащий сессионный middleware. Для настройки исключений используется проход по всем эндпоинтам и поиск настроек в аттрибутах классов, также можно передать эти параметры в аргументах конструктора. Аргументы: api(falcon.App, необходим): ссылка на экземпляр API. exempt_routes(list, опционально): список путей, не требущих аутентификации. exempt_methods(list, опционально): список методов, не требующих аутентификации.
- def _get_all_routes(self, api): Ищет все пары вида (класс ресурса, шаблон URI) в API Аргументы: api(falcon.App, необходим): ссылка на экземпляр API.
- def _get_settings(self, resource, uri_template): Собирает настройки из класса эндпоинта и добавляет их в глобальный конфиг. Аргументы: resource(необходим): ссылка на экземпляр класса эндпоинта. uri_template(string, необходим): строка, по которой производится маршрутизация к этому эндпоинту.
- def csrf_protect(self, req): Проверяет CSRF-токен всех POST-запросов. Выбрасывает исключение, если запрос не проходит проверку. Аргументы: req(необходим): текущий запрос.
- def process_resource(self, req, resp, resource, params): Автоматически вызывается Falcon при получении запроса. Аутентифицирует пользователя, проверяет CSRF-токен, а также добавляет в контекст запроса информацию о пользователе и его сессии.

Implement the Python class `SessionMiddleware` described below.

Class description:
Implement the SessionMiddleware class.

Method signatures and docstrings:
- def __init__(self, api, exempt_routes=list(), exempt_methods=list()): Класс, содержащий сессионный middleware. Для настройки исключений используется проход по всем эндпоинтам и поиск настроек в аттрибутах классов, также можно передать эти параметры в аргументах конструктора. Аргументы: api(falcon.App, необходим): ссылка на экземпляр API. exempt_routes(list, опционально): список путей, не требущих аутентификации. exempt_methods(list, опционально): список методов, не требующих аутентификации.
- def _get_all_routes(self, api): Ищет все пары вида (класс ресурса, шаблон URI) в API Аргументы: api(falcon.App, необходим): ссылка на экземпляр API.
- def _get_settings(self, resource, uri_template): Собирает настройки из класса эндпоинта и добавляет их в глобальный конфиг. Аргументы: resource(необходим): ссылка на экземпляр класса эндпоинта. uri_template(string, необходим): строка, по которой производится маршрутизация к этому эндпоинту.
- def csrf_protect(self, req): Проверяет CSRF-токен всех POST-запросов. Выбрасывает исключение, если запрос не проходит проверку. Аргументы: req(необходим): текущий запрос.
- def process_resource(self, req, resp, resource, params): Автоматически вызывается Falcon при получении запроса. Аутентифицирует пользователя, проверяет CSRF-токен, а также добавляет в контекст запроса информацию о пользователе и его сессии.

<|skeleton|>
class SessionMiddleware:

    def __init__(self, api, exempt_routes=list(), exempt_methods=list()):
        """Класс, содержащий сессионный middleware. Для настройки исключений используется проход по всем эндпоинтам и поиск настроек в аттрибутах классов, также можно передать эти параметры в аргументах конструктора. Аргументы: api(falcon.App, необходим): ссылка на экземпляр API. exempt_routes(list, опционально): список путей, не требущих аутентификации. exempt_methods(list, опционально): список методов, не требующих аутентификации."""
        <|body_0|>

    def _get_all_routes(self, api):
        """Ищет все пары вида (класс ресурса, шаблон URI) в API Аргументы: api(falcon.App, необходим): ссылка на экземпляр API."""
        <|body_1|>

    def _get_settings(self, resource, uri_template):
        """Собирает настройки из класса эндпоинта и добавляет их в глобальный конфиг. Аргументы: resource(необходим): ссылка на экземпляр класса эндпоинта. uri_template(string, необходим): строка, по которой производится маршрутизация к этому эндпоинту."""
        <|body_2|>

    def csrf_protect(self, req):
        """Проверяет CSRF-токен всех POST-запросов. Выбрасывает исключение, если запрос не проходит проверку. Аргументы: req(необходим): текущий запрос."""
        <|body_3|>

    def process_resource(self, req, resp, resource, params):
        """Автоматически вызывается Falcon при получении запроса. Аутентифицирует пользователя, проверяет CSRF-токен, а также добавляет в контекст запроса информацию о пользователе и его сессии."""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        self.manager = SessionManager()
        self.config = dict()
        self.config['exempt_routes'] = exempt_routes
        self.config['exempt_methods'] = dict()
        self.config['exempt_methods']['global'] = exempt_methods
        routes = self._get_all_routes(api)
        for route in routes:
            self._get_settings(*route)
<|end_body_0|>

<|body_start_1|>
        routes = []

        def get_node_and_children(node):
            routes.append((node.resource, node.uri_template))
            if len(node.children):
                for child_node in node.children:
                    get_node_and_children(child_node)
        for node in api._router._roots:
            get_node_and_children(node)
        return routes
<|end_body_1|>

<|body_start_2|>
        local_conf = getattr(resource, 'auth', {})
        if local_conf.get('disabled'):
            self.config['exempt_routes'].append(uri_template)
        self.config['exempt_methods'][str(resource)] = local_conf.get('exempt_methods', [])
<|end_body_2|>

<|body_start_3|>
        if req.method == 'POST':
            csrf = req.get_header('X-CSRF-Token')
            if csrf is None or csrf != req.context['user']['csrf_token']:
                req.context.logger.error('[ПОПЫТКА CSRF] uid %s, sid %s' % (req.context['user']['uid'], req.context['user']['sid']))
                raise falcon.HTTPUnauthorized(description='Неверный CSRF-токен')
<|end_body_3|>

<|body_start_4|>
        exempted = req.method in self.config['exempt_methods']['global'] or req.uri_template in self.config['exempt_routes'] or req.method in self.config['exempt_methods'][str(resource)]
        try:
            req.context['user'] = self.manager.authenticate(req.context.session, req.cookies)
        except BadAuthError:
            req.context['user'] = None
            if exempted:
                return
            else:
                raise falcon.HTTPUnauthorized
        self.csrf_protect(req)
<|end_body_4|>

Solution:
class SessionMiddleware:
    def __init__(self, api, exempt_routes=list(), exempt_methods=list()):
        """Класс, содержащий сессионный middleware. Для настройки исключений используется проход по всем эндпоинтам и поиск настроек в аттрибутах классов, также можно передать эти параметры в аргументах конструктора. Аргументы: api(falcon.App, необходим): ссылка на экземпляр API. exempt_routes(list, опционально): список путей, не требущих аутентификации. exempt_methods(list, опционально): список методов, не требующих аутентификации."""
        self.manager = SessionManager()
        self.config = dict()
        self.config['exempt_routes'] = exempt_routes
        self.config['exempt_methods'] = dict()
        self.config['exempt_methods']['global'] = exempt_methods
        routes = self._get_all_routes(api)
        for route in routes:
            self._get_settings(*route)

    def _get_all_routes(self, api):
        """Ищет все пары вида (класс ресурса, шаблон URI) в API Аргументы: api(falcon.App, необходим): ссылка на экземпляр API."""
        routes = []

        def get_node_and_children(node):
            routes.append((node.resource, node.uri_template))
            if len(node.children):
                for child_node in node.children:
                    get_node_and_children(child_node)
        for node in api._router._roots:
            get_node_and_children(node)
        return routes

    def _get_settings(self, resource, uri_template):
        """Собирает настройки из класса эндпоинта и добавляет их в глобальный конфиг. Аргументы: resource(необходим): ссылка на экземпляр класса эндпоинта. uri_template(string, необходим): строка, по которой производится маршрутизация к этому эндпоинту."""
        local_conf = getattr(resource, 'auth', {})
        if local_conf.get('disabled'):
            self.config['exempt_routes'].append(uri_template)
        self.config['exempt_methods'][str(resource)] = local_conf.get('exempt_methods', [])

    def csrf_protect(self, req):
        """Проверяет CSRF-токен всех POST-запросов. Выбрасывает исключение, если запрос не проходит проверку. Аргументы: req(необходим): текущий запрос."""
        if req.method == 'POST':
            csrf = req.get_header('X-CSRF-Token')
            if csrf is None or csrf != req.context['user']['csrf_token']:
                req.context.logger.error('[ПОПЫТКА CSRF] uid %s, sid %s' % (req.context['user']['uid'], req.context['user']['sid']))
                raise falcon.HTTPUnauthorized(description='Неверный CSRF-токен')

    def process_resource(self, req, resp, resource, params):
        """Автоматически вызывается Falcon при получении запроса. Аутентифицирует пользователя, проверяет CSRF-токен, а также добавляет в контекст запроса информацию о пользователе и его сессии."""
        exempted = req.method in self.config['exempt_methods']['global'] or req.uri_template in self.config['exempt_routes'] or req.method in self.config['exempt_methods'][str(resource)]
        try:
            req.context['user'] = self.manager.authenticate(req.context.session, req.cookies)
        except BadAuthError:
            req.context['user'] = None
            if exempted:
                return
            else:
                raise falcon.HTTPUnauthorized
        self.csrf_protect(req)


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

Class description:
Implement the Singleton class.

Method signatures and docstrings:
- def getInstance(): Static access method.
- def __init__(self): Virtually private constructor.

Implement the Python class `Singleton` described below.

Class description:
Implement the Singleton class.

Method signatures and docstrings:
- def getInstance(): Static access method.
- def __init__(self): Virtually private constructor.

<|skeleton|>
class Singleton:

    def getInstance():
        """Static access method."""
        <|body_0|>

    def __init__(self):
        """Virtually private constructor."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        a = int(input('Birinci Sayı:'))
        b = int(input('İkinci Sayı:'))
        if Singleton.__instance == None:
            Singleton()
        return ('Toplam:', a + b, 'fark: ', a - b, 'Carpim: ', a * b, 'bolum: ', a / b)
<|end_body_0|>

<|body_start_1|>
        if Singleton.__instance != None:
            raise Exception('This class is a singleton!')
        else:
            Singleton.__instance = self
<|end_body_1|>

Solution:
class Singleton:
    def getInstance():
        """Static access method."""
        a = int(input('Birinci Sayı:'))
        b = int(input('İkinci Sayı:'))
        if Singleton.__instance == None:
            Singleton()
        return ('Toplam:', a + b, 'fark: ', a - b, 'Carpim: ', a * b, 'bolum: ', a / b)

    def __init__(self):
        """Virtually private constructor."""
        if Singleton.__instance != None:
            raise Exception('This class is a singleton!')
        else:
            Singleton.__instance = self