execute

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

Class description:
Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> nan, nan, nan, 8, 5, 5, 1, 0, 0, 0 'b': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> 8, 8, 8, 8, 5, 1, 1, 0, nan, nan 'fb': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> 8, 8, 8, 8, 5, 5, 1, 0, 0, 0 'bf': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> 8, 8, 8, 8, 5, 1, 1, 0, 0, 0

Method signatures and docstrings:
- def __init__(self, feature: SingleFeatureSpec, operations: Literal['f', 'b', 'fb', 'bf']='fb', value: float=np.nan, axis: int=0): :param feature: A feature that must be value-filled. :param operations: Fill directions, which should be one of ['f', 'b', 'fb', 'bf']. :param value: Which value to fill by its neighbors. :param axis: An axis along which to fill values.
- def fill(data: np.ndarray, value: float=np.nan, operation: Literal['f', 'b']='f') -> np.ndarray: Fills occurrences of a desired value in a 2d array with their neighbors in either forward or backward direction. :param data: A 2d numpy array. :param value: Which value to fill by its neighbors. :param operation: Fill directions, which should be either 'f' or 'b'. :return: Value-filled numpy array.
- def execute(self, eopatch: EOPatch) -> EOPatch: :param eopatch: Source EOPatch from which to read the feature data. :return: An eopatch with the value-filled feature.

Implement the Python class `ValueFilloutTask` described below.

Class description:
Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> nan, nan, nan, 8, 5, 5, 1, 0, 0, 0 'b': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> 8, 8, 8, 8, 5, 1, 1, 0, nan, nan 'fb': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> 8, 8, 8, 8, 5, 5, 1, 0, 0, 0 'bf': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> 8, 8, 8, 8, 5, 1, 1, 0, 0, 0

Method signatures and docstrings:
- def __init__(self, feature: SingleFeatureSpec, operations: Literal['f', 'b', 'fb', 'bf']='fb', value: float=np.nan, axis: int=0): :param feature: A feature that must be value-filled. :param operations: Fill directions, which should be one of ['f', 'b', 'fb', 'bf']. :param value: Which value to fill by its neighbors. :param axis: An axis along which to fill values.
- def fill(data: np.ndarray, value: float=np.nan, operation: Literal['f', 'b']='f') -> np.ndarray: Fills occurrences of a desired value in a 2d array with their neighbors in either forward or backward direction. :param data: A 2d numpy array. :param value: Which value to fill by its neighbors. :param operation: Fill directions, which should be either 'f' or 'b'. :return: Value-filled numpy array.
- def execute(self, eopatch: EOPatch) -> EOPatch: :param eopatch: Source EOPatch from which to read the feature data. :return: An eopatch with the value-filled feature.

<|skeleton|>
class ValueFilloutTask:
    """Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> nan, nan, nan, 8, 5, 5, 1, 0, 0, 0 'b': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> 8, 8, 8, 8, 5, 1, 1, 0, nan, nan 'fb': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> 8, 8, 8, 8, 5, 5, 1, 0, 0, 0 'bf': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> 8, 8, 8, 8, 5, 1, 1, 0, 0, 0"""

    def __init__(self, feature: SingleFeatureSpec, operations: Literal['f', 'b', 'fb', 'bf']='fb', value: float=np.nan, axis: int=0):
        """:param feature: A feature that must be value-filled. :param operations: Fill directions, which should be one of ['f', 'b', 'fb', 'bf']. :param value: Which value to fill by its neighbors. :param axis: An axis along which to fill values."""
        <|body_0|>

    def fill(data: np.ndarray, value: float=np.nan, operation: Literal['f', 'b']='f') -> np.ndarray:
        """Fills occurrences of a desired value in a 2d array with their neighbors in either forward or backward direction. :param data: A 2d numpy array. :param value: Which value to fill by its neighbors. :param operation: Fill directions, which should be either 'f' or 'b'. :return: Value-filled numpy array."""
        <|body_1|>

    def execute(self, eopatch: EOPatch) -> EOPatch:
        """:param eopatch: Source EOPatch from which to read the feature data. :return: An eopatch with the value-filled feature."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        if operations not in ['f', 'b', 'fb', 'bf']:
            raise ValueError("'operations' parameter should be one of the following options: f, b, fb, bf.")
        self.feature = self.parse_feature(feature)
        self.operations = operations
        self.value = value
        self.axis = axis
<|end_body_0|>

<|body_start_1|>
        if not isinstance(data, np.ndarray) or data.ndim != 2:
            raise ValueError('Wrong data input')
        if operation not in ['f', 'b']:
            raise ValueError("'operation' parameter should either be 'f' (forward) or 'b' (backward)!")
        n_rows, n_frames = data.shape
        value_mask = np.isnan(data) if np.isnan(value) else data == value
        init_index = 0 if operation == 'f' else n_frames - 1
        idx = np.where(value_mask, init_index, np.arange(n_frames))
        if operation == 'f':
            idx = np.maximum.accumulate(idx, axis=1)
        else:
            idx = idx[:, ::-1]
            idx = np.minimum.accumulate(idx, axis=1)
            idx = idx[:, ::-1]
        return data[np.arange(n_rows)[:, np.newaxis], idx]
<|end_body_1|>

<|body_start_2|>
        data = eopatch[self.feature]
        value_mask = np.isnan(data) if np.isnan(self.value) else data == self.value
        if not value_mask.any():
            return eopatch
        data = np.swapaxes(data, self.axis, -1)
        original_shape = data.shape
        data = data.reshape(np.prod(original_shape[:-1]), original_shape[-1])
        for operation in self.operations:
            operation = cast(Literal['f', 'b'], operation)
            data = self.fill(data, value=self.value, operation=operation)
        data = data.reshape(*original_shape)
        data = np.swapaxes(data, self.axis, -1)
        eopatch[self.feature] = data
        return eopatch
<|end_body_2|>

Solution:
class ValueFilloutTask:
    """Overwrites occurrences of a desired value with their neighbor values in either forward, backward direction or both, along an axis. Possible fillout operations are 'f' (forward), 'b' (backward) or both, 'fb' or 'bf': 'f': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> nan, nan, nan, 8, 5, 5, 1, 0, 0, 0 'b': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> 8, 8, 8, 8, 5, 1, 1, 0, nan, nan 'fb': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> 8, 8, 8, 8, 5, 5, 1, 0, 0, 0 'bf': nan, nan, nan, 8, 5, nan, 1, 0, nan, nan -> 8, 8, 8, 8, 5, 1, 1, 0, 0, 0"""

    def __init__(self, feature: SingleFeatureSpec, operations: Literal['f', 'b', 'fb', 'bf']='fb', value: float=np.nan, axis: int=0):
        """:param feature: A feature that must be value-filled. :param operations: Fill directions, which should be one of ['f', 'b', 'fb', 'bf']. :param value: Which value to fill by its neighbors. :param axis: An axis along which to fill values."""
        if operations not in ['f', 'b', 'fb', 'bf']:
            raise ValueError("'operations' parameter should be one of the following options: f, b, fb, bf.")
        self.feature = self.parse_feature(feature)
        self.operations = operations
        self.value = value
        self.axis = axis

    def fill(data: np.ndarray, value: float=np.nan, operation: Literal['f', 'b']='f') -> np.ndarray:
        """Fills occurrences of a desired value in a 2d array with their neighbors in either forward or backward direction. :param data: A 2d numpy array. :param value: Which value to fill by its neighbors. :param operation: Fill directions, which should be either 'f' or 'b'. :return: Value-filled numpy array."""
        if not isinstance(data, np.ndarray) or data.ndim != 2:
            raise ValueError('Wrong data input')
        if operation not in ['f', 'b']:
            raise ValueError("'operation' parameter should either be 'f' (forward) or 'b' (backward)!")
        n_rows, n_frames = data.shape
        value_mask = np.isnan(data) if np.isnan(value) else data == value
        init_index = 0 if operation == 'f' else n_frames - 1
        idx = np.where(value_mask, init_index, np.arange(n_frames))
        if operation == 'f':
            idx = np.maximum.accumulate(idx, axis=1)
        else:
            idx = idx[:, ::-1]
            idx = np.minimum.accumulate(idx, axis=1)
            idx = idx[:, ::-1]
        return data[np.arange(n_rows)[:, np.newaxis], idx]

    def execute(self, eopatch: EOPatch) -> EOPatch:
        """:param eopatch: Source EOPatch from which to read the feature data. :return: An eopatch with the value-filled feature."""
        data = eopatch[self.feature]
        value_mask = np.isnan(data) if np.isnan(self.value) else data == self.value
        if not value_mask.any():
            return eopatch
        data = np.swapaxes(data, self.axis, -1)
        original_shape = data.shape
        data = data.reshape(np.prod(original_shape[:-1]), original_shape[-1])
        for operation in self.operations:
            operation = cast(Literal['f', 'b'], operation)
            data = self.fill(data, value=self.value, operation=operation)
        data = data.reshape(*original_shape)
        data = np.swapaxes(data, self.axis, -1)
        eopatch[self.feature] = data
        return eopatch


create

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

Class description:
Implement the EventViewSet class.

Method signatures and docstrings:
- def list(self, request): Endpoint returns paginated list of all events available in the database. Required params: - current_page: number (starting from 1) - page_size: number :param request: :return: - events: list - list of events - last_page: number
- def create(self, request): Endpoint returns detailed info about particular event based on given event id. Required params: - event_id: string :param request: :return: Event data, types of tickets, amount of tickets available

Implement the Python class `EventViewSet` described below.

Class description:
Implement the EventViewSet class.

Method signatures and docstrings:
- def list(self, request): Endpoint returns paginated list of all events available in the database. Required params: - current_page: number (starting from 1) - page_size: number :param request: :return: - events: list - list of events - last_page: number
- def create(self, request): Endpoint returns detailed info about particular event based on given event id. Required params: - event_id: string :param request: :return: Event data, types of tickets, amount of tickets available

<|skeleton|>
class EventViewSet:

    def list(self, request):
        """Endpoint returns paginated list of all events available in the database. Required params: - current_page: number (starting from 1) - page_size: number :param request: :return: - events: list - list of events - last_page: number"""
        <|body_0|>

    def create(self, request):
        """Endpoint returns detailed info about particular event based on given event id. Required params: - event_id: string :param request: :return: Event data, types of tickets, amount of tickets available"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        current_page = int(self.request.query_params.get('current_page'))
        page_size = int(self.request.query_params.get('page_size'))
        now = datetime.datetime.now()
        events = Event.objects.filter(date__gte=now).order_by('date')
        events_serializer = EventSerializer(events, many=True)
        paginator = Paginator(events_serializer.data, page_size)
        page = paginator.get_page(current_page)
        return_data = dict()
        return_data['events'] = page.object_list
        return_data['last_page'] = paginator.num_pages
        return JsonResponse(return_data)
<|end_body_0|>

<|body_start_1|>
        event = Event.objects.get(id=request.data['event_id'])
        event_serializer = EventSerializer(event)
        ticket_types = event.ticket_types.all()
        ticket_type_serializer = TicketTypeSerializer(ticket_types, many=True)
        serialized_ticket_types = ticket_type_serializer.data
        ticket_counters = dict()
        for ticket in serialized_ticket_types:
            ticket_counters[ticket['type']] = event.tickets_ordered.filter(Q(type=ticket['type'], reservation__status='PENDING') | Q(type=ticket['type'], reservation__status='COMPLETED')).count()
        for ticket in serialized_ticket_types:
            ticket['tickets_left'] = ticket['amount'] - ticket_counters[ticket['type']]
        return_data = dict()
        return_data['event'] = event_serializer.data
        return_data['ticket_types'] = ticket_type_serializer.data
        return JsonResponse(return_data)
<|end_body_1|>

Solution:
class EventViewSet:
    def list(self, request):
        """Endpoint returns paginated list of all events available in the database. Required params: - current_page: number (starting from 1) - page_size: number :param request: :return: - events: list - list of events - last_page: number"""
        current_page = int(self.request.query_params.get('current_page'))
        page_size = int(self.request.query_params.get('page_size'))
        now = datetime.datetime.now()
        events = Event.objects.filter(date__gte=now).order_by('date')
        events_serializer = EventSerializer(events, many=True)
        paginator = Paginator(events_serializer.data, page_size)
        page = paginator.get_page(current_page)
        return_data = dict()
        return_data['events'] = page.object_list
        return_data['last_page'] = paginator.num_pages
        return JsonResponse(return_data)

    def create(self, request):
        """Endpoint returns detailed info about particular event based on given event id. Required params: - event_id: string :param request: :return: Event data, types of tickets, amount of tickets available"""
        event = Event.objects.get(id=request.data['event_id'])
        event_serializer = EventSerializer(event)
        ticket_types = event.ticket_types.all()
        ticket_type_serializer = TicketTypeSerializer(ticket_types, many=True)
        serialized_ticket_types = ticket_type_serializer.data
        ticket_counters = dict()
        for ticket in serialized_ticket_types:
            ticket_counters[ticket['type']] = event.tickets_ordered.filter(Q(type=ticket['type'], reservation__status='PENDING') | Q(type=ticket['type'], reservation__status='COMPLETED')).count()
        for ticket in serialized_ticket_types:
            ticket['tickets_left'] = ticket['amount'] - ticket_counters[ticket['type']]
        return_data = dict()
        return_data['event'] = event_serializer.data
        return_data['ticket_types'] = ticket_type_serializer.data
        return JsonResponse(return_data)


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

Class description:
Benchmark with default configuration & relevant functions for SGD

Method signatures and docstrings:
- def __init__(self, config_path=None, config=None): Initialize SGD Benchmark Parameters ------- config_path : str Path to config file (optional)
- def get_environment(self): Return SGDEnv env with current configuration Returns ------- SGDEnv SGD environment
- def read_instance_set(self, test=False): Read path of instances from config into list
- def get_benchmark(self, instance_set_path=None, seed=0): Get benchmark from the LTO paper Parameters ------- seed : int Environment seed Returns ------- env : SGDEnv SGD environment

Implement the Python class `SGDBenchmark` described below.

Class description:
Benchmark with default configuration & relevant functions for SGD

Method signatures and docstrings:
- def __init__(self, config_path=None, config=None): Initialize SGD Benchmark Parameters ------- config_path : str Path to config file (optional)
- def get_environment(self): Return SGDEnv env with current configuration Returns ------- SGDEnv SGD environment
- def read_instance_set(self, test=False): Read path of instances from config into list
- def get_benchmark(self, instance_set_path=None, seed=0): Get benchmark from the LTO paper Parameters ------- seed : int Environment seed Returns ------- env : SGDEnv SGD environment

<|skeleton|>
class SGDBenchmark:
    """Benchmark with default configuration & relevant functions for SGD"""

    def __init__(self, config_path=None, config=None):
        """Initialize SGD Benchmark Parameters ------- config_path : str Path to config file (optional)"""
        <|body_0|>

    def get_environment(self):
        """Return SGDEnv env with current configuration Returns ------- SGDEnv SGD environment"""
        <|body_1|>

    def read_instance_set(self, test=False):
        """Read path of instances from config into list"""
        <|body_2|>

    def get_benchmark(self, instance_set_path=None, seed=0):
        """Get benchmark from the LTO paper Parameters ------- seed : int Environment seed Returns ------- env : SGDEnv SGD environment"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        super(SGDBenchmark, self).__init__(config_path, config)
        if not self.config:
            self.config = objdict(SGD_DEFAULTS.copy())
        for key in SGD_DEFAULTS:
            if key not in self.config:
                self.config[key] = SGD_DEFAULTS[key]
<|end_body_0|>

<|body_start_1|>
        if 'instance_set' not in self.config.keys():
            self.read_instance_set()
        if 'test_set' not in self.config.keys() and 'test_set_path' in self.config.keys():
            self.read_instance_set(test=True)
        env = SGDEnv(self.config)
        for func in self.wrap_funcs:
            env = func(env)
        return env
<|end_body_1|>

<|body_start_2|>
        if test:
            path = os.path.dirname(os.path.abspath(__file__)) + '/' + self.config.test_set_path
            keyword = 'test_set'
        else:
            path = os.path.dirname(os.path.abspath(__file__)) + '/' + self.config.instance_set_path
            keyword = 'instance_set'
        self.config[keyword] = {}
        with open(path, 'r') as fh:
            reader = csv.DictReader(fh, delimiter=';')
            for row in reader:
                if '_' in row['dataset']:
                    dataset_info = row['dataset'].split('_')
                    dataset_name = dataset_info[0]
                    dataset_size = int(dataset_info[1])
                else:
                    dataset_name = row['dataset']
                    dataset_size = None
                instance = [dataset_name, int(row['seed']), row['architecture'], int(row['steps']), dataset_size]
                self.config[keyword][int(row['ID'])] = instance
<|end_body_2|>

<|body_start_3|>
        self.config = objdict(SGD_DEFAULTS.copy())
        if instance_set_path is not None:
            self.config['instance_set_path'] = instance_set_path
        self.config.seed = seed
        self.read_instance_set()
        return SGDEnv(self.config)
<|end_body_3|>

Solution:
class SGDBenchmark:
    """Benchmark with default configuration & relevant functions for SGD"""

    def __init__(self, config_path=None, config=None):
        """Initialize SGD Benchmark Parameters ------- config_path : str Path to config file (optional)"""
        super(SGDBenchmark, self).__init__(config_path, config)
        if not self.config:
            self.config = objdict(SGD_DEFAULTS.copy())
        for key in SGD_DEFAULTS:
            if key not in self.config:
                self.config[key] = SGD_DEFAULTS[key]

    def get_environment(self):
        """Return SGDEnv env with current configuration Returns ------- SGDEnv SGD environment"""
        if 'instance_set' not in self.config.keys():
            self.read_instance_set()
        if 'test_set' not in self.config.keys() and 'test_set_path' in self.config.keys():
            self.read_instance_set(test=True)
        env = SGDEnv(self.config)
        for func in self.wrap_funcs:
            env = func(env)
        return env

    def read_instance_set(self, test=False):
        """Read path of instances from config into list"""
        if test:
            path = os.path.dirname(os.path.abspath(__file__)) + '/' + self.config.test_set_path
            keyword = 'test_set'
        else:
            path = os.path.dirname(os.path.abspath(__file__)) + '/' + self.config.instance_set_path
            keyword = 'instance_set'
        self.config[keyword] = {}
        with open(path, 'r') as fh:
            reader = csv.DictReader(fh, delimiter=';')
            for row in reader:
                if '_' in row['dataset']:
                    dataset_info = row['dataset'].split('_')
                    dataset_name = dataset_info[0]
                    dataset_size = int(dataset_info[1])
                else:
                    dataset_name = row['dataset']
                    dataset_size = None
                instance = [dataset_name, int(row['seed']), row['architecture'], int(row['steps']), dataset_size]
                self.config[keyword][int(row['ID'])] = instance

    def get_benchmark(self, instance_set_path=None, seed=0):
        """Get benchmark from the LTO paper Parameters ------- seed : int Environment seed Returns ------- env : SGDEnv SGD environment"""
        self.config = objdict(SGD_DEFAULTS.copy())
        if instance_set_path is not None:
            self.config['instance_set_path'] = instance_set_path
        self.config.seed = seed
        self.read_instance_set()
        return SGDEnv(self.config)


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

Class description:
测试查询schedulers接口 /api/schedulers/query

Method signatures and docstrings:
- def test_case01(self): 根据scheduler name模糊查询
- def test_case02(self): 根据flowtype-dataflow查询
- def test_case03(self): 根据flowtype-workflow查询
- def test_case04(self): 根据flowtype-streamflow查询
- def test_case05(self): flowtype+name组合查询scheduler
- def test_case06(self): query:根据上次修改时间查询全部的scheduler

Implement the Python class `QuerySchedulers` described below.

Class description:
测试查询schedulers接口 /api/schedulers/query

Method signatures and docstrings:
- def test_case01(self): 根据scheduler name模糊查询
- def test_case02(self): 根据flowtype-dataflow查询
- def test_case03(self): 根据flowtype-workflow查询
- def test_case04(self): 根据flowtype-streamflow查询
- def test_case05(self): flowtype+name组合查询scheduler
- def test_case06(self): query:根据上次修改时间查询全部的scheduler

<|skeleton|>
class QuerySchedulers:
    """测试查询schedulers接口 /api/schedulers/query"""

    def test_case01(self):
        """根据scheduler name模糊查询"""
        <|body_0|>

    def test_case02(self):
        """根据flowtype-dataflow查询"""
        <|body_1|>

    def test_case03(self):
        """根据flowtype-workflow查询"""
        <|body_2|>

    def test_case04(self):
        """根据flowtype-streamflow查询"""
        <|body_3|>

    def test_case05(self):
        """flowtype+name组合查询scheduler"""
        <|body_4|>

    def test_case06(self):
        """query:根据上次修改时间查询全部的scheduler"""
        <|body_5|>

<|end_skeleton|>

<|body_start_0|>
        keyword = '%student%'
        data = {'fieldList': [{'fieldName': 'name', 'fieldValue': keyword, 'comparatorOperator': 'LIKE'}], 'sortObject': {'field': 'lastModifiedTime', 'orderDirection': 'DESC'}, 'offset': 0, 'limit': 8}
        fieldValue = data['fieldList'][0]['fieldValue'][1:-1]
        res = requests.post(url=self.query_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))
        query_results = dict_res(res.text)
        self.assertEqual(res.status_code, 200, '查询失败')
        query_results = dict_res(query_results['content'][0])
        query_result_name = query_results['name']
        self.assertIn(fieldValue, query_result_name, '查询结果中scheduler的name和查询关键词name不一致')
<|end_body_0|>

<|body_start_1|>
        data = {'fieldList': [{'fieldName': 'flowType', 'fieldValue': 'dataflow', 'comparatorOperator': 'LIKE'}], 'sortObject': {'field': 'lastModifiedTime', 'orderDirection': 'DESC'}, 'offset': 0, 'limit': 8}
        fieldValue = data['fieldList'][0]['fieldValue']
        res = requests.post(url=self.query_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))
        query_results = dict_res(res.text)
        query_results = dict_res(query_results['content'][0])
        query_result_flowType = query_results['flowType']
        self.assertEqual(res.status_code, 200, '查询失败')
        self.assertEqual(fieldValue, query_result_flowType, '查询结果中scheduler关联flowtype和查询关键词flowType不一致')
<|end_body_1|>

<|body_start_2|>
        data = {'fieldList': [{'fieldName': 'flowType', 'fieldValue': 'workflow', 'comparatorOperator': 'LIKE'}], 'sortObject': {'field': 'lastModifiedTime', 'orderDirection': 'DESC'}, 'offset': 0, 'limit': 8}
        fieldValue = data['fieldList'][0]['fieldValue']
        res = requests.post(url=self.query_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))
        self.assertEqual(res.status_code, 200, '查询失败')
<|end_body_2|>

<|body_start_3|>
        data = {'fieldList': [{'fieldName': 'flowType', 'fieldValue': 'streamflow', 'comparatorOperator': 'LIKE'}], 'sortObject': {'field': 'lastModifiedTime', 'orderDirection': 'DESC'}, 'offset': 0, 'limit': 8}
        fieldValue = data['fieldList'][0]['fieldValue']
        res = requests.post(url=self.query_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))
        query_results = dict_res(res.text)
        self.assertEqual(res.status_code, 200, '查询失败')
<|end_body_3|>

<|body_start_4|>
        data = {'fieldList': [{'fieldName': 'name', 'fieldValue': '%gbj%', 'comparatorOperator': 'LIKE'}, {'fieldName': 'flowType', 'fieldValue': 'workflow', 'comparatorOperator': 'EQUAL'}], 'sortObject': {'field': 'lastModifiedTime', 'orderDirection': 'DESC'}, 'offset': 0, 'limit': 8}
        data_name = data['fieldList'][0]['fieldValue'][1:-1]
        data_flowType = data['fieldList'][1]['fieldValue']
        res = requests.post(url=self.query_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))
        self.assertEqual(200, res.status_code, 'flowtype+name组合查询scheduler失败:%s' % res.text)
<|end_body_4|>

<|body_start_5|>
        end_time = get_time()
        start_time = get_time() - 10 * 24 * 3600 * 1000
        data = {'fieldList': [{'fieldName': 'lastModifiedTime', 'fieldValue': start_time, 'comparatorOperator': 'GREATER_THAN'}, {'fieldName': 'lastModifiedTime', 'fieldValue': end_time, 'comparatorOperator': 'LESS_THAN'}], 'sortObject': {'field': 'lastModifiedTime', 'orderDirection': 'DESC'}, 'offset': 0, 'limit': 8}
        res = requests.post(url=self.query_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))
        query_results = dict_res(res.text)
        first_Time = query_results['content'][0]['lastModifiedTime']
        self.assertEqual(end_time > first_Time > start_time, True, '查询结果的lastModifiedTime不包含在起始时间内，查询结果不正确')
<|end_body_5|>

Solution:
class QuerySchedulers:
    """测试查询schedulers接口 /api/schedulers/query"""

    def test_case01(self):
        """根据scheduler name模糊查询"""
        keyword = '%student%'
        data = {'fieldList': [{'fieldName': 'name', 'fieldValue': keyword, 'comparatorOperator': 'LIKE'}], 'sortObject': {'field': 'lastModifiedTime', 'orderDirection': 'DESC'}, 'offset': 0, 'limit': 8}
        fieldValue = data['fieldList'][0]['fieldValue'][1:-1]
        res = requests.post(url=self.query_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))
        query_results = dict_res(res.text)
        self.assertEqual(res.status_code, 200, '查询失败')
        query_results = dict_res(query_results['content'][0])
        query_result_name = query_results['name']
        self.assertIn(fieldValue, query_result_name, '查询结果中scheduler的name和查询关键词name不一致')

    def test_case02(self):
        """根据flowtype-dataflow查询"""
        data = {'fieldList': [{'fieldName': 'flowType', 'fieldValue': 'dataflow', 'comparatorOperator': 'LIKE'}], 'sortObject': {'field': 'lastModifiedTime', 'orderDirection': 'DESC'}, 'offset': 0, 'limit': 8}
        fieldValue = data['fieldList'][0]['fieldValue']
        res = requests.post(url=self.query_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))
        query_results = dict_res(res.text)
        query_results = dict_res(query_results['content'][0])
        query_result_flowType = query_results['flowType']
        self.assertEqual(res.status_code, 200, '查询失败')
        self.assertEqual(fieldValue, query_result_flowType, '查询结果中scheduler关联flowtype和查询关键词flowType不一致')

    def test_case03(self):
        """根据flowtype-workflow查询"""
        data = {'fieldList': [{'fieldName': 'flowType', 'fieldValue': 'workflow', 'comparatorOperator': 'LIKE'}], 'sortObject': {'field': 'lastModifiedTime', 'orderDirection': 'DESC'}, 'offset': 0, 'limit': 8}
        fieldValue = data['fieldList'][0]['fieldValue']
        res = requests.post(url=self.query_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))
        self.assertEqual(res.status_code, 200, '查询失败')

    def test_case04(self):
        """根据flowtype-streamflow查询"""
        data = {'fieldList': [{'fieldName': 'flowType', 'fieldValue': 'streamflow', 'comparatorOperator': 'LIKE'}], 'sortObject': {'field': 'lastModifiedTime', 'orderDirection': 'DESC'}, 'offset': 0, 'limit': 8}
        fieldValue = data['fieldList'][0]['fieldValue']
        res = requests.post(url=self.query_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))
        query_results = dict_res(res.text)
        self.assertEqual(res.status_code, 200, '查询失败')

    def test_case05(self):
        """flowtype+name组合查询scheduler"""
        data = {'fieldList': [{'fieldName': 'name', 'fieldValue': '%gbj%', 'comparatorOperator': 'LIKE'}, {'fieldName': 'flowType', 'fieldValue': 'workflow', 'comparatorOperator': 'EQUAL'}], 'sortObject': {'field': 'lastModifiedTime', 'orderDirection': 'DESC'}, 'offset': 0, 'limit': 8}
        data_name = data['fieldList'][0]['fieldValue'][1:-1]
        data_flowType = data['fieldList'][1]['fieldValue']
        res = requests.post(url=self.query_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))
        self.assertEqual(200, res.status_code, 'flowtype+name组合查询scheduler失败:%s' % res.text)

    def test_case06(self):
        """query:根据上次修改时间查询全部的scheduler"""
        end_time = get_time()
        start_time = get_time() - 10 * 24 * 3600 * 1000
        data = {'fieldList': [{'fieldName': 'lastModifiedTime', 'fieldValue': start_time, 'comparatorOperator': 'GREATER_THAN'}, {'fieldName': 'lastModifiedTime', 'fieldValue': end_time, 'comparatorOperator': 'LESS_THAN'}], 'sortObject': {'field': 'lastModifiedTime', 'orderDirection': 'DESC'}, 'offset': 0, 'limit': 8}
        res = requests.post(url=self.query_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))
        query_results = dict_res(res.text)
        first_Time = query_results['content'][0]['lastModifiedTime']
        self.assertEqual(end_time > first_Time > start_time, True, '查询结果的lastModifiedTime不包含在起始时间内，查询结果不正确')


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

Class description:
Custom view mixin which adds context data to the view, based on loaded plugins. This allows rendered pages to be augmented by loaded plugins.

Method signatures and docstrings:
- def get_plugin_panels(self, ctx): Return a list of extra 'plugin panels' associated with this view.
- def get_context_data(self, **kwargs): Add plugin context data to the view.

Implement the Python class `InvenTreePluginViewMixin` described below.

Class description:
Custom view mixin which adds context data to the view, based on loaded plugins. This allows rendered pages to be augmented by loaded plugins.

Method signatures and docstrings:
- def get_plugin_panels(self, ctx): Return a list of extra 'plugin panels' associated with this view.
- def get_context_data(self, **kwargs): Add plugin context data to the view.

<|skeleton|>
class InvenTreePluginViewMixin:
    """Custom view mixin which adds context data to the view, based on loaded plugins. This allows rendered pages to be augmented by loaded plugins."""

    def get_plugin_panels(self, ctx):
        """Return a list of extra 'plugin panels' associated with this view."""
        <|body_0|>

    def get_context_data(self, **kwargs):
        """Add plugin context data to the view."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        panels = []
        for plug in registry.with_mixin('panel', active=True):
            try:
                panels += plug.render_panels(self, self.request, ctx)
            except Exception:
                log_error(self.request.path)
                logger.error(f"Plugin '{plug.slug}' could not render custom panels at '{self.request.path}'")
        return panels
<|end_body_0|>

<|body_start_1|>
        ctx = super().get_context_data(**kwargs)
        if settings.PLUGINS_ENABLED:
            ctx['plugin_panels'] = self.get_plugin_panels(ctx)
        return ctx
<|end_body_1|>

Solution:
class InvenTreePluginViewMixin:
    """Custom view mixin which adds context data to the view, based on loaded plugins. This allows rendered pages to be augmented by loaded plugins."""

    def get_plugin_panels(self, ctx):
        """Return a list of extra 'plugin panels' associated with this view."""
        panels = []
        for plug in registry.with_mixin('panel', active=True):
            try:
                panels += plug.render_panels(self, self.request, ctx)
            except Exception:
                log_error(self.request.path)
                logger.error(f"Plugin '{plug.slug}' could not render custom panels at '{self.request.path}'")
        return panels

    def get_context_data(self, **kwargs):
        """Add plugin context data to the view."""
        ctx = super().get_context_data(**kwargs)
        if settings.PLUGINS_ENABLED:
            ctx['plugin_panels'] = self.get_plugin_panels(ctx)
        return ctx


open

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

Class description:
Klasse zum Einlesen der Wertetabellen

Method signatures and docstrings:
- def __init__(self, competition_folder: str, settings: SettingsTable, database: Database, station, group): Konstruktor. Args: competition_folder (str): Ordner der Veranstaltung settings (SettingsTable): Einstellungen database (Database): Datenbank station (typing.Dict): Station group (typing.Dict): Riege
- def open(self) -> bool: Öffnen der Tabelle und Auslesen der Werte Returns: bool: True, wenn erfolgreich
- def process_row(self, row: int, row_data: typing.Dict[str, typing.Any]): Methode zum Auslesen einer Zeile Args: row (int): Zeilennummer row_data (typing.Dict[str, typing.Any]): Daten der Zeile

Implement the Python class `ValuesInputTable` described below.

Class description:
Klasse zum Einlesen der Wertetabellen

Method signatures and docstrings:
- def __init__(self, competition_folder: str, settings: SettingsTable, database: Database, station, group): Konstruktor. Args: competition_folder (str): Ordner der Veranstaltung settings (SettingsTable): Einstellungen database (Database): Datenbank station (typing.Dict): Station group (typing.Dict): Riege
- def open(self) -> bool: Öffnen der Tabelle und Auslesen der Werte Returns: bool: True, wenn erfolgreich
- def process_row(self, row: int, row_data: typing.Dict[str, typing.Any]): Methode zum Auslesen einer Zeile Args: row (int): Zeilennummer row_data (typing.Dict[str, typing.Any]): Daten der Zeile

<|skeleton|>
class ValuesInputTable:
    """Klasse zum Einlesen der Wertetabellen"""

    def __init__(self, competition_folder: str, settings: SettingsTable, database: Database, station, group):
        """Konstruktor. Args: competition_folder (str): Ordner der Veranstaltung settings (SettingsTable): Einstellungen database (Database): Datenbank station (typing.Dict): Station group (typing.Dict): Riege"""
        <|body_0|>

    def open(self) -> bool:
        """Öffnen der Tabelle und Auslesen der Werte Returns: bool: True, wenn erfolgreich"""
        <|body_1|>

    def process_row(self, row: int, row_data: typing.Dict[str, typing.Any]):
        """Methode zum Auslesen einer Zeile Args: row (int): Zeilennummer row_data (typing.Dict[str, typing.Any]): Daten der Zeile"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        self.settings = settings
        self.database = database
        self.station = station
        self.group = group
        self.table_reader: TableReader = None
        self.status = logging.INFO
        filename = self.settings['values_input_file'] % {'station': self.station[STATION_SHORT], 'riege': self.group[GROUP_NAME]}
        Table.__init__(self, competition_folder, filename)
<|end_body_0|>

<|body_start_1|>
        if not Table.open(self):
            self.status = logging.ERROR
            return False
        try:
            reader = TableReader.from_settings(self, self.settings, 'values_input')
            if not reader.read(self.process_row):
                self.status = logging.ERROR
        except:
            logging.exception('Fehler beim Auslesen der Daten aus der Tabelle %s', self.filename)
            self.status = logging.ERROR
            return False
        return True
<|end_body_1|>

<|body_start_2|>
        attendee = self.database.filter_attendee(row_data, self.settings['values_input_required'])
        if not attendee:
            logging.warning('Zeile %d der Datei %s konnte nicht eindeutig zugewiesen werden.', row, self.filename)
            self.status = logging.WARNING
            return
        for key, value in row_data.items():
            if key in self.station[STATION_COLUMNS]:
                attendee[key] = value
<|end_body_2|>

Solution:
class ValuesInputTable:
    """Klasse zum Einlesen der Wertetabellen"""

    def __init__(self, competition_folder: str, settings: SettingsTable, database: Database, station, group):
        """Konstruktor. Args: competition_folder (str): Ordner der Veranstaltung settings (SettingsTable): Einstellungen database (Database): Datenbank station (typing.Dict): Station group (typing.Dict): Riege"""
        self.settings = settings
        self.database = database
        self.station = station
        self.group = group
        self.table_reader: TableReader = None
        self.status = logging.INFO
        filename = self.settings['values_input_file'] % {'station': self.station[STATION_SHORT], 'riege': self.group[GROUP_NAME]}
        Table.__init__(self, competition_folder, filename)

    def open(self) -> bool:
        """Öffnen der Tabelle und Auslesen der Werte Returns: bool: True, wenn erfolgreich"""
        if not Table.open(self):
            self.status = logging.ERROR
            return False
        try:
            reader = TableReader.from_settings(self, self.settings, 'values_input')
            if not reader.read(self.process_row):
                self.status = logging.ERROR
        except:
            logging.exception('Fehler beim Auslesen der Daten aus der Tabelle %s', self.filename)
            self.status = logging.ERROR
            return False
        return True

    def process_row(self, row: int, row_data: typing.Dict[str, typing.Any]):
        """Methode zum Auslesen einer Zeile Args: row (int): Zeilennummer row_data (typing.Dict[str, typing.Any]): Daten der Zeile"""
        attendee = self.database.filter_attendee(row_data, self.settings['values_input_required'])
        if not attendee:
            logging.warning('Zeile %d der Datei %s konnte nicht eindeutig zugewiesen werden.', row, self.filename)
            self.status = logging.WARNING
            return
        for key, value in row_data.items():
            if key in self.station[STATION_COLUMNS]:
                attendee[key] = value


create

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

Class description:
The serializer responsible for the Question object :author: Claas Voelcker

Method signatures and docstrings:
- def to_representation(self, obj): Appends additional information to the model. :param: obj: The object that should be serialized (Question) :return: value: a valid json object containing all required fields
- def create(self, validated_data): Serializer that governs the dispatch to specific class serializers :param validated_data: the data to be serialized :return: serialized representation

Implement the Python class `QuestionSerializer` described below.

Class description:
The serializer responsible for the Question object :author: Claas Voelcker

Method signatures and docstrings:
- def to_representation(self, obj): Appends additional information to the model. :param: obj: The object that should be serialized (Question) :return: value: a valid json object containing all required fields
- def create(self, validated_data): Serializer that governs the dispatch to specific class serializers :param validated_data: the data to be serialized :return: serialized representation

<|skeleton|>
class QuestionSerializer:
    """The serializer responsible for the Question object :author: Claas Voelcker"""

    def to_representation(self, obj):
        """Appends additional information to the model. :param: obj: The object that should be serialized (Question) :return: value: a valid json object containing all required fields"""
        <|body_0|>

    def create(self, validated_data):
        """Serializer that governs the dispatch to specific class serializers :param validated_data: the data to be serialized :return: serialized representation"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        course_module = obj.module
        value = super(QuestionSerializer, self).to_representation(obj)
        value['type'] = obj.__class__.__name__
        user = self.context['request'].user
        value['progress'] = []
        answered_question_before = True
        for course_module in obj.module.course.module_set.all():
            module_set = []
            for question in course_module.question_set.all():
                if answered_question_before and question.try_set.filter(solved=True, user=user).exists():
                    module_set.append({'solved': True, 'title': question.title})
                else:
                    answered_question_before = False
                    module_set.append({'solved': False, 'title': question.title})
            value['progress'].append(module_set)
        value['last_question'] = obj.is_last_question()
        value['last_module'] = course_module.is_last_module()
        value['learning_text'] = course_module.learning_text
        serializer = obj.get_serializer()
        value['question_body'] = serializer(obj).data
        value['solved'] = obj.try_set.filter(solved=True, user=user).exists()
        return value
<|end_body_0|>

<|body_start_1|>
        question_type = validated_data.pop('type')
        if question_type == 'multiple_choice':
            MultipleChoiceQuestionSerializer().create(validated_data)
        elif question_type == 'info_text':
            InformationTextSerializer().create(validated_data)
        elif question_type == 'info_text_youtube':
            InformationYoutubeSerializer().create(validated_data)
        else:
            raise ParseError(detail='{} is not a valid question type'.format(question_type))
<|end_body_1|>

Solution:
class QuestionSerializer:
    """The serializer responsible for the Question object :author: Claas Voelcker"""

    def to_representation(self, obj):
        """Appends additional information to the model. :param: obj: The object that should be serialized (Question) :return: value: a valid json object containing all required fields"""
        course_module = obj.module
        value = super(QuestionSerializer, self).to_representation(obj)
        value['type'] = obj.__class__.__name__
        user = self.context['request'].user
        value['progress'] = []
        answered_question_before = True
        for course_module in obj.module.course.module_set.all():
            module_set = []
            for question in course_module.question_set.all():
                if answered_question_before and question.try_set.filter(solved=True, user=user).exists():
                    module_set.append({'solved': True, 'title': question.title})
                else:
                    answered_question_before = False
                    module_set.append({'solved': False, 'title': question.title})
            value['progress'].append(module_set)
        value['last_question'] = obj.is_last_question()
        value['last_module'] = course_module.is_last_module()
        value['learning_text'] = course_module.learning_text
        serializer = obj.get_serializer()
        value['question_body'] = serializer(obj).data
        value['solved'] = obj.try_set.filter(solved=True, user=user).exists()
        return value

    def create(self, validated_data):
        """Serializer that governs the dispatch to specific class serializers :param validated_data: the data to be serialized :return: serialized representation"""
        question_type = validated_data.pop('type')
        if question_type == 'multiple_choice':
            MultipleChoiceQuestionSerializer().create(validated_data)
        elif question_type == 'info_text':
            InformationTextSerializer().create(validated_data)
        elif question_type == 'info_text_youtube':
            InformationYoutubeSerializer().create(validated_data)
        else:
            raise ParseError(detail='{} is not a valid question type'.format(question_type))


learn

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

Class description:
A multilayer perceptron based on the starter tutorial at pytorch: https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py

Method signatures and docstrings:
- def __init__(self, input_size, hidden_dim, num_layers=1, activation_function=torch.relu, learning_rate=0.001, decay_factor=0.5, momentum=0.9): A simple multi layer network for binary classification :param input_size: the dimensionality of the feature vectors to be input :param hidden_dim: the number of neurons used in each layers :param num_layers: number of layers in the network :param activation_function: the nonlinearity used after each layer except the last :param learning_rate: coefficient for gradient decent :param decay_factor: coefficient for scheduled learning_rate decrease per epoch :param momentum: momentum coefficient for gradient decent
- def forward(self, x): A forward pass of the network to classify a given tweet :param x: a feature vector representing a tweet :return: a 1d tensor of predicted classes (between 1 for informative, 0 for not)
- def learn(self, X_train, y_train, epochs=3): Train the network on a labeled dataset :param X_train: a tensor of features :param y_train: a tensor of labels :param epochs: an int, number of epochs to learn for
- def get_accuracy(self, X_test, y_test): Get the accuracy of the model on some test set :param X_test: a tensor of features :param y_test: a tensor of labels :return: a float, the accuracy (number of correct predictions out of total)

Implement the Python class `MLP` described below.

Class description:
A multilayer perceptron based on the starter tutorial at pytorch: https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py

Method signatures and docstrings:
- def __init__(self, input_size, hidden_dim, num_layers=1, activation_function=torch.relu, learning_rate=0.001, decay_factor=0.5, momentum=0.9): A simple multi layer network for binary classification :param input_size: the dimensionality of the feature vectors to be input :param hidden_dim: the number of neurons used in each layers :param num_layers: number of layers in the network :param activation_function: the nonlinearity used after each layer except the last :param learning_rate: coefficient for gradient decent :param decay_factor: coefficient for scheduled learning_rate decrease per epoch :param momentum: momentum coefficient for gradient decent
- def forward(self, x): A forward pass of the network to classify a given tweet :param x: a feature vector representing a tweet :return: a 1d tensor of predicted classes (between 1 for informative, 0 for not)
- def learn(self, X_train, y_train, epochs=3): Train the network on a labeled dataset :param X_train: a tensor of features :param y_train: a tensor of labels :param epochs: an int, number of epochs to learn for
- def get_accuracy(self, X_test, y_test): Get the accuracy of the model on some test set :param X_test: a tensor of features :param y_test: a tensor of labels :return: a float, the accuracy (number of correct predictions out of total)

<|skeleton|>
class MLP:
    """A multilayer perceptron based on the starter tutorial at pytorch: https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py"""

    def __init__(self, input_size, hidden_dim, num_layers=1, activation_function=torch.relu, learning_rate=0.001, decay_factor=0.5, momentum=0.9):
        """A simple multi layer network for binary classification :param input_size: the dimensionality of the feature vectors to be input :param hidden_dim: the number of neurons used in each layers :param num_layers: number of layers in the network :param activation_function: the nonlinearity used after each layer except the last :param learning_rate: coefficient for gradient decent :param decay_factor: coefficient for scheduled learning_rate decrease per epoch :param momentum: momentum coefficient for gradient decent"""
        <|body_0|>

    def forward(self, x):
        """A forward pass of the network to classify a given tweet :param x: a feature vector representing a tweet :return: a 1d tensor of predicted classes (between 1 for informative, 0 for not)"""
        <|body_1|>

    def learn(self, X_train, y_train, epochs=3):
        """Train the network on a labeled dataset :param X_train: a tensor of features :param y_train: a tensor of labels :param epochs: an int, number of epochs to learn for"""
        <|body_2|>

    def get_accuracy(self, X_test, y_test):
        """Get the accuracy of the model on some test set :param X_test: a tensor of features :param y_test: a tensor of labels :return: a float, the accuracy (number of correct predictions out of total)"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        super(MLP, self).__init__()
        self.f = activation_function
        self.fc_first = nn.Linear(input_size, hidden_dim)
        self.layers = []
        for i in range(num_layers):
            self.layers.append(nn.Linear(hidden_dim, hidden_dim))
        self.fc_last = nn.Linear(hidden_dim, 1)
        self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
        self.to(self.device)
        for i in range(len(self.layers)):
            self.layers[i].to(self.device)
        self.criterion = nn.BCELoss()
        self.optimizer = optim.SGD(self.parameters(), lr=learning_rate, momentum=momentum)
        self.scheduler = StepLR(self.optimizer, step_size=1, gamma=decay_factor)
<|end_body_0|>

<|body_start_1|>
        x = self.f(self.fc_first(x))
        for i in range(len(self.layers)):
            x = self.f(self.layers[i](x))
        x = torch.sigmoid(self.fc_last(x))
        return x
<|end_body_1|>

<|body_start_2|>
        trainset = utils.TensorDataset(X_train, y_train)
        trainloader = utils.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2)
        for epoch in range(epochs):
            print('epoch:', epoch, 'learning rate:', self.scheduler.get_lr())
            running_loss = 0.0
            for j, data in enumerate(trainloader, 0):
                inputs, labels = (data[0].to(self.device), data[1].to(self.device))
                self.optimizer.zero_grad()
                outputs = self(inputs)
                loss = self.criterion(outputs.reshape(-1), labels)
                loss.backward()
                self.optimizer.step()
                running_loss += loss.item()
                if j % 200 == 199:
                    print('[%d, %5d] loss: %.3f' % (epoch + 1, j + 1, running_loss / 200))
                    running_loss = 0.0
            self.scheduler.step()
<|end_body_2|>

<|body_start_3|>
        testset = utils.TensorDataset(X_test, y_test)
        testloader = utils.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2)
        correct = 0
        total = 0
        with torch.no_grad():
            for data in testloader:
                inputs, labels = (data[0].to(self.device), data[1].to(self.device))
                outputs = self(inputs)
                predictions = torch.round(outputs).reshape(-1)
                total += labels.size(0)
                correct += (predictions == labels).sum().item()
        return correct / total
<|end_body_3|>

Solution:
class MLP:
    """A multilayer perceptron based on the starter tutorial at pytorch: https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py"""

    def __init__(self, input_size, hidden_dim, num_layers=1, activation_function=torch.relu, learning_rate=0.001, decay_factor=0.5, momentum=0.9):
        """A simple multi layer network for binary classification :param input_size: the dimensionality of the feature vectors to be input :param hidden_dim: the number of neurons used in each layers :param num_layers: number of layers in the network :param activation_function: the nonlinearity used after each layer except the last :param learning_rate: coefficient for gradient decent :param decay_factor: coefficient for scheduled learning_rate decrease per epoch :param momentum: momentum coefficient for gradient decent"""
        super(MLP, self).__init__()
        self.f = activation_function
        self.fc_first = nn.Linear(input_size, hidden_dim)
        self.layers = []
        for i in range(num_layers):
            self.layers.append(nn.Linear(hidden_dim, hidden_dim))
        self.fc_last = nn.Linear(hidden_dim, 1)
        self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
        self.to(self.device)
        for i in range(len(self.layers)):
            self.layers[i].to(self.device)
        self.criterion = nn.BCELoss()
        self.optimizer = optim.SGD(self.parameters(), lr=learning_rate, momentum=momentum)
        self.scheduler = StepLR(self.optimizer, step_size=1, gamma=decay_factor)

    def forward(self, x):
        """A forward pass of the network to classify a given tweet :param x: a feature vector representing a tweet :return: a 1d tensor of predicted classes (between 1 for informative, 0 for not)"""
        x = self.f(self.fc_first(x))
        for i in range(len(self.layers)):
            x = self.f(self.layers[i](x))
        x = torch.sigmoid(self.fc_last(x))
        return x

    def learn(self, X_train, y_train, epochs=3):
        """Train the network on a labeled dataset :param X_train: a tensor of features :param y_train: a tensor of labels :param epochs: an int, number of epochs to learn for"""
        trainset = utils.TensorDataset(X_train, y_train)
        trainloader = utils.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2)
        for epoch in range(epochs):
            print('epoch:', epoch, 'learning rate:', self.scheduler.get_lr())
            running_loss = 0.0
            for j, data in enumerate(trainloader, 0):
                inputs, labels = (data[0].to(self.device), data[1].to(self.device))
                self.optimizer.zero_grad()
                outputs = self(inputs)
                loss = self.criterion(outputs.reshape(-1), labels)
                loss.backward()
                self.optimizer.step()
                running_loss += loss.item()
                if j % 200 == 199:
                    print('[%d, %5d] loss: %.3f' % (epoch + 1, j + 1, running_loss / 200))
                    running_loss = 0.0
            self.scheduler.step()

    def get_accuracy(self, X_test, y_test):
        """Get the accuracy of the model on some test set :param X_test: a tensor of features :param y_test: a tensor of labels :return: a float, the accuracy (number of correct predictions out of total)"""
        testset = utils.TensorDataset(X_test, y_test)
        testloader = utils.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2)
        correct = 0
        total = 0
        with torch.no_grad():
            for data in testloader:
                inputs, labels = (data[0].to(self.device), data[1].to(self.device))
                outputs = self(inputs)
                predictions = torch.round(outputs).reshape(-1)
                total += labels.size(0)
                correct += (predictions == labels).sum().item()
        return correct / total


decode

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

Class description:
Class that creates JWT tokens for users.

Method signatures and docstrings:
- def __init__(self, jwt_secret, jwt_issuer, jwt_audiences, default_lifespan=None): Initializes self. Args: jwt_secret (str): The symmetric secret for signing tokens. jwt_issuer (str): The issuer string to use ("who issued this token?"). jwt_audiences (List[str]): The audiences list to use ("who should accept this token?"). default_lifespan(datetime.timedelta): if no lifespan is passed to the create* methods, this will be used. Returns: None: None.
- def create_for_user(self, user, lifespan=None): Creates a token for a user. Args: user (nest_py.flask.accounts.user.NestUser): The user. lifespan (datetime.timedelta): How long the token should be valid. Or None to use the default_lifespan
- def create_for_system_operation_as_user(self, nest_id, lifespan=None, given_name='Nest', family_name='System', thumb_url='', username='nestsysteminternal'): Creates a token for a system operation performed on a user's behalf. Args: nest_id(NestId): The user's id. lifespan (Optional(datetime.timedelta)): How long the token should be valid. given_name (Optional[str]): A given name to use on the token. family_name (Optional[str]): A family name to use on the token. thumb_url (Optional[str]): A thumbnail URL to use on the token. username (Optional[str]): A username to use on the token.
- def decode(self, token): token(str): A jwt token, generated by a compatible TokenAgent returns a TokenPayload. Returns None if the token could not be decoded. Will return a TokenPayload if it is expired.

Implement the Python class `TokenAgent` described below.

Class description:
Class that creates JWT tokens for users.

Method signatures and docstrings:
- def __init__(self, jwt_secret, jwt_issuer, jwt_audiences, default_lifespan=None): Initializes self. Args: jwt_secret (str): The symmetric secret for signing tokens. jwt_issuer (str): The issuer string to use ("who issued this token?"). jwt_audiences (List[str]): The audiences list to use ("who should accept this token?"). default_lifespan(datetime.timedelta): if no lifespan is passed to the create* methods, this will be used. Returns: None: None.
- def create_for_user(self, user, lifespan=None): Creates a token for a user. Args: user (nest_py.flask.accounts.user.NestUser): The user. lifespan (datetime.timedelta): How long the token should be valid. Or None to use the default_lifespan
- def create_for_system_operation_as_user(self, nest_id, lifespan=None, given_name='Nest', family_name='System', thumb_url='', username='nestsysteminternal'): Creates a token for a system operation performed on a user's behalf. Args: nest_id(NestId): The user's id. lifespan (Optional(datetime.timedelta)): How long the token should be valid. given_name (Optional[str]): A given name to use on the token. family_name (Optional[str]): A family name to use on the token. thumb_url (Optional[str]): A thumbnail URL to use on the token. username (Optional[str]): A username to use on the token.
- def decode(self, token): token(str): A jwt token, generated by a compatible TokenAgent returns a TokenPayload. Returns None if the token could not be decoded. Will return a TokenPayload if it is expired.

<|skeleton|>
class TokenAgent:
    """Class that creates JWT tokens for users."""

    def __init__(self, jwt_secret, jwt_issuer, jwt_audiences, default_lifespan=None):
        """Initializes self. Args: jwt_secret (str): The symmetric secret for signing tokens. jwt_issuer (str): The issuer string to use ("who issued this token?"). jwt_audiences (List[str]): The audiences list to use ("who should accept this token?"). default_lifespan(datetime.timedelta): if no lifespan is passed to the create* methods, this will be used. Returns: None: None."""
        <|body_0|>

    def create_for_user(self, user, lifespan=None):
        """Creates a token for a user. Args: user (nest_py.flask.accounts.user.NestUser): The user. lifespan (datetime.timedelta): How long the token should be valid. Or None to use the default_lifespan"""
        <|body_1|>

    def create_for_system_operation_as_user(self, nest_id, lifespan=None, given_name='Nest', family_name='System', thumb_url='', username='nestsysteminternal'):
        """Creates a token for a system operation performed on a user's behalf. Args: nest_id(NestId): The user's id. lifespan (Optional(datetime.timedelta)): How long the token should be valid. given_name (Optional[str]): A given name to use on the token. family_name (Optional[str]): A family name to use on the token. thumb_url (Optional[str]): A thumbnail URL to use on the token. username (Optional[str]): A username to use on the token."""
        <|body_2|>

    def decode(self, token):
        """token(str): A jwt token, generated by a compatible TokenAgent returns a TokenPayload. Returns None if the token could not be decoded. Will return a TokenPayload if it is expired."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        self.jwt_secret = jwt_secret
        self.jwt_issuer = jwt_issuer
        self.jwt_audiences = jwt_audiences
        self.default_lifespan = default_lifespan
        return
<|end_body_0|>

<|body_start_1|>
        if lifespan is None:
            lifespan = self.default_lifespan
        print('TokenAgent.create_for_user: ' + str(user.to_jdata()))
        token_payload = create_user_payload_now(user, self.jwt_issuer, self.jwt_audiences, lifespan)
        print('TokenAgent created payload: ' + str(token_payload.data))
        token = token_payload.to_jwt_token(self.jwt_secret)
        print('TokenAgent created token: ' + str(token))
        return token
<|end_body_1|>

<|body_start_2|>
        nest_user = NestUser(nest_id, username, given_name, family_name, thumb_url=thumb_url)
        token = self.create_for_user(nest_user, lifespan=lifespan)
        return token
<|end_body_2|>

<|body_start_3|>
        audience = self.jwt_audiences[0]
        tkn_payload = decode_token(token, self.jwt_secret, audience, self.jwt_issuer)
        return tkn_payload
<|end_body_3|>

Solution:
class TokenAgent:
    """Class that creates JWT tokens for users."""

    def __init__(self, jwt_secret, jwt_issuer, jwt_audiences, default_lifespan=None):
        """Initializes self. Args: jwt_secret (str): The symmetric secret for signing tokens. jwt_issuer (str): The issuer string to use ("who issued this token?"). jwt_audiences (List[str]): The audiences list to use ("who should accept this token?"). default_lifespan(datetime.timedelta): if no lifespan is passed to the create* methods, this will be used. Returns: None: None."""
        self.jwt_secret = jwt_secret
        self.jwt_issuer = jwt_issuer
        self.jwt_audiences = jwt_audiences
        self.default_lifespan = default_lifespan
        return

    def create_for_user(self, user, lifespan=None):
        """Creates a token for a user. Args: user (nest_py.flask.accounts.user.NestUser): The user. lifespan (datetime.timedelta): How long the token should be valid. Or None to use the default_lifespan"""
        if lifespan is None:
            lifespan = self.default_lifespan
        print('TokenAgent.create_for_user: ' + str(user.to_jdata()))
        token_payload = create_user_payload_now(user, self.jwt_issuer, self.jwt_audiences, lifespan)
        print('TokenAgent created payload: ' + str(token_payload.data))
        token = token_payload.to_jwt_token(self.jwt_secret)
        print('TokenAgent created token: ' + str(token))
        return token

    def create_for_system_operation_as_user(self, nest_id, lifespan=None, given_name='Nest', family_name='System', thumb_url='', username='nestsysteminternal'):
        """Creates a token for a system operation performed on a user's behalf. Args: nest_id(NestId): The user's id. lifespan (Optional(datetime.timedelta)): How long the token should be valid. given_name (Optional[str]): A given name to use on the token. family_name (Optional[str]): A family name to use on the token. thumb_url (Optional[str]): A thumbnail URL to use on the token. username (Optional[str]): A username to use on the token."""
        nest_user = NestUser(nest_id, username, given_name, family_name, thumb_url=thumb_url)
        token = self.create_for_user(nest_user, lifespan=lifespan)
        return token

    def decode(self, token):
        """token(str): A jwt token, generated by a compatible TokenAgent returns a TokenPayload. Returns None if the token could not be decoded. Will return a TokenPayload if it is expired."""
        audience = self.jwt_audiences[0]
        tkn_payload = decode_token(token, self.jwt_secret, audience, self.jwt_issuer)
        return tkn_payload


put

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

Class description:
Implement the WAN class.

Method signatures and docstrings:
- def get(self, interface): Returns status of WAN simulation on the given interface.
- def post(self, interface): Start WAN simulation on given interface or add rule to running WAN simulation.
- def put(self, interface): Update a WAN simulation on given interface
- def delete(self, interface): Stop WAN Simulation on given interface

Implement the Python class `WAN` described below.

Class description:
Implement the WAN class.

Method signatures and docstrings:
- def get(self, interface): Returns status of WAN simulation on the given interface.
- def post(self, interface): Start WAN simulation on given interface or add rule to running WAN simulation.
- def put(self, interface): Update a WAN simulation on given interface
- def delete(self, interface): Stop WAN Simulation on given interface

<|skeleton|>
class WAN:

    def get(self, interface):
        """Returns status of WAN simulation on the given interface."""
        <|body_0|>

    def post(self, interface):
        """Start WAN simulation on given interface or add rule to running WAN simulation."""
        <|body_1|>

    def put(self, interface):
        """Update a WAN simulation on given interface"""
        <|body_2|>

    def delete(self, interface):
        """Stop WAN Simulation on given interface"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        AnomalyEngine = app.config['AnomalyEngine']
        simulation = AnomalyEngine.lookup_simulation(interface)
        if simulation == None:
            logging.info("Can't find interface " + interface)
            api.abort(400, "Interface {} doesn't exist".format(interface))
        if simulation.is_running():
            return (simulation.status(), 201)
        else:
            return ({'message': 'No simulation running'}, 200)
<|end_body_0|>

<|body_start_1|>
        AnomalyEngine = app.config['AnomalyEngine']
        interface_simulation = AnomalyEngine.lookup_simulation(interface)
        args = simulation_parser.parse_args()
        params = {key: value for key, value in args.items() if value}
        if interface_simulation == None:
            logging.info("Can't find interface " + interface)
            api.abort(400, "Interface {} doesn't exist".format(interface))
        logging.info('Using interface ' + interface + ' for the WAN simulation')
        logging.info('Using the following simulation params: ' + json.dumps(params))
        if AnomalyEngine.simulation_running(interface_simulation):
            logging.info('There is already a simulation running on interface ' + interface + '. Trying to add rule.')
            if not interface_simulation.network_conflict(params):
                error = AnomalyEngine.start_simulation(interface_simulation, params, add_rule=True)
                if error:
                    api.abort(500, 'Error during start of simulation: {}'.format(error))
            else:
                api.abort(406, 'There is already a running simulation using the network you specified')
            return (interface_simulation.status(), 201)
        AnomalyEngine.start_simulation(interface_simulation, params)
        return (interface_simulation.status(), 200)
<|end_body_1|>

<|body_start_2|>
        AnomalyEngine = app.config['AnomalyEngine']
        simulation = AnomalyEngine.lookup_simulation(interface)
        args = simulation_parser.parse_args()
        params = {key: value for key, value in args.items() if value}
        if simulation == None:
            logging.info("Can't find interface " + interface)
            api.abort(400, "Interface {} doesn't exist".format(interface))
        if not simulation.is_running():
            api.abort(405, 'There is no simulation running on interface {}'.format(interface))
        logging.info('Updating WAN simulation on ' + interface)
        logging.info('Using the following simulation params: ' + json.dumps(params))
        error = AnomalyEngine.start_simulation(simulation, params, update=True)
        if error:
            api.abort(500, 'Error during execution: {}'.format(error))
        return (simulation.status(), 201)
<|end_body_2|>

<|body_start_3|>
        AnomalyEngine = app.config['AnomalyEngine']
        simulation = AnomalyEngine.lookup_simulation(interface)
        if simulation == None:
            logging.info("Can't find interface " + interface)
            api.abort(400, "Interface {} doesn't exist".format(interface))
        if simulation.is_running():
            error = simulation.stop()
            if error:
                api.abort(500, 'Error during stop operation: {}'.format(error))
        else:
            api.abort(404, 'There is no simulation running on interface {}'.format(interface))
<|end_body_3|>

Solution:
class WAN:
    def get(self, interface):
        """Returns status of WAN simulation on the given interface."""
        AnomalyEngine = app.config['AnomalyEngine']
        simulation = AnomalyEngine.lookup_simulation(interface)
        if simulation == None:
            logging.info("Can't find interface " + interface)
            api.abort(400, "Interface {} doesn't exist".format(interface))
        if simulation.is_running():
            return (simulation.status(), 201)
        else:
            return ({'message': 'No simulation running'}, 200)

    def post(self, interface):
        """Start WAN simulation on given interface or add rule to running WAN simulation."""
        AnomalyEngine = app.config['AnomalyEngine']
        interface_simulation = AnomalyEngine.lookup_simulation(interface)
        args = simulation_parser.parse_args()
        params = {key: value for key, value in args.items() if value}
        if interface_simulation == None:
            logging.info("Can't find interface " + interface)
            api.abort(400, "Interface {} doesn't exist".format(interface))
        logging.info('Using interface ' + interface + ' for the WAN simulation')
        logging.info('Using the following simulation params: ' + json.dumps(params))
        if AnomalyEngine.simulation_running(interface_simulation):
            logging.info('There is already a simulation running on interface ' + interface + '. Trying to add rule.')
            if not interface_simulation.network_conflict(params):
                error = AnomalyEngine.start_simulation(interface_simulation, params, add_rule=True)
                if error:
                    api.abort(500, 'Error during start of simulation: {}'.format(error))
            else:
                api.abort(406, 'There is already a running simulation using the network you specified')
            return (interface_simulation.status(), 201)
        AnomalyEngine.start_simulation(interface_simulation, params)
        return (interface_simulation.status(), 200)

    def put(self, interface):
        """Update a WAN simulation on given interface"""
        AnomalyEngine = app.config['AnomalyEngine']
        simulation = AnomalyEngine.lookup_simulation(interface)
        args = simulation_parser.parse_args()
        params = {key: value for key, value in args.items() if value}
        if simulation == None:
            logging.info("Can't find interface " + interface)
            api.abort(400, "Interface {} doesn't exist".format(interface))
        if not simulation.is_running():
            api.abort(405, 'There is no simulation running on interface {}'.format(interface))
        logging.info('Updating WAN simulation on ' + interface)
        logging.info('Using the following simulation params: ' + json.dumps(params))
        error = AnomalyEngine.start_simulation(simulation, params, update=True)
        if error:
            api.abort(500, 'Error during execution: {}'.format(error))
        return (simulation.status(), 201)

    def delete(self, interface):
        """Stop WAN Simulation on given interface"""
        AnomalyEngine = app.config['AnomalyEngine']
        simulation = AnomalyEngine.lookup_simulation(interface)
        if simulation == None:
            logging.info("Can't find interface " + interface)
            api.abort(400, "Interface {} doesn't exist".format(interface))
        if simulation.is_running():
            error = simulation.stop()
            if error:
                api.abort(500, 'Error during stop operation: {}'.format(error))
        else:
            api.abort(404, 'There is no simulation running on interface {}'.format(interface))


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

Class description:
Class for all ImageField type The __init__ should take optional parameters as bellow :param {string} resize_based_on: name of the field that should be resized :param {integer} width: width of the image resized :param {integer} height: height of the image resized

Method signatures and docstrings:
- def _compute_write(self, records): Control how a value of ImageField should be updated, when an ImageField field is updated should consider the case: - current field is parent field or child field: the parent field should be always update first, then update related child fields. :param {openerp.models.BaseModel} records: current working recordset
- def _refresh_cache(self, record): Refresh the cache of the child field to resize again based on new binary value from parent field or totally remove all if parent field is not set. :params {openerp.models.BaseModel} record: current recordset (one) to update value for binary field
- def _read_binary(self, storage, record, binary_uid): Internal method to read contents from binary field depending on storage configuration. :param {dict} storage: default storage configuration :param {openerp.models.BaseModel} record: current recordset to read data from :param {string} binary_uid: binary UID (file name) of binary file

Implement the Python class `ImageField` described below.

Class description:
Class for all ImageField type The __init__ should take optional parameters as bellow :param {string} resize_based_on: name of the field that should be resized :param {integer} width: width of the image resized :param {integer} height: height of the image resized

Method signatures and docstrings:
- def _compute_write(self, records): Control how a value of ImageField should be updated, when an ImageField field is updated should consider the case: - current field is parent field or child field: the parent field should be always update first, then update related child fields. :param {openerp.models.BaseModel} records: current working recordset
- def _refresh_cache(self, record): Refresh the cache of the child field to resize again based on new binary value from parent field or totally remove all if parent field is not set. :params {openerp.models.BaseModel} record: current recordset (one) to update value for binary field
- def _read_binary(self, storage, record, binary_uid): Internal method to read contents from binary field depending on storage configuration. :param {dict} storage: default storage configuration :param {openerp.models.BaseModel} record: current recordset to read data from :param {string} binary_uid: binary UID (file name) of binary file

<|skeleton|>
class ImageField:
    """Class for all ImageField type The __init__ should take optional parameters as bellow :param {string} resize_based_on: name of the field that should be resized :param {integer} width: width of the image resized :param {integer} height: height of the image resized"""

    def _compute_write(self, records):
        """Control how a value of ImageField should be updated, when an ImageField field is updated should consider the case: - current field is parent field or child field: the parent field should be always update first, then update related child fields. :param {openerp.models.BaseModel} records: current working recordset"""
        <|body_0|>

    def _refresh_cache(self, record):
        """Refresh the cache of the child field to resize again based on new binary value from parent field or totally remove all if parent field is not set. :params {openerp.models.BaseModel} record: current recordset (one) to update value for binary field"""
        <|body_1|>

    def _read_binary(self, storage, record, binary_uid):
        """Internal method to read contents from binary field depending on storage configuration. :param {dict} storage: default storage configuration :param {openerp.models.BaseModel} record: current recordset to read data from :param {string} binary_uid: binary UID (file name) of binary file"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        field_name = self.name
        for record in records:
            context = record.env.context
            binary_value = record[field_name]
            field_object = record._fields[field_name]
            parent_field = field_object._attrs.get('resize_based_on')
            if parent_field and (not record.env.context.get('refresh_image_cache')):
                record[parent_field] = binary_value
                return
            else:
                width = field_object._attrs.get('height')
                height = field_object._attrs.get('width')
                if width or height:
                    size = (height or 64, width or 64)
                    binary_value = image_resize_image(binary_value, size)
                self._write_binary(record, field_name, binary_value)
                for _name, _field in record._fields.items():
                    if not isinstance(_field, BinaryField):
                        continue
                    if _field._attrs.get('resize_based_on') == field_name:
                        _field._refresh_cache(record)
        return
<|end_body_0|>

<|body_start_1|>
        field = record._fields[self.name]
        parent_field = field._attrs.get('resize_based_on')
        _logger.debug('Refreshing Image Cache from the field %s of object %s id : %s' % (field.name, record._name, record.id))
        ctx = record.env.context.copy()
        ctx['refresh_image_cache'] = True
        ctx['bin_base64_%s' % field._attrs.get('resize_based_on')] = True
        resized_image = None
        if parent_field:
            original_binary = getattr(record, parent_field)
            size = (field._attrs.get('height'), field._attrs.get('width'))
            resized_image = image_resize_image(original_binary, size)
        record.with_context(**ctx)[field.name] = resized_image
<|end_body_1|>

<|body_start_2|>
        context = record.env.context
        field_name = self.name
        if not context.get('bin_size_%s' % field_name) and (not context.get('bin_base64_%s' % field_name)) and storage.external_storage_server:
            if context.get('bin_size'):
                context.pop('bin_size')
            return storage.get_url(binary_uid)
        else:
            return super(ImageField, self)._read_binary(storage, record, binary_uid)
<|end_body_2|>

Solution:
class ImageField:
    """Class for all ImageField type The __init__ should take optional parameters as bellow :param {string} resize_based_on: name of the field that should be resized :param {integer} width: width of the image resized :param {integer} height: height of the image resized"""

    def _compute_write(self, records):
        """Control how a value of ImageField should be updated, when an ImageField field is updated should consider the case: - current field is parent field or child field: the parent field should be always update first, then update related child fields. :param {openerp.models.BaseModel} records: current working recordset"""
        field_name = self.name
        for record in records:
            context = record.env.context
            binary_value = record[field_name]
            field_object = record._fields[field_name]
            parent_field = field_object._attrs.get('resize_based_on')
            if parent_field and (not record.env.context.get('refresh_image_cache')):
                record[parent_field] = binary_value
                return
            else:
                width = field_object._attrs.get('height')
                height = field_object._attrs.get('width')
                if width or height:
                    size = (height or 64, width or 64)
                    binary_value = image_resize_image(binary_value, size)
                self._write_binary(record, field_name, binary_value)
                for _name, _field in record._fields.items():
                    if not isinstance(_field, BinaryField):
                        continue
                    if _field._attrs.get('resize_based_on') == field_name:
                        _field._refresh_cache(record)
        return

    def _refresh_cache(self, record):
        """Refresh the cache of the child field to resize again based on new binary value from parent field or totally remove all if parent field is not set. :params {openerp.models.BaseModel} record: current recordset (one) to update value for binary field"""
        field = record._fields[self.name]
        parent_field = field._attrs.get('resize_based_on')
        _logger.debug('Refreshing Image Cache from the field %s of object %s id : %s' % (field.name, record._name, record.id))
        ctx = record.env.context.copy()
        ctx['refresh_image_cache'] = True
        ctx['bin_base64_%s' % field._attrs.get('resize_based_on')] = True
        resized_image = None
        if parent_field:
            original_binary = getattr(record, parent_field)
            size = (field._attrs.get('height'), field._attrs.get('width'))
            resized_image = image_resize_image(original_binary, size)
        record.with_context(**ctx)[field.name] = resized_image

    def _read_binary(self, storage, record, binary_uid):
        """Internal method to read contents from binary field depending on storage configuration. :param {dict} storage: default storage configuration :param {openerp.models.BaseModel} record: current recordset to read data from :param {string} binary_uid: binary UID (file name) of binary file"""
        context = record.env.context
        field_name = self.name
        if not context.get('bin_size_%s' % field_name) and (not context.get('bin_base64_%s' % field_name)) and storage.external_storage_server:
            if context.get('bin_size'):
                context.pop('bin_size')
            return storage.get_url(binary_uid)
        else:
            return super(ImageField, self)._read_binary(storage, record, binary_uid)


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

Class description:
install packages,uninstall packages ['post', 'delete']

Method signatures and docstrings:
- def post(self, request, format=None): install packages
- def delete(self, request, format=None): uninstall packages

Implement the Python class `packages` described below.

Class description:
install packages,uninstall packages ['post', 'delete']

Method signatures and docstrings:
- def post(self, request, format=None): install packages
- def delete(self, request, format=None): uninstall packages

<|skeleton|>
class packages:
    """install packages,uninstall packages ['post', 'delete']"""

    def post(self, request, format=None):
        """install packages"""
        <|body_0|>

    def delete(self, request, format=None):
        """uninstall packages"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        packagestr = request.data
        if packagestr['path'][-1] != '/':
            packagestr['path'] = packagestr['path'] + '/'
        package_dir = settings.PACKAGE_DIR
        if package_dir[-1] == '/':
            package_dir = package_dir[:-1]
        packagestr['path'] = package_dir + packagestr['path']
        cmd = 'rpm -ivh ' + packagestr['path'] + packagestr['filename']
        code, resultMSG = commands.getstatusoutput(cmd)
        if code != 0:
            return_error = {'errormsg': resultMSG, 'errorcode': code}
            return Response(return_error, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        MSG = {'message': resultMSG}
        return_dict = {'result': MSG}
        return Response(return_dict, status=status.HTTP_200_OK)
<|end_body_0|>

<|body_start_1|>
        packagestr = request.data
        if packagestr['forcedel'] is not True:
            cmd = 'rpm -e ' + packagestr['package']
        else:
            cmd = 'rpm -e ' + packagestr['package'] + ' --nodeps'
        code, result = commands.getstatusoutput(cmd)
        if code != 0:
            return_error = {'errormsg': result, 'errorcode': code}
            return Response(return_error, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        MSGlist = []
        MSGlist.append(packagestr['package'] + ':' + result)
        return Response(MSGlist, status=status.HTTP_200_OK)
<|end_body_1|>

Solution:
class packages:
    """install packages,uninstall packages ['post', 'delete']"""

    def post(self, request, format=None):
        """install packages"""
        packagestr = request.data
        if packagestr['path'][-1] != '/':
            packagestr['path'] = packagestr['path'] + '/'
        package_dir = settings.PACKAGE_DIR
        if package_dir[-1] == '/':
            package_dir = package_dir[:-1]
        packagestr['path'] = package_dir + packagestr['path']
        cmd = 'rpm -ivh ' + packagestr['path'] + packagestr['filename']
        code, resultMSG = commands.getstatusoutput(cmd)
        if code != 0:
            return_error = {'errormsg': resultMSG, 'errorcode': code}
            return Response(return_error, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        MSG = {'message': resultMSG}
        return_dict = {'result': MSG}
        return Response(return_dict, status=status.HTTP_200_OK)

    def delete(self, request, format=None):
        """uninstall packages"""
        packagestr = request.data
        if packagestr['forcedel'] is not True:
            cmd = 'rpm -e ' + packagestr['package']
        else:
            cmd = 'rpm -e ' + packagestr['package'] + ' --nodeps'
        code, result = commands.getstatusoutput(cmd)
        if code != 0:
            return_error = {'errormsg': result, 'errorcode': code}
            return Response(return_error, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        MSGlist = []
        MSGlist.append(packagestr['package'] + ':' + result)
        return Response(MSGlist, status=status.HTTP_200_OK)


isBalanced

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def isBalanced1(self, root: TreeNode) -> bool: 执行用时： 76 ms , 在所有 Python3 提交中击败了 31.32% 的用户 内存消耗： 19.9 MB , 在所有 Python3 提交中击败了 6.97% 的用户
- def isBalanced(self, root: TreeNode) -> bool: 执行用时： 60 ms , 在所有 Python3 提交中击败了 72.75% 的用户 内存消耗： 19.6 MB , 在所有 Python3 提交中击败了 36.65% 的用

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def isBalanced1(self, root: TreeNode) -> bool: 执行用时： 76 ms , 在所有 Python3 提交中击败了 31.32% 的用户 内存消耗： 19.9 MB , 在所有 Python3 提交中击败了 6.97% 的用户
- def isBalanced(self, root: TreeNode) -> bool: 执行用时： 60 ms , 在所有 Python3 提交中击败了 72.75% 的用户 内存消耗： 19.6 MB , 在所有 Python3 提交中击败了 36.65% 的用

<|skeleton|>
class Solution:

    def isBalanced1(self, root: TreeNode) -> bool:
        """执行用时： 76 ms , 在所有 Python3 提交中击败了 31.32% 的用户 内存消耗： 19.9 MB , 在所有 Python3 提交中击败了 6.97% 的用户"""
        <|body_0|>

    def isBalanced(self, root: TreeNode) -> bool:
        """执行用时： 60 ms , 在所有 Python3 提交中击败了 72.75% 的用户 内存消耗： 19.6 MB , 在所有 Python3 提交中击败了 36.65% 的用"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        def dfs(node, depth):
            left = depth
            if node.left:
                left = dfs(node.left, depth + 1)
            if left < 0:
                return left
            right = depth
            if node.right:
                right = dfs(node.right, depth + 1)
            if right < 0:
                return right
            if left - right > 1 or right - left > 1:
                return -1
            return max(left, right)
        if not root:
            return True
        res = dfs(root, 0)
        return res >= 0
<|end_body_0|>

<|body_start_1|>
        def height(root: TreeNode) -> int:
            if not root:
                return 0
            leftHeight = height(root.left)
            rightHeight = height(root.right)
            if leftHeight == -1 or rightHeight == -1 or abs(leftHeight - rightHeight) > 1:
                return -1
            else:
                return max(leftHeight, rightHeight) + 1
        return height(root) >= 0
<|end_body_1|>

Solution:
class Solution:
    def isBalanced1(self, root: TreeNode) -> bool:
        """执行用时： 76 ms , 在所有 Python3 提交中击败了 31.32% 的用户 内存消耗： 19.9 MB , 在所有 Python3 提交中击败了 6.97% 的用户"""
        def dfs(node, depth):
            left = depth
            if node.left:
                left = dfs(node.left, depth + 1)
            if left < 0:
                return left
            right = depth
            if node.right:
                right = dfs(node.right, depth + 1)
            if right < 0:
                return right
            if left - right > 1 or right - left > 1:
                return -1
            return max(left, right)
        if not root:
            return True
        res = dfs(root, 0)
        return res >= 0

    def isBalanced(self, root: TreeNode) -> bool:
        """执行用时： 60 ms , 在所有 Python3 提交中击败了 72.75% 的用户 内存消耗： 19.6 MB , 在所有 Python3 提交中击败了 36.65% 的用"""
        def height(root: TreeNode) -> int:
            if not root:
                return 0
            leftHeight = height(root.left)
            rightHeight = height(root.right)
            if leftHeight == -1 or rightHeight == -1 or abs(leftHeight - rightHeight) > 1:
                return -1
            else:
                return max(leftHeight, rightHeight) + 1
        return height(root) >= 0