Instruction:
Can you create a Python 3 function that
writes the end of the directory header at the current file position.

Response:
def write_end_of_directory(fp, dir_size, dir_offset, count):
    """
        Write zip file end of directory header at the current file position

        :param fp: the file point to which to write the header
        :param dir_size: the total size of the directory
        :param dir_offset: the start of the first directory header
        :param count: the count of files
    """
    fp.write(struct.pack('I', 0x06054b50))  # central directory header
    fp.write(struct.pack('H', 0))           # disk number
    fp.write(struct.pack('H', 0))           # disk number
    fp.write(struct.pack('H', count))       # number of files
    fp.write(struct.pack('H', count))       # number of files
    fp.write(struct.pack('I', dir_size))    # central directory size
    fp.write(struct.pack('I', dir_offset))  # central directory offset
    fp.write(struct.pack('H', 0))


Instruction:
How would you explain what the following Python 3 function does
def write_zip_fp(fp, data, properties, dir_data_list=None):
    assert data is not None or properties is not None
    # dir_data_list has the format: local file record offset, name, data length, crc32
    dir_data_list = list() if dir_data_list is None else dir_data_list
    dt = datetime.datetime.now()
    if data is not None:
        offset_data = fp.tell()
        def write_data(fp):
            numpy_start_pos = fp.tell()
            numpy.save(fp, data)
            numpy_end_pos = fp.tell()
            fp.seek(numpy_start_pos)
            data_c = numpy.require(data, dtype=data.dtype, requirements=["C_CONTIGUOUS"])
            header_data = fp.read((numpy_end_pos - numpy_start_pos) - data_c.nbytes)  # read the header
            data_crc32 = binascii.crc32(data_c.data, binascii.crc32(header_data)) & 0xFFFFFFFF
            fp.seek(numpy_end_pos)
            return data_crc32
        data_len, crc32 = write_local_file(fp, b"data.npy", write_data, dt)
        dir_data_list.append((offset_data, b"data.npy", data_len, crc32))
    if properties is not None:
        json_str = str()
        try:
            class JSONEncoder(json.JSONEncoder):
                def default(self, obj):
                    if isinstance(obj, Geometry.IntPoint) or isinstance(obj, Geometry.IntSize) or isinstance(obj, Geometry.IntRect) or isinstance(obj, Geometry.FloatPoint) or isinstance(obj, Geometry.FloatSize) or isinstance(obj, Geometry.FloatRect):
                        return tuple(obj)
                    else:
                        return json.JSONEncoder.default(self, obj)
            json_io = io.StringIO()
            json.dump(properties, json_io, cls=JSONEncoder)
            json_str = json_io.getvalue()
        except Exception as e:
            # catch exceptions to avoid corrupt zip files
            import traceback
            logging.error("Exception writing zip file %s" + str(e))
            traceback.print_exc()
            traceback.print_stack()
        def write_json(fp):
            json_bytes = bytes(json_str, 'ISO-8859-1')
            fp.write(json_bytes)
            return binascii.crc32(json_bytes) & 0xFFFFFFFF
        offset_json = fp.tell()
        json_len, json_crc32 = write_local_file(fp, b"metadata.json", write_json, dt)
        dir_data_list.append((offset_json, b"metadata.json", json_len, json_crc32))
    dir_offset = fp.tell()
    for offset, name_bytes, data_len, crc32 in dir_data_list:
        write_directory_data(fp, offset, name_bytes, data_len, crc32, dt)
    dir_size = fp.tell() - dir_offset
    write_end_of_directory(fp, dir_size, dir_offset, len(dir_data_list))
    fp.truncate()

Response: Writes a custom zip file of data and properties to the file.


Instruction:
Here you have a function in Python 3, explain what it does
def write_zip(file_path, data, properties):
    with open(file_path, "w+b") as fp:
        write_zip_fp(fp, data, properties)

Response: Writes a custom zip file to the file path


Instruction:
Write a Python 3 function that can
parse the zip file at fp and return a tuple of the local files directory headers and end of central directory entries.

Response:
def parse_zip(fp):
    """
        Parse the zip file headers at fp

        :param fp: the file pointer from which to parse the zip file
        :return: A tuple of local files, directory headers, and end of central directory

        The local files are dictionary where the keys are the local file offset and the
        values are each a tuple consisting of the name, data position, data length, and crc32.

        The directory headers are a dictionary where the keys are the names of the files
        and the values are a tuple consisting of the directory header position, and the
        associated local file position.

        The end of central directory is a tuple consisting of the location of the end of
        central directory header and the location of the first directory header.

        This method will seek to location 0 of fp and leave fp at end of file.
    """
    local_files = {}
    dir_files = {}
    eocd = None
    fp.seek(0)
    while True:
        pos = fp.tell()
        signature = struct.unpack('I', fp.read(4))[0]
        if signature == 0x04034b50:
            fp.seek(pos + 14)
            crc32 = struct.unpack('I', fp.read(4))[0]
            fp.seek(pos + 18)
            data_len = struct.unpack('I', fp.read(4))[0]
            fp.seek(pos + 26)
            name_len = struct.unpack('H', fp.read(2))[0]
            extra_len = struct.unpack('H', fp.read(2))[0]
            name_bytes = fp.read(name_len)
            fp.seek(extra_len, os.SEEK_CUR)
            data_pos = fp.tell()
            fp.seek(data_len, os.SEEK_CUR)
            local_files[pos] = (name_bytes, data_pos, data_len, crc32)
        elif signature == 0x02014b50:
            fp.seek(pos + 28)
            name_len = struct.unpack('H', fp.read(2))[0]
            extra_len = struct.unpack('H', fp.read(2))[0]
            comment_len = struct.unpack('H', fp.read(2))[0]
            fp.seek(pos + 42)
            pos2 = struct.unpack('I', fp.read(4))[0]
            name_bytes = fp.read(name_len)
            fp.seek(pos + 46 + name_len + extra_len + comment_len)
            dir_files[name_bytes] = (pos, pos2)
        elif signature == 0x06054b50:
            fp.seek(pos + 16)
            pos2 = struct.unpack('I', fp.read(4))[0]
            eocd = (pos, pos2)
            break
        else:
            raise IOError()
    return local_files, dir_files, eocd


Instruction:
Here you have a function in Python 3, explain what it does
def read_data(fp, local_files, dir_files, name_bytes):
    if name_bytes in dir_files:
        fp.seek(local_files[dir_files[name_bytes][1]][1])
        return numpy.load(fp)
    return None

Response: Read a numpy array from the zip file containing the data file.


Instruction:
Can you tell what is the following Python 3 function doing
def read_json(fp, local_files, dir_files, name_bytes):
    if name_bytes in dir_files:
        json_pos = local_files[dir_files[name_bytes][1]][1]
        json_len = local_files[dir_files[name_bytes][1]][2]
        fp.seek(json_pos)
        json_properties = fp.read(json_len)
        return json.loads(json_properties.decode("utf-8"))
    return None

Response: Read json properties from the zip file containing the name of the entry in the local_files directory.


Instruction:
Write a Python 3 function that can
rewrite the json properties in the zip file :param file_path: the file path to the zip file :param properties: the updated properties to write to the zip file This method will attempt to keep the data file within the zip file intact without rewriting it. However, if the data file is not the first item in the zip file, this method will rewrite it. The properties param must not change during this method. Callers should take care to ensure this does not happen.

Response:
def rewrite_zip(file_path, properties):
    """
        Rewrite the json properties in the zip file

        :param file_path: the file path to the zip file
        :param properties: the updated properties to write to the zip file

        This method will attempt to keep the data file within the zip
        file intact without rewriting it. However, if the data file is not the
        first item in the zip file, this method will rewrite it.

        The properties param must not change during this method. Callers should
        take care to ensure this does not happen.
    """
    with open(file_path, "r+b") as fp:
        local_files, dir_files, eocd = parse_zip(fp)
        # check to make sure directory has two files, named data.npy and metadata.json, and that data.npy is first
        # TODO: check compression, etc.
        if len(dir_files) == 2 and b"data.npy" in dir_files and b"metadata.json" in dir_files and dir_files[b"data.npy"][1] == 0:
            fp.seek(dir_files[b"metadata.json"][1])
            dir_data_list = list()
            local_file_pos = dir_files[b"data.npy"][1]
            local_file = local_files[local_file_pos]
            dir_data_list.append((local_file_pos, b"data.npy", local_file[2], local_file[3]))
            write_zip_fp(fp, None, properties, dir_data_list)
        else:
            data = None
            if b"data.npy" in dir_files:
                fp.seek(local_files[dir_files[b"data.npy"][1]][1])
                data = numpy.load(fp)
            fp.seek(0)
            write_zip_fp(fp, data, properties)


Instruction:
How would you explain what the following Python 3 function does
def is_matching(cls, file_path):
        if file_path.endswith(".ndata") and os.path.exists(file_path):
            try:
                with open(file_path, "r+b") as fp:
                    local_files, dir_files, eocd = parse_zip(fp)
                    contains_data = b"data.npy" in dir_files
                    contains_metadata = b"metadata.json" in dir_files
                    file_count = contains_data + contains_metadata  # use fact that True is 1, False is 0
                    # TODO: make sure ndata isn't compressed, or handle it
                    if len(dir_files) != file_count or file_count == 0:
                        return False
                    return True
            except Exception as e:
                logging.error("Exception parsing ndata file: %s", file_path)
                logging.error(str(e))
        return False

Response: Return whether the given absolute file path is an ndata file.


Instruction:
How would you implement a function in Python 3 that
writes data to the ndata file specified by reference.

Response:
def write_data(self, data, file_datetime):
        """
            Write data to the ndata file specified by reference.

            :param data: the numpy array data to write
            :param file_datetime: the datetime for the file
        """
        with self.__lock:
            assert data is not None
            absolute_file_path = self.__file_path
            #logging.debug("WRITE data file %s for %s", absolute_file_path, key)
            make_directory_if_needed(os.path.dirname(absolute_file_path))
            properties = self.read_properties() if os.path.exists(absolute_file_path) else dict()
            write_zip(absolute_file_path, data, properties)
            # convert to utc time.
            tz_minutes = Utility.local_utcoffset_minutes(file_datetime)
            timestamp = calendar.timegm(file_datetime.timetuple()) - tz_minutes * 60
            os.utime(absolute_file_path, (time.time(), timestamp))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write_properties(self, properties, file_datetime):
        with self.__lock:
            absolute_file_path = self.__file_path
            #logging.debug("WRITE properties %s for %s", absolute_file_path, key)
            make_directory_if_needed(os.path.dirname(absolute_file_path))
            exists = os.path.exists(absolute_file_path)
            if exists:
                rewrite_zip(absolute_file_path, Utility.clean_dict(properties))
            else:
                write_zip(absolute_file_path, None, Utility.clean_dict(properties))
            # convert to utc time.
            tz_minutes = Utility.local_utcoffset_minutes(file_datetime)
            timestamp = calendar.timegm(file_datetime.timetuple()) - tz_minutes * 60
            os.utime(absolute_file_path, (time.time(), timestamp))

Response: Writes the properties to the ndata file specified by reference.


Instruction:
How would you code a function in Python 3 to
read properties from the ndata file

Response:
def read_properties(self):
        """
            Read properties from the ndata file reference

            :param reference: the reference from which to read
            :return: a tuple of the item_uuid and a dict of the properties
        """
        with self.__lock:
            absolute_file_path = self.__file_path
            with open(absolute_file_path, "rb") as fp:
                local_files, dir_files, eocd = parse_zip(fp)
                properties = read_json(fp, local_files, dir_files, b"metadata.json")
            return properties


Instruction:
Can you implement a function in Python 3 that
reads data from the ndata file and return numpy array of the data.

Response:
def read_data(self):
        """
            Read data from the ndata file reference

            :param reference: the reference from which to read
            :return: a numpy array of the data; maybe None
        """
        with self.__lock:
            absolute_file_path = self.__file_path
            #logging.debug("READ data file %s", absolute_file_path)
            with open(absolute_file_path, "rb") as fp:
                local_files, dir_files, eocd = parse_zip(fp)
                return read_data(fp, local_files, dir_files, b"data.npy")
            return None


Instruction:
How would you code a function in Python 3 to
remove the ndata file associated with the current ndata class.

Response:
def remove(self):
        """
            Remove the ndata file reference

            :param reference: the reference to remove
        """
        with self.__lock:
            absolute_file_path = self.__file_path
            #logging.debug("DELETE data file %s", absolute_file_path)
            if os.path.isfile(absolute_file_path):
                os.remove(absolute_file_path)


Instruction:
Implement a Python 3 function for
building the dynamic menu for the selected display panel.

Response:
def build_menu(self, display_type_menu, document_controller, display_panel):
        """Build the dynamic menu for the selected display panel.

        The user accesses this menu by right-clicking on the display panel.

        The basic menu items are to an empty display panel or a browser display panel.

        After that, each display controller factory is given a chance to add to the menu. The display
        controllers (for instance, a scan acquisition controller), may add its own menu items.
        """
        dynamic_live_actions = list()

        def switch_to_display_content(display_panel_type):
            self.switch_to_display_content(document_controller, display_panel, display_panel_type, display_panel.display_item)

        empty_action = display_type_menu.add_menu_item(_("Clear Display Panel"), functools.partial(switch_to_display_content, "empty-display-panel"))
        display_type_menu.add_separator()

        data_item_display_action = display_type_menu.add_menu_item(_("Display Item"), functools.partial(switch_to_display_content, "data-display-panel"))
        thumbnail_browser_action = display_type_menu.add_menu_item(_("Thumbnail Browser"), functools.partial(switch_to_display_content, "thumbnail-browser-display-panel"))
        grid_browser_action = display_type_menu.add_menu_item(_("Grid Browser"), functools.partial(switch_to_display_content, "browser-display-panel"))
        display_type_menu.add_separator()

        display_panel_type = display_panel.display_panel_type

        empty_action.checked = display_panel_type == "empty" and display_panel.display_panel_controller is None
        data_item_display_action.checked = display_panel_type == "data_item"
        thumbnail_browser_action.checked = display_panel_type == "horizontal"
        grid_browser_action.checked = display_panel_type == "grid"

        dynamic_live_actions.append(empty_action)
        dynamic_live_actions.append(data_item_display_action)
        dynamic_live_actions.append(thumbnail_browser_action)
        dynamic_live_actions.append(grid_browser_action)

        for factory in self.__display_controller_factories.values():
            dynamic_live_actions.extend(factory.build_menu(display_type_menu, display_panel))

        return dynamic_live_actions


Instruction:
Here you have a function in Python 3, explain what it does
def persistent_object_context_changed(self):
        super().persistent_object_context_changed()

        def source_registered(source):
            self.__source = source

        def source_unregistered(source=None):
            pass

        def reference_registered(property_name, reference):
            self.__referenced_objects[property_name] = reference

        def reference_unregistered(property_name, reference=None):
            pass

        if self.persistent_object_context:
            self.persistent_object_context.subscribe(self.source_uuid, source_registered, source_unregistered)

            for property_name, value in self.__properties.items():
                if isinstance(value, dict) and value.get("type") in {"data_item", "display_item", "data_source", "graphic", "structure"} and "uuid" in value:
                    self.persistent_object_context.subscribe(uuid.UUID(value["uuid"]), functools.partial(reference_registered, property_name), functools.partial(reference_unregistered, property_name))
        else:
            source_unregistered()

            for property_name, value in self.__properties.items():
                if isinstance(value, dict) and value.get("type") in {"data_item", "display_item", "data_source", "graphic", "structure"} and "uuid" in value:
                    reference_unregistered(property_name)

Response: Called by the persistent object when the persistent object context changes.


Instruction:
Here you have a function in Python 3, explain what it does
def ativar_sat(self, tipo_certificado, cnpj, codigo_uf):
        resp = self._http_post('ativarsat',
                tipo_certificado=tipo_certificado,
                cnpj=cnpj,
                codigo_uf=codigo_uf)
        conteudo = resp.json()
        return RespostaAtivarSAT.analisar(conteudo.get('retorno'))

Response: Mostrar uma resposta SAT especializada em AtivarSAT.


Instruction:
Make a summary of the following Python 3 code
def cancelar_ultima_venda(self, chave_cfe, dados_cancelamento):
        resp = self._http_post('cancelarultimavenda',
                chave_cfe=chave_cfe,
                dados_cancelamento=dados_cancelamento.documento())
        conteudo = resp.json()
        return RespostaCancelarUltimaVenda.analisar(conteudo.get('retorno'))

Response:
Sobrepõe :meth:`~satcfe.base.FuncoesSAT.cancelar_ultima_venda`.

        :return: Uma resposta SAT especializada em ``CancelarUltimaVenda``.
        :rtype: satcfe.resposta.cancelarultimavenda.RespostaCancelarUltimaVenda


Instruction:
Explain what the following Python 3 code does
def consultar_numero_sessao(self, numero_sessao):
        resp = self._http_post('consultarnumerosessao',
                numero_sessao=numero_sessao)
        conteudo = resp.json()
        return RespostaConsultarNumeroSessao.analisar(conteudo.get('retorno'))

Response:
Sobrepõe :meth:`~satcfe.base.FuncoesSAT.consultar_numero_sessao`.

        :return: Uma resposta SAT que irá depender da sessão consultada.
        :rtype: satcfe.resposta.padrao.RespostaSAT


Instruction:
Explain what the following Python 3 code does
def atualizar_software_sat(self):
        resp = self._http_post('atualizarsoftwaresat')
        conteudo = resp.json()
        return RespostaSAT.atualizar_software_sat(conteudo.get('retorno'))

Response: Sobreve uma resposta SAT atualizar a software.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def bloquear_sat(self):
        resp = self._http_post('bloquearsat')
        conteudo = resp.json()
        return RespostaSAT.bloquear_sat(conteudo.get('retorno'))

Response: Bloquear un objeto RespostaSAT.


Instruction:
Here you have a function in Python 3, explain what it does
def desbloquear_sat(self):
        resp = self._http_post('desbloquearsat')
        conteudo = resp.json()
        return RespostaSAT.desbloquear_sat(conteudo.get('retorno'))

Response: Desbloquear un objeto RespostaSAT.


Instruction:
Can you tell what is the following Python 3 function doing
def trocar_codigo_de_ativacao(self, novo_codigo_ativacao,
            opcao=constantes.CODIGO_ATIVACAO_REGULAR,
            codigo_emergencia=None):
        """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.trocar_codigo_de_ativacao`.

        :return: Uma resposta SAT padrão.
        :rtype: satcfe.resposta.padrao.RespostaSAT
        """
        resp = self._http_post('trocarcodigodeativacao',
                novo_codigo_ativacao=novo_codigo_ativacao,
                opcao=opcao,
                codigo_emergencia=codigo_emergencia)
        conteudo = resp.json()
        return RespostaSAT.trocar_codigo_de_ativacao(conteudo.get('retorno'))

Response: Trocar codigo de ativacao.


Instruction:
Given the following Python 3 function, write the documentation
def bounds(self) -> typing.Tuple[typing.Tuple[float, float], typing.Tuple[float, float]]:
        ...

Response: Return the bounds property in relative coordinates.


Instruction:
Write a Python 3 script to
set the end property in relative coordinates.

Response:
def end(self, value: typing.Union[float, typing.Tuple[float, float]]) -> None:
        """Set the end property in relative coordinates.

        End may be a float when graphic is an Interval or a tuple (y, x) when graphic is a Line."""
        ...


Instruction:
Can you implement a function in Python 3 that
sets the start property in relative coordinates.

Response:
def start(self, value: typing.Union[float, typing.Tuple[float, float]]) -> None:
        """Set the end property in relative coordinates.

        End may be a float when graphic is an Interval or a tuple (y, x) when graphic is a Line."""
        ...


Instruction:
Write a Python 3 script for
returning the vector property in relative coordinates.

Response:
def vector(self) -> typing.Tuple[typing.Tuple[float, float], typing.Tuple[float, float]]:
        """Return the vector property in relative coordinates.

        Vector will be a tuple of tuples ((y_start, x_start), (y_end, x_end))."""
        ...


Instruction:
How would you explain what the following Python 3 function does
def get_data_item_for_hardware_source(self, hardware_source, channel_id: str=None, processor_id: str=None, create_if_needed: bool=False, large_format: bool=False) -> DataItem:
        ...

Response: Get the data item associated with a hardware source.


Instruction:
Write a Python 3 function that can
return the data item associated with the data item reference key. If large_format is True the data item will be large format.

Response:
def get_data_item_for_reference_key(self, data_item_reference_key: str=None, create_if_needed: bool=False, large_format: bool=False) -> DataItem:
        """Get the data item associated with data item reference key. Optionally create if missing.

        :param data_item_reference_key: The data item reference key.
        :param create_if_needed: Whether to create a new data item if none is found.
        :return: The associated data item. May be None.

        .. versionadded:: 1.0

        Status: Provisional
        Scriptable: Yes
        """
        ...


Instruction:
Here you have a function in Python 3, explain what it does
def show_get_string_message_box(self, caption: str, text: str, accepted_fn, rejected_fn=None, accepted_text: str=None, rejected_text: str=None) -> None:
        ...

Response: Show a dialog box and ask for a string message dialog.


Instruction:
Write a Python 3 script to
create a calibration object with offset scale and units.

Response:
def create_calibration(self, offset: float=None, scale: float=None, units: str=None) -> Calibration.Calibration:
        """Create a calibration object with offset, scale, and units.

        :param offset: The offset of the calibration.
        :param scale: The scale of the calibration.
        :param units: The units of the calibration as a string.
        :return: The calibration object.

        .. versionadded:: 1.0

        Scriptable: Yes

        Calibrated units and uncalibrated units have the following relationship:
            :samp:`calibrated_value = offset + value * scale`
        """
        ...


Instruction:
Write a Python 3 script for
creating a data_and_metadata object from data.

Response:
def create_data_and_metadata(self, data: numpy.ndarray, intensity_calibration: Calibration.Calibration=None, dimensional_calibrations: typing.List[Calibration.Calibration]=None, metadata: dict=None, timestamp: str=None, data_descriptor: DataAndMetadata.DataDescriptor=None) -> DataAndMetadata.DataAndMetadata:
        """Create a data_and_metadata object from data.

        :param data: an ndarray of data.
        :param intensity_calibration: An optional calibration object.
        :param dimensional_calibrations: An optional list of calibration objects.
        :param metadata: A dict of metadata.
        :param timestamp: A datetime object.
        :param data_descriptor: A data descriptor describing the dimensions.

        .. versionadded:: 1.0

        Scriptable: Yes
        """
        ...


Instruction:
Here you have a function in Python 3, explain what it does
def create_data_and_metadata_from_data(self, data: numpy.ndarray, intensity_calibration: Calibration.Calibration=None, dimensional_calibrations: typing.List[Calibration.Calibration]=None, metadata: dict=None, timestamp: str=None) -> DataAndMetadata.DataAndMetadata:
        ...

Response: Create a data_and_metadata object from data.


Instruction:
Implement a Python 3 function for
creating a data descriptor.

Response:
def create_data_descriptor(self, is_sequence: bool, collection_dimension_count: int, datum_dimension_count: int) -> DataAndMetadata.DataDescriptor:
        """Create a data descriptor.

        :param is_sequence: whether the descriptor describes a sequence of data.
        :param collection_dimension_count: the number of collection dimensions represented by the descriptor.
        :param datum_dimension_count: the number of datum dimensions represented by the descriptor.

        .. versionadded:: 1.0

        Scriptable: Yes
        """
        ...


Instruction:
Make a summary of the following Python 3 code
def make_calibration_row_widget(ui, calibration_observable, label: str=None):
    calibration_row = ui.create_row_widget()
    row_label = ui.create_label_widget(label, properties={"width": 60})
    row_label.widget_id = "label"
    offset_field = ui.create_line_edit_widget(properties={"width": 60})
    offset_field.widget_id = "offset"
    scale_field = ui.create_line_edit_widget(properties={"width": 60})
    scale_field.widget_id = "scale"
    units_field = ui.create_line_edit_widget(properties={"width": 60})
    units_field.widget_id = "units"
    float_point_4_converter = Converter.FloatToStringConverter(format="{0:.4f}")
    offset_field.bind_text(Binding.PropertyBinding(calibration_observable, "offset", converter=float_point_4_converter))
    scale_field.bind_text(Binding.PropertyBinding(calibration_observable, "scale", converter=float_point_4_converter))
    units_field.bind_text(Binding.PropertyBinding(calibration_observable, "units"))
    # notice the binding of calibration_index below.
    calibration_row.add(row_label)
    calibration_row.add_spacing(12)
    calibration_row.add(offset_field)
    calibration_row.add_spacing(12)
    calibration_row.add(scale_field)
    calibration_row.add_spacing(12)
    calibration_row.add(units_field)
    calibration_row.add_stretch()
    return calibration_row

Response: Called when an item is inserted into the list widget. Returns a widget.


Instruction:
Here you have a function in Python 3, explain what it does
def add_widget_to_content(self, widget):
        self.__section_content_column.add_spacing(4)
        self.__section_content_column.add(widget)

Response: Subclasses should call this to add a widget to the section s top level column.


Instruction:
Create a Python 3 function to
call when an item is inserted into the list widget. Returns a widget.

Response:
def __create_list_item_widget(self, ui, calibration_observable):
        """Called when an item (calibration_observable) is inserted into the list widget. Returns a widget."""
        calibration_row = make_calibration_row_widget(ui, calibration_observable)
        column = ui.create_column_widget()
        column.add_spacing(4)
        column.add(calibration_row)
        return column


Instruction:
Explain what the following Python 3 code does
def _repaint(self, drawing_context):

        # canvas size
        canvas_width = self.canvas_size[1]
        canvas_height = self.canvas_size[0]

        left = self.display_limits[0]
        right = self.display_limits[1]

        # draw left display limit
        if left > 0.0:
            with drawing_context.saver():
                drawing_context.begin_path()
                drawing_context.move_to(left * canvas_width, 1)
                drawing_context.line_to(left * canvas_width, canvas_height-1)
                drawing_context.line_width = 2
                drawing_context.stroke_style = "#000"
                drawing_context.stroke()

        # draw right display limit
        if right < 1.0:
            with drawing_context.saver():
                drawing_context.begin_path()
                drawing_context.move_to(right * canvas_width, 1)
                drawing_context.line_to(right * canvas_width, canvas_height-1)
                drawing_context.line_width = 2
                drawing_context.stroke_style = "#FFF"
                drawing_context.stroke()

        # draw border
        with drawing_context.saver():
            drawing_context.begin_path()
            drawing_context.move_to(0,canvas_height)
            drawing_context.line_to(canvas_width,canvas_height)
            drawing_context.line_width = 1
            drawing_context.stroke_style = "#444"
            drawing_context.stroke()

Response: Repaint the canvas item. This will occur on a thread.


Instruction:
Explain what the following Python 3 code does
def _repaint(self, drawing_context):

        # canvas size
        canvas_width = self.canvas_size[1]
        canvas_height = self.canvas_size[0]

        # draw background
        if self.background_color:
            with drawing_context.saver():
                drawing_context.begin_path()
                drawing_context.move_to(0,0)
                drawing_context.line_to(canvas_width,0)
                drawing_context.line_to(canvas_width,canvas_height)
                drawing_context.line_to(0,canvas_height)
                drawing_context.close_path()
                drawing_context.fill_style = self.background_color
                drawing_context.fill()

        # draw the data, if any
        if (self.data is not None and len(self.data) > 0):

            # draw the histogram itself
            with drawing_context.saver():
                drawing_context.begin_path()
                binned_data = Image.rebin_1d(self.data, int(canvas_width), self.__retained_rebin_1d) if int(canvas_width) != self.data.shape[0] else self.data
                for i in range(canvas_width):
                    drawing_context.move_to(i, canvas_height)
                    drawing_context.line_to(i, canvas_height * (1 - binned_data[i]))
                drawing_context.line_width = 1
                drawing_context.stroke_style = "#444"
                drawing_context.stroke()

Response: Repaint the canvas item. This will occur on a thread.


Instruction:
Can you tell what is the following Python 3 function doing
def color_map_data(self, data: numpy.ndarray) -> None:
        self.__color_map_data = data
        self.update()

Response: Set the data and mark the canvas item for updating.


Instruction:
Can you tell what is the following Python 3 function doing
def _repaint(self, drawing_context: DrawingContext.DrawingContext):

        # canvas size
        canvas_width = self.canvas_size.width
        canvas_height = self.canvas_size.height

        with drawing_context.saver():
            if self.__color_map_data is not None:
                rgba_image = numpy.empty((4,) + self.__color_map_data.shape[:-1], dtype=numpy.uint32)
                Image.get_rgb_view(rgba_image)[:] = self.__color_map_data[numpy.newaxis, :, :]  # scalar data assigned to each component of rgb view
                Image.get_alpha_view(rgba_image)[:] = 255
                drawing_context.draw_image(rgba_image, 0, 0, canvas_width, canvas_height)

Response: Repaint the canvas item. This will occur on a thread.


Instruction:
Here you have a function in Python 3, explain what it does
def get_params(self):
        "Parameters used to initialize the class"
        import inspect
        a = inspect.getargspec(self.__init__)[0]
        out = dict()
        for key in a[1:]:
            value = getattr(self, "_%s" % key, None)
            out[key] = value
        return out

Response: Parameters used to initialize the class


Instruction:
Implement a function in Python 3 to
class containing the population and all the individuals generated

Response:
def population(self):
        "Class containing the population and all the individuals generated"
        try:
            return self._p
        except AttributeError:
            self._p = self._population_class(base=self,
                                             tournament_size=self._tournament_size,
                                             classifier=self.classifier,
                                             labels=self._labels,
                                             es_extra_test=self.es_extra_test,
                                             popsize=self._popsize,
                                             random_generations=self._random_generations,
                                             negative_selection=self._negative_selection)
            return self._p


Instruction:
Can you generate a brief explanation for the following Python 3 code
def random_leaf(self):
        "Returns a random variable with the associated weight"
        for i in range(self._number_tries_feasible_ind):
            var = np.random.randint(self.nvar)
            v = self._random_leaf(var)
            if v is None:
                continue
            return v
        raise RuntimeError("Could not find a suitable random leaf")

Response: Returns a random variable with the associated weight


Instruction:
Can you generate a brief explanation for the following Python 3 code
def random_offspring(self):
        "Returns an offspring with the associated weight(s)"
        function_set = self.function_set
        function_selection = self._function_selection_ins
        function_selection.density = self.population.density
        function_selection.unfeasible_functions.clear()
        for i in range(self._number_tries_feasible_ind):
            if self._function_selection:
                func_index = function_selection.tournament()
            else:
                func_index = function_selection.random_function()
            func = function_set[func_index]
            args = self.get_args(func)
            if args is None:
                continue
            args = [self.population.population[x].position for x in args]
            f = self._random_offspring(func, args)
            if f is None:
                function_selection.unfeasible_functions.add(func_index)
                continue
            function_selection[func_index] = f.fitness
            return f
        raise RuntimeError("Could not find a suitable random offpsring")

Response: Returns an offspring with the associated weight ( s )


Instruction:
Write a Python 3 function that can
test whether the stopping criteria has been achieved.

Response:
def stopping_criteria(self):
        "Test whether the stopping criteria has been achieved."
        if self.stopping_criteria_tl():
            return True
        if self.generations < np.inf:
            inds = self.popsize * self.generations
            flag = inds <= len(self.population.hist)
        else:
            flag = False
        if flag:
            return True
        est = self.population.estopping
        if self._tr_fraction < 1:
            if est is not None and est.fitness_vs == 0:
                return True
        esr = self._early_stopping_rounds
        if self._tr_fraction < 1 and esr is not None and est is not None:
            position = self.population.estopping.position
            if position < self.init_popsize:
                position = self.init_popsize
            return (len(self.population.hist) +
                    self._unfeasible_counter -
                    position) > esr
        return flag


Instruction:
Make a summary of the following Python 3 code
def nclasses(self, v):
        "Number of classes of v, also sets the labes"
        if not self.classifier:
            return 0
        if isinstance(v, list):
            self._labels = np.arange(len(v))
            return
        if not isinstance(v, np.ndarray):
            v = tonparray(v)
        self._labels = np.unique(v)
        return self._labels.shape[0]

Response: Number of classes of v also sets the labes


Instruction:
Can you tell what is the following Python 3 function doing
def fit(self, X, y, test_set=None):
        self._init_time = time.time()
        self.X = X
        if self._popsize == "nvar":
            self._popsize = self.nvar + len(self._input_functions)
        if isinstance(test_set, str) and test_set == 'shuffle':
            test_set = self.shuffle_tr2ts()
        nclasses = self.nclasses(y)
        if self.classifier and self._multiple_outputs:
            pass
        elif nclasses > 2:
            assert False
            self._multiclass = True
            return self.multiclass(X, y, test_set=test_set)
        self.y = y
        if test_set is not None:
            self.Xtest = test_set
        for _ in range(self._number_tries_feasible_ind):
            self._logger.info("Starting evolution")
            try:
                self.create_population()
                if self.stopping_criteria_tl():
                    break
            except RuntimeError as err:
                self._logger.info("Done evolution (RuntimeError (%s), hist: %s)" % (err, len(self.population.hist)))
                return self
            self._logger.info("Population created (hist: %s)" % len(self.population.hist))
            if len(self.population.hist) >= self._tournament_size:
                break
        if len(self.population.hist) == 0:
            raise RuntimeError("Could not find a suitable individual")
        if len(self.population.hist) < self._tournament_size:
            self._logger.info("Done evolution (hist: %s)" % len(self.population.hist))
            return self
        if self._remove_raw_inputs:
            for x in range(self.nvar):
                self._X[x] = None
        while not self.stopping_criteria():
            try:
                a = self.random_offspring()
            except RuntimeError as err:
                self._logger.info("Done evolution (RuntimeError (%s), hist: %s)" % (err, len(self.population.hist)))
                return self
            self.replace(a)
        self._logger.info("Done evolution (hist: %s)" % len(self.population.hist))
        return self

Response: Fits the evolution process


Instruction:
How would you explain what the following Python 3 function does
def serve(application, host='127.0.0.1', port=8080):

	# Instantiate the server with a host/port configuration and our application.
	WSGIServer((host, int(port)), application).serve_forever()

Response: Gevent - based WSGI - HTTP server.


Instruction:
Write a Python 3 script to
return the subscribers for a given object.

Response:
def get_subscribers(obj):
    """
    Returns the subscribers for a given object.

    :param obj: Any object.

    """
    ctype = ContentType.objects.get_for_model(obj)
    return Subscription.objects.filter(content_type=ctype, object_id=obj.pk)


Instruction:
Can you tell what is the following Python 3 function doing
def is_subscribed(user, obj):
    if not user.is_authenticated():
        return False

    ctype = ContentType.objects.get_for_model(obj)

    try:
        Subscription.objects.get(
            user=user, content_type=ctype, object_id=obj.pk)
    except Subscription.DoesNotExist:
        return False

    return True

Response: Returns True if the user is subscribed to the given object.


Instruction:
Here you have a function in Python 3, explain what it does
def _promote(self, name, instantiate=True):

		metaclass = type(self.__class__)
		contents = self.__dict__.copy()
		cls = metaclass(str(name), (self.__class__, ), contents)

		if instantiate:
			return cls()

		return cls

Response: Create a new subclass of Context which incorporates instance attributes and descriptors and returns an instance of that class.


Instruction:
Explain what the following Python 3 code does
def run_individual(sim_var,
                   reference,
                   neuroml_file,
                   nml_doc,
                   still_included,
                   generate_dir,
                   target,
                   sim_time,
                   dt,
                   simulator,
                   cleanup = True,
                   show=False):
    """
    Run an individual simulation.

    The candidate data has been flattened into the sim_var dict. The
    sim_var dict contains parameter:value key value pairs, which are
    applied to the model before it is simulated.

    """

    for var_name in sim_var.keys():

        individual_var_names = var_name.split('+')

        for individual_var_name in individual_var_names:
            words = individual_var_name.split('/')
            type, id1 = words[0].split(':')
            if ':' in words[1]:
                variable, id2 = words[1].split(':')
            else:
                variable = words[1]
                id2 = None

            units = words[2]
            value = sim_var[var_name]

            pyneuroml.pynml.print_comment_v('  Changing value of %s (%s) in %s (%s) to: %s %s'%(variable, id2, type, id1, value, units))

            if type == 'channel':
                channel = nml_doc.get_by_id(id1)

                if channel:
                    print("Setting channel %s"%(channel))
                    if variable == 'vShift':
                        channel.v_shift = '%s %s'%(value, units)
                else:

                    pyneuroml.pynml.print_comment_v('Could not find channel with id %s from expression: %s'%(id1, individual_var_name))
                    exit()

            elif type == 'cell':
                cell = None
                for c in nml_doc.cells:
                    if c.id == id1:
                        cell = c

                if variable == 'channelDensity':

                    chanDens = None
                    for cd in cell.biophysical_properties.membrane_properties.channel_densities + cell.biophysical_properties.membrane_properties.channel_density_v_shifts:
                        if cd.id == id2:
                            chanDens = cd

                    chanDens.cond_density = '%s %s'%(value, units)

                elif variable == 'vShift_channelDensity':

                    chanDens = None
                    for cd in cell.biophysical_properties.membrane_properties.channel_density_v_shifts:
                        if cd.id == id2:
                            chanDens = cd

                    chanDens.v_shift = '%s %s'%(value, units)

                elif variable == 'channelDensityNernst':

                    chanDens = None
                    for cd in cell.biophysical_properties.membrane_properties.channel_density_nernsts:
                        if cd.id == id2:
                            chanDens = cd

                    chanDens.cond_density = '%s %s'%(value, units)

                elif variable == 'erev_id': # change all values of erev in channelDensity elements with only this id

                    chanDens = None
                    for cd in cell.biophysical_properties.membrane_properties.channel_densities + cell.biophysical_properties.membrane_properties.channel_density_v_shifts:
                        if cd.id == id2:
                            chanDens = cd

                    chanDens.erev = '%s %s'%(value, units)

                elif variable == 'erev_ion': # change all values of erev in channelDensity elements with this ion

                    chanDens = None
                    for cd in cell.biophysical_properties.membrane_properties.channel_densities + cell.biophysical_properties.membrane_properties.channel_density_v_shifts:
                        if cd.ion == id2:
                            chanDens = cd

                    chanDens.erev = '%s %s'%(value, units)

                elif variable == 'specificCapacitance':

                    specCap = None
                    for sc in cell.biophysical_properties.membrane_properties.specific_capacitances:
                        if (sc.segment_groups == None and id2 == 'all') or sc.segment_groups == id2 :
                            specCap = sc

                    specCap.value = '%s %s'%(value, units)

                elif variable == 'resistivity':

                    resistivity = None
                    for rs in cell.biophysical_properties.intracellular_properties.resistivities:
                        if (rs.segment_groups == None and id2 == 'all') or rs.segment_groups == id2 :
                            resistivity = rs

                    resistivity.value = '%s %s'%(value, units)

                else:
                    pyneuroml.pynml.print_comment_v('Unknown variable (%s) in variable expression: %s'%(variable, individual_var_name))
                    exit()

            elif type == 'izhikevich2007Cell':
                izhcell = None
                for c in nml_doc.izhikevich2007_cells:
                    if c.id == id1:
                        izhcell = c

                izhcell.__setattr__(variable, '%s %s'%(value, units))

            else:
                pyneuroml.pynml.print_comment_v('Unknown type (%s) in variable expression: %s'%(type, individual_var_name))

    new_neuroml_file =  '%s/%s'%(generate_dir,os.path.basename(neuroml_file))
    if new_neuroml_file == neuroml_file:
        pyneuroml.pynml.print_comment_v('Cannot use a directory for generating into (%s) which is the same location of the NeuroML file (%s)!'% \
                  (neuroml_file, generate_dir))

    pyneuroml.pynml.write_neuroml2_file(nml_doc, new_neuroml_file)

    for include in still_included:
        inc_loc = '%s/%s'%(os.path.dirname(os.path.abspath(neuroml_file)),include)
        pyneuroml.pynml.print_comment_v("Copying non included file %s to %s (%s) beside %s"%(inc_loc, generate_dir,os.path.abspath(generate_dir), new_neuroml_file))
        shutil.copy(inc_loc, generate_dir)

    from pyneuroml.tune.NeuroMLSimulation import NeuroMLSimulation

    sim = NeuroMLSimulation(reference,
                         neuroml_file = new_neuroml_file,
                         target = target,
                         sim_time = sim_time,
                         dt = dt,
                         simulator = simulator,
                         generate_dir = generate_dir,
                         cleanup = cleanup,
                         nml_doc = nml_doc)

    sim.go()

    if show:
        sim.show()

    return sim.t, sim.volts

Response: Runs an individual simulation.


Instruction:
Explain what the following Python 3 code does
def run(self,candidates,parameters):

        traces = []
        start_time = time.time()

        if self.num_parallel_evaluations == 1:

            for candidate_i in range(len(candidates)):

                candidate = candidates[candidate_i]
                sim_var = dict(zip(parameters,candidate))
                pyneuroml.pynml.print_comment_v('\n\n  - RUN %i (%i/%i); variables: %s\n'%(self.count,candidate_i+1,len(candidates),sim_var))
                self.count+=1
                t,v = self.run_individual(sim_var)
                traces.append([t,v])

        else:
            import pp
            ppservers = ()
            job_server = pp.Server(self.num_parallel_evaluations, ppservers=ppservers)
            pyneuroml.pynml.print_comment_v('Running %i candidates across %i local processes'%(len(candidates),job_server.get_ncpus()))
            jobs = []

            for candidate_i in range(len(candidates)):

                candidate = candidates[candidate_i]
                sim_var = dict(zip(parameters,candidate))
                pyneuroml.pynml.print_comment_v('\n\n  - PARALLEL RUN %i (%i/%i of curr candidates); variables: %s\n'%(self.count,candidate_i+1,len(candidates),sim_var))
                self.count+=1
                cand_dir = self.generate_dir+"/CANDIDATE_%s"%candidate_i
                if not os.path.exists(cand_dir):
                    os.mkdir(cand_dir)
                vars = (sim_var,
                        self.ref,
                        self.neuroml_file,
                        self.nml_doc,
                        self.still_included,
                        cand_dir,
                        self.target,
                        self.sim_time,
                        self.dt,
                        self.simulator)

                job = job_server.submit(run_individual, vars, (), ("pyneuroml.pynml",'pyneuroml.tune.NeuroMLSimulation','shutil','neuroml'))
                jobs.append(job)

            for job_i in range(len(jobs)):
                job = jobs[job_i]
                pyneuroml.pynml.print_comment_v("Checking parallel job %i/%i; set running so far: %i"%(job_i,len(jobs),self.count))
                t,v = job()
                traces.append([t,v])

                #pyneuroml.pynml.print_comment_v("Obtained: %s"%result)

            ####job_server.print_stats()
            job_server.destroy()
            print("-------------------------------------------")

        end_time = time.time()
        tot = (end_time-start_time)
        pyneuroml.pynml.print_comment_v('Ran %i candidates in %s seconds (~%ss per job)'%(len(candidates),tot,tot/len(candidates)))

        return traces

Response: Run simulation for each candidate and return a list of voltage traces.


Instruction:
Can you write a function in Python 3 where it
executes prior to processing a request.

Response:
def prepare(self, context):
		"""Executed prior to processing a request."""
		if __debug__:
			log.debug("Assigning thread local request context.")

		self.local.context = context


Instruction:
Given the following Python 3 function, write the documentation
def register(self, kind, handler):
		if __debug__:  # In production this logging is completely skipped, regardless of logging level.
			if py3 and not pypy:  # Where possible, we shorten things to just the cannonical name.
				log.debug("Registering view handler.", extra=dict(type=name(kind), handler=name(handler)))
			else:  # Canonical name lookup is not entirely reliable on some combinations.
				log.debug("Registering view handler.", extra=dict(type=repr(kind), handler=repr(handler)))

		# Add the handler to the pool of candidates. This adds to a list instead of replacing the "dictionary item".
		self._map.add(kind, handler)

		return handler

Response: Register a handler for a given type class interface or abstract base class.


Instruction:
How would you explain what the following Python 3 function does
def static(base, mapping=None, far=('js', 'css', 'gif', 'jpg', 'jpeg', 'png', 'ttf', 'woff')):

	base = abspath(base)

	@staticmethod
	def static_handler(context, *parts, **kw):
		path = normpath(pathjoin(base, *parts))

		if __debug__:
			log.debug("Attempting to serve static file.", extra=dict(
					request = id(context),
					base = base,
					path = path
				))

		if not path.startswith(base):  # Ensure we only serve files from the allowed path.
			raise HTTPForbidden("Cowardly refusing to violate base path policy." if __debug__ else None)

		if not exists(path):  # Do the right thing if the file doesn't actually exist.
			raise HTTPNotFound()

		if not isfile(path):  # Only serve normal files; no UNIX domain sockets, FIFOs, etc., etc.
			raise HTTPForbidden("Cowardly refusing to open a non-file." if __debug__ else None)

		if far and path.rpartition('.')[2] in far:
			context.response.cache_expires = 60*60*24*365

		if mapping:  # Handle the mapping of filename extensions to 2-tuples. 'Cause why not?
			_, _, extension = basename(path).partition('.')
			if extension in mapping:
				return mapping[extension] + ':' + path, dict()

		return open(path, 'rb')

	return static_handler

Response: This function is used to serve static files from disk.


Instruction:
Create a Python 3 function for
parsing command - line arguments and return a list of dictionaries containing spike time data.

Response:
def process_args():
    """
    Parse command-line arguments.
    """
    parser = argparse.ArgumentParser(description="A script for plotting files containing spike time data")

    parser.add_argument('spiketimeFiles',
                        type=str,
                        metavar='<spiketime file>',
                        help='List of text file containing spike times',
                        nargs='+')

    parser.add_argument('-format',
                        type=str,
                        metavar='<format>',
                        default=DEFAULTS['format'],
                        help='How the spiketimes are represented on each line of file:\n'+\
                             'id_t: id of cell, space(s)/tab(s), time of spike (default);\n'+\
                             't_id: time of spike, space(s)/tab(s), id of cell;\n'+\
                             'sonata: SONATA format HDF5 file containing spike times')

    parser.add_argument('-rates',
                        action='store_true',
                        default=DEFAULTS['rates'],
                        help='Show a plot of rates')

    parser.add_argument('-showPlotsAlready',
                        action='store_true',
                        default=DEFAULTS['show_plots_already'],
                        help='Show plots once generated')

    parser.add_argument('-saveSpikePlotTo',
                        type=str,
                        metavar='<spiketime plot filename>',
                        default=DEFAULTS['save_spike_plot_to'],
                        help='Name of file in which to save spiketime plot')

    parser.add_argument('-rateWindow',
                        type=int,
                        metavar='<rate window>',
                        default=DEFAULTS['rate_window'],
                        help='Window for rate calculation in ms')

    parser.add_argument('-rateBins',
                        type=int,
                        metavar='<rate bins>',
                        default=DEFAULTS['rate_bins'],
                        help='Number of bins for rate histogram')

    return parser.parse_args()


Instruction:
Given the following Python 3 function, write the documentation
def save(self, *args, **kwargs):
        method_kwargs = self._get_method_kwargs()
        try:
            subscription = Subscription.objects.get(**method_kwargs)
        except Subscription.DoesNotExist:
            subscription = Subscription.objects.create(**method_kwargs)
        return subscription

Response: Adds a subscription for the given user to the given object.


Instruction:
Can you tell what is the following Python 3 function doing
def prepare(self, context):

		if __debug__:
			log.debug("Preparing request context.", extra=dict(request=id(context)))

		# Bridge in WebOb `Request` and `Response` objects.
		# Extensions shouldn't rely on these, using `environ` where possible instead.
		context.request = Request(context.environ)
		context.response = Response(request=context.request)

		# Record the initial path representing the point where a front-end web server bridged to us.
		context.environ['web.base'] = context.request.script_name

		# Track the remaining (unprocessed) path elements.
		context.request.remainder = context.request.path_info.split('/')
		if context.request.remainder and not context.request.remainder[0]:
			del context.request.remainder[0]

		# Track the "breadcrumb list" of dispatch through distinct controllers.
		context.path = Bread()

Response: This method is called before the request context is processed.


Instruction:
Can you generate the documentation for the following Python 3 function
def dispatch(self, context, consumed, handler, is_endpoint):

		request = context.request

		if __debug__:
			log.debug("Handling dispatch event.", extra=dict(
					request = id(context),
					consumed = consumed,
					handler = safe_name(handler),
					endpoint = is_endpoint
				))

		# The leading path element (leading slash) requires special treatment.
		if not consumed and context.request.path_info_peek() == '':
			consumed = ['']

		nConsumed = 0
		if consumed:
			# Migrate path elements consumed from the `PATH_INFO` to `SCRIPT_NAME` WSGI environment variables.
			if not isinstance(consumed, (list, tuple)):
				consumed = consumed.split('/')

			for element in consumed:
				if element == context.request.path_info_peek():
					context.request.path_info_pop()
					nConsumed += 1
				else:
					break

		# Update the breadcrumb list.
		context.path.append(Crumb(handler, Path(request.script_name)))

		if consumed:  # Lastly, update the remaining path element list.
			request.remainder = request.remainder[nConsumed:]

Response: Called as a dispatch descends into a tier.


Instruction:
Can you implement a function in Python 3 that
returns binary responses unmodified.

Response:
def render_binary(self, context, result):
		"""Return binary responses unmodified."""
		context.response.app_iter = iter((result, ))  # This wraps the binary string in a WSGI body iterable.
		return True


Instruction:
Implement a Python 3 function for
performing appropriate metadata wrangling for returned open file handles.

Response:
def render_file(self, context, result):
		"""Perform appropriate metadata wrangling for returned open file handles."""
		if __debug__:
			log.debug("Processing file-like object.", extra=dict(request=id(context), result=repr(result)))

		response = context.response
		response.conditional_response = True

		modified = mktime(gmtime(getmtime(result.name)))

		response.last_modified = datetime.fromtimestamp(modified)
		ct, ce = guess_type(result.name)
		if not ct: ct = 'application/octet-stream'
		response.content_type, response.content_encoding = ct, ce
		response.etag = unicode(modified)

		result.seek(0, 2)  # Seek to the end of the file.
		response.content_length = result.tell()

		result.seek(0)  # Seek back to the start of the file.
		response.body_file = result

		return True


Instruction:
Explain what the following Python 3 code does
def render_generator(self, context, result):
		context.response.encoding = 'utf8'
		context.response.app_iter = (
				(i.encode('utf8') if isinstance(i, unicode) else i)  # Stream encode unicode chunks.
				for i in result if i is not None  # Skip None values.
			)
		return True

Response: Attempt to serve generator responses through stream encoding.


Instruction:
How would you explain what the following Python 3 function does
def serve(application, host='127.0.0.1', port=8080):

	# Instantiate the server with our configuration and application.
	server = CherryPyWSGIServer((host, int(port)), application, server_name=host)

	# Try to be handy as many terminals allow clicking links.
	print("serving on http://{0}:{1}".format(host, port))

	# Bind and launch the server; this is a blocking operation.
	try:
		server.start()
	except KeyboardInterrupt:
		server.stop()

Response: Start a CherryPy - based WSGI - HTTP server.


Instruction:
Write a Python 3 function for
returning the colored string

Response:
def colorize(self, string, rgb=None, ansi=None, bg=None, ansi_bg=None):
        '''Returns the colored string'''
        if not isinstance(string, str):
            string = str(string)
        if rgb is None and ansi is None:
            raise TerminalColorMapException(
                'colorize: must specify one named parameter: rgb or ansi')
        if rgb is not None and ansi is not None:
            raise TerminalColorMapException(
                'colorize: must specify only one named parameter: rgb or ansi')
        if bg is not None and ansi_bg is not None:
            raise TerminalColorMapException(
                'colorize: must specify only one named parameter: bg or ansi_bg')

        if rgb is not None:
            (closestAnsi, closestRgb) = self.convert(rgb)
        elif ansi is not None:
            (closestAnsi, closestRgb) = (ansi, self.colors[ansi])

        if bg is None and ansi_bg is None:
            return "\033[38;5;{ansiCode:d}m{string:s}\033[0m".format(ansiCode=closestAnsi, string=string)

        if bg is not None:
            (closestBgAnsi, unused) = self.convert(bg)
        elif ansi_bg is not None:
            (closestBgAnsi, unused) = (ansi_bg, self.colors[ansi_bg])

        return "\033[38;5;{ansiCode:d}m\033[48;5;{bf:d}m{string:s}\033[0m".format(ansiCode=closestAnsi, bf=closestBgAnsi, string=string)


Instruction:
How would you implement a function in Python 3 that
functions that generates the plot of all the available components.

Response:
def main(args=None):
    """Main"""

    vs = [(v-100)*0.001 for v in range(200)]

    for f in ['IM.channel.nml','Kd.channel.nml']:
        nml_doc = pynml.read_neuroml2_file(f)

        for ct in nml_doc.ComponentType:

            ys = []
            for v in vs:
                req_variables = {'v':'%sV'%v,'vShift':'10mV'}
                vals = pynml.evaluate_component(ct,req_variables=req_variables)
                print vals
                if 'x' in vals:
                    ys.append(vals['x'])
                if 't' in vals:
                    ys.append(vals['t'])
                if 'r' in vals:
                    ys.append(vals['r'])

            ax = pynml.generate_plot([vs],[ys],
                             "Some traces from %s in %s"%(ct.name,f),
                             show_plot_already=False )

            print vals

    plt.show()


Instruction:
Explain what the following Python 3 code does
def root(context):

	response = context.response

	parts = []

	for i in range(12):
		for j in range(12):
			parts.append(executor.submit(mul, i, j))

	def stream(parts, timeout=None):
		try:
			for future in as_completed(parts, timeout):
				mime, result = future.result()
				result = result.encode('utf8')

				yield "!!!!!!=_NextPart_{num}\nContent-Type: {mime}\nContent-Length: {length}\n\n".format(
						num = randint(100000000, 999999999),
						mime = mime,
						length = len(result)
					).encode('utf8') + result

		except TimeoutError:
			for future in parts:
				future.cancel()

	response.content_length = None
	response.app_iter = stream(parts, 0.2)

	return response

Response: This function returns a multipart ajax request example. It returns a response object that contains the response body.


Instruction:
Write a Python 3 script to
get a file and render the content of the template_file_name with kwargs in a file

Response:
def render_template_with_args_in_file(file, template_file_name, **kwargs):
    """
    Get a file and render the content of the template_file_name with kwargs in a file
    :param file: A File Stream to write
    :param template_file_name: path to route with template name
    :param **kwargs: Args to be rendered in template
    """
    template_file_content = "".join(
        codecs.open(
            template_file_name,
            encoding='UTF-8'
        ).readlines()
    )
    template_rendered = string.Template(template_file_content).safe_substitute(**kwargs)
    file.write(template_rendered)


Instruction:
Can you implement a function in Python 3 that
creates a file or opens a file with file_name name

Response:
def create_or_open(file_name, initial_template_file_name, args):
    """
    Creates a file or open the file with file_name name
    :param file_name: String with a filename
    :param initial_template_file_name: String with path to initial template
    :param args: from console to determine path to save the files
    """
    file = None
    if not os.path.isfile(
        os.path.join(
            args['django_application_folder'],
            file_name
        )
    ):
        # If file_name does not exists, create
        file = codecs.open(
            os.path.join(
                args['django_application_folder'],
                file_name
            ),
            'w+',
            encoding='UTF-8'
        )
        print("Creating {}".format(file_name))
        if initial_template_file_name:
            render_template_with_args_in_file(file, initial_template_file_name, **{})
    else:
        # If file exists, just load the file
        file = codecs.open(
            os.path.join(
                args['django_application_folder'],
                file_name
            ),
            'a+',
            encoding='UTF-8'
        )

    return file


Instruction:
Implement a function in Python 3 to
verify if the work folder is a Django application folder.

Response:
def sanity_check(args):
    """
    Verify if the work folder is a django app.
    A valid django app always must have a models.py file
    :return: None
    """
    if not os.path.isfile(
        os.path.join(
            args['django_application_folder'],
            'models.py'
        )
    ):
        print("django_application_folder is not a Django application folder")
        sys.exit(1)


Instruction:
Here you have a function in Python 3, explain what it does
def generic_insert_with_folder(folder_name, file_name, template_name, args):
    # First we make sure views are a package instead a file
    if not os.path.isdir(
        os.path.join(
            args['django_application_folder'],
            folder_name
        )
    ):
        os.mkdir(os.path.join(args['django_application_folder'], folder_name))
        codecs.open(
            os.path.join(
                args['django_application_folder'],
                folder_name,
                '__init__.py'
            ),
            'w+'
        )

    view_file = create_or_open(
        os.path.join(
            folder_name,
            '{}.py'.format(file_name)
        ),
        '',
        args
    )
    # Load content from template
    render_template_with_args_in_file(
        view_file,
        os.path.join(
            BASE_TEMPLATES_DIR,
            template_name
        ),
        model_name=args['model_name'],
        model_prefix=args['model_prefix'],
        model_name_lower=args['model_name'].lower(),
        application_name=args['django_application_folder'].split("/")[-1]
    )
    view_file.close()

Response: Generic method for inserting a new file into a folder.


Instruction:
Implement a function in Python 3 to
plot the result of the simulation once it s intialized

Response:
def show(self):
        """
        Plot the result of the simulation once it's been intialized
        """

        from matplotlib import pyplot as plt

        if self.already_run:

            for ref in self.volts.keys():

                plt.plot(self.t, self.volts[ref], label=ref)
                plt.title("Simulation voltage vs time")
                plt.legend()
                plt.xlabel("Time [ms]")
                plt.ylabel("Voltage [mV]")

        else:
            pynml.print_comment("First you have to 'go()' the simulation.", True)
        plt.show()


Instruction:
Write a Python 3 function for
multiplying two values together and return the result via JSON.

Response:
def mul(self, a: int = None, b: int = None) -> 'json':
		"""Multiply two values together and return the result via JSON.

		Python 3 function annotations are used to ensure that the arguments are integers. This requires the
		functionality of `web.ext.annotation:AnnotationExtension`.

		There are several ways to execute this method:

		* POST http://localhost:8080/mul
		* GET http://localhost:8080/mul?a=27&b=42
		* GET http://localhost:8080/mul/27/42

		The latter relies on the fact we can't descend past a callable method so the remaining path elements are
		used as positional arguments, whereas the others rely on keyword argument assignment from a form-encoded
		request body or query string arguments.  (Security note: any data in the request body takes presidence over
		query string arguments!)

		You can easily test these on the command line using cURL:

			curl http://localhost:8080/mul/27/42  # HTTP GET

			curl -d a=27 -d b=42 http://localhost:8080/mul  # HTTP POST
		"""

		if not a or not b:
			return dict(message="Pass arguments a and b to multiply them together!")

		return dict(answer=a * b)


Instruction:
How would you implement a function in Python 3 that
returns the colored string to print on the terminal.

Response:
def colorize(string, rgb=None, ansi=None, bg=None, ansi_bg=None, fd=1):
    '''Returns the colored string to print on the terminal.

    This function detects the terminal type and if it is supported and the
    output is not going to a pipe or a file, then it will return the colored
    string, otherwise it will return the string without modifications.

    string = the string to print. Only accepts strings, unicode strings must
             be encoded in advance.
    rgb    = Rgb color for the text; for example 0xFF0000 is red.
    ansi   = Ansi for the text
    bg     = Rgb color for the background
    ansi_bg= Ansi color for the background
    fd     = The file descriptor that will be used by print, by default is the
             stdout
    '''

    #Reinitializes if fd used is different
    if colorize.fd != fd:
        colorize.init = False
        colorize.fd = fd

    #Checks if it is on a terminal, and if the terminal is recognized
    if not colorize.init:
        colorize.init = True
        colorize.is_term = isatty(fd)
        if 'TERM' in environ:
            if environ['TERM'].startswith('xterm'):
                colorize.cmap = XTermColorMap()
            elif environ['TERM'] == 'vt100':
                colorize.cmap = VT100ColorMap()
            else:
                colorize.is_term = False
        else:
            colorize.is_term = False

    if colorize.is_term:
        string = colorize.cmap.colorize(string, rgb, ansi, bg, ansi_bg)

    return string


Instruction:
How would you explain what the following Python 3 function does
def mutate(self, context, handler, args, kw):
		def cast(arg, val):
			if arg not in annotations:
				return

			cast = annotations[key]

			try:
				val = cast(val)
			except (ValueError, TypeError) as e:
				parts = list(e.args)
				parts[0] = parts[0] + " processing argument '{}'".format(arg)
				e.args = tuple(parts)
				raise

			return val

		annotations = getattr(handler.__func__ if hasattr(handler, '__func__') else handler, '__annotations__', None)
		if not annotations:
			return

		argspec = getfullargspec(handler)
		arglist = list(argspec.args)

		if ismethod(handler):
			del arglist[0]

		for i, value in enumerate(list(args)):
			key = arglist[i]
			if key in annotations:
				args[i] = cast(key, value)

		# Convert keyword arguments
		for key, value in list(items(kw)):
			if key in annotations:
				kw[key] = cast(key, value)

Response: Inspect and potentially mutate the given handler s arguments.


Instruction:
Can you tell what is the following Python 3 function doing
def transform(self, context, handler, result):
		handler = handler.__func__ if hasattr(handler, '__func__') else handler
		annotation = getattr(handler, '__annotations__', {}).get('return', None)

		if annotation:
			return (annotation, result)

		return result

Response: Transform the value returned by the controller endpoint. This extension transforms returned values if the endpoint has a return type annotation.


Instruction:
Can you create a Python 3 function that
parses command - line arguments and return a new object.

Response:
def process_args():
    """
    Parse command-line arguments.
    """
    parser = argparse.ArgumentParser(
                description=("A script which can be run to tune a NeuroML 2 model against a number of target properties. Work in progress!"))

    parser.add_argument('prefix',
                        type=str,
                        metavar='<prefix>',
                        help="Prefix for optimisation run")

    parser.add_argument('neuromlFile',
                        type=str,
                        metavar='<neuromlFile>',
                        help="NeuroML2 file containing model")

    parser.add_argument('target',
                        type=str,
                        metavar='<target>',
                        help="Target in NeuroML2 model")

    parser.add_argument('parameters',
                        type=str,
                        metavar='<parameters>',
                        help="List of parameter to adjust")

    parser.add_argument('maxConstraints',
                        type=str,
                        metavar='<max_constraints>',
                        help="Max values for parameters")

    parser.add_argument('minConstraints',
                        type=str,
                        metavar='<min_constraints>',
                        help="Min values for parameters")

    parser.add_argument('targetData',
                        type=str,
                        metavar='<targetData>',
                        help="List of name/value pairs for properties extracted from data to judge fitness against")

    parser.add_argument('weights',
                        type=str,
                        metavar='<weights>',
                        help="Weights to assign to each target name/value pair")

    parser.add_argument('-simTime',
                        type=float,
                        metavar='<simTime>',
                        default=DEFAULTS['simTime'],
                        help="Simulation duration")

    parser.add_argument('-dt',
                        type=float,
                        metavar='<dt>',
                        default=DEFAULTS['dt'],
                        help="Simulation timestep")

    parser.add_argument('-analysisStartTime',
                        type=float,
                        metavar='<analysisStartTime>',
                        default=DEFAULTS['analysisStartTime'],
                        help="Analysis start time")

    parser.add_argument('-populationSize',
                        type=int,
                        metavar='<populationSize>',
                        default=DEFAULTS['populationSize'],
                        help="Population size")

    parser.add_argument('-maxEvaluations',
                        type=int,
                        metavar='<maxEvaluations>',
                        default=DEFAULTS['maxEvaluations'],
                        help="Maximum evaluations")

    parser.add_argument('-numSelected',
                        type=int,
                        metavar='<numSelected>',
                        default=DEFAULTS['numSelected'],
                        help="Number selected")

    parser.add_argument('-numOffspring',
                        type=int,
                        metavar='<numOffspring>',
                        default=DEFAULTS['numOffspring'],
                        help="Number offspring")

    parser.add_argument('-mutationRate',
                        type=float,
                        metavar='<mutationRate>',
                        default=DEFAULTS['mutationRate'],
                        help="Mutation rate")

    parser.add_argument('-numElites',
                        type=int,
                        metavar='<numElites>',
                        default=DEFAULTS['numElites'],
                        help="Number of elites")

    parser.add_argument('-numParallelEvaluations',
                        type=int,
                        metavar='<numParallelEvaluations>',
                        default=DEFAULTS['numParallelEvaluations'],
                        help="Number of evaluations to run in parallel")

    parser.add_argument('-seed',
                        type=int,
                        metavar='<seed>',
                        default=DEFAULTS['seed'],
                        help="Seed for optimiser")

    parser.add_argument('-simulator',
                        type=str,
                        metavar='<simulator>',
                        default=DEFAULTS['simulator'],
                        help="Simulator to run")

    parser.add_argument('-knownTargetValues',
                        type=str,
                        metavar='<knownTargetValues>',
                        help="List of name/value pairs which represent the known values of the target parameters")

    parser.add_argument('-nogui',
                        action='store_true',
                        default=DEFAULTS['nogui'],
                        help="Should GUI elements be supressed?")

    parser.add_argument('-showPlotAlready',
                        action='store_true',
                        default=DEFAULTS['showPlotAlready'],
                        help="Should generated plots be suppressed until show() called?")

    parser.add_argument('-verbose',
                        action='store_true',
                        default=DEFAULTS['verbose'],
                        help="Verbose mode")

    parser.add_argument('-dryRun',
                        action='store_true',
                        default=DEFAULTS['dryRun'],
                        help="Dry run; just print setup information")

    parser.add_argument('-extraReportInfo',
                        type=str,
                        metavar='<extraReportInfo>',
                        default=DEFAULTS['extraReportInfo'],
                        help='Extra tag/value pairs can be put into the report.json:  -extraReportInfo=["tag":"value"]')

    parser.add_argument('-cleanup',
                        action='store_true',
                        default=DEFAULTS['cleanup'],
                        help="Should (some) generated files, e.g. *.dat, be deleted as optimisation progresses?")

    return parser.parse_args()


Instruction:
Here you have a function in Python 3, explain what it does
def process_args():
    parser = argparse.ArgumentParser(description="A file for overlaying POVRay files generated from NeuroML by NeuroML1ToPOVRay.py with cell activity (e.g. as generated from a neuroConstruct simulation)")

    parser.add_argument('prefix',
                        type=str,
                        metavar='<network prefix>',
                        help='Prefix for files in PovRay, e.g. use PREFIX is files are PREFIX.pov, PREFIX_net.inc, etc.')

    parser.add_argument('-activity',
                        action='store_true',
                        default=False,
                        help="If this is specified, overlay network activity (not tested!!)")

    parser.add_argument('-maxV',
                        type=float,
                        metavar='<maxV>',
                        default=50.0,
                        help='Max voltage for colour scale in mV')

    parser.add_argument('-minV',
                        type=float,
                        metavar='<minV>',
                        default=-90.0,
                        help='Min voltage for colour scale in mV')

    parser.add_argument('-startTime',
                        type=float,
                        metavar='<startTime>',
                        default=0,
                        help='Time in ms at which to start overlaying the simulation activity')

    parser.add_argument('-endTime',
                        type=float,
                        metavar='<endTime>',
                        default=100,
                        help='End time of simulation activity in ms')

    parser.add_argument('-title',
                        type=str,
                        metavar='<title>',
                        default='Movie generated from neuroConstruct simulation',
                        help='Title for movie')

    parser.add_argument('-left',
                        type=str,
                        metavar='<left info>',
                        default='',
                        help='Text on left')

    parser.add_argument('-frames',
                        type=int,
                        metavar='<frames>',
                        default=100,
                        help='Number of frames')

    parser.add_argument('-name',
                        type=str,
                        metavar='<Movie name>',
                        default='output',
                        help='Movie name')

    return parser.parse_args()

Response: Parse command - line arguments and return a list of the resulting objects.


Instruction:
Create a Python 3 function for
parsing command line arguments

Response:
def parse_arguments():
    """Parse command line arguments"""

    import argparse

    parser = argparse.ArgumentParser(
            description=('pyNeuroML v%s: Python utilities for NeuroML2' % __version__
                          + "\n    libNeuroML v%s"%(neuroml.__version__)
                          + "\n    jNeuroML v%s"%JNEUROML_VERSION),
            usage=('pynml [-h|--help] [<shared options>] '
                   '<one of the mutually-exclusive options>'),
            formatter_class=argparse.RawTextHelpFormatter
            )

    shared_options = parser.add_argument_group(
            title='Shared options',
            description=('These options can be added to any of the '
                         'mutually-exclusive options')
            )

    shared_options.add_argument(
            '-verbose',
            action='store_true',
            default=DEFAULTS['v'],
            help='Verbose output'
            )
    shared_options.add_argument(
            '-java_max_memory',
            metavar='MAX',
            default=DEFAULTS['default_java_max_memory'],
            help=('Java memory for jNeuroML, e.g. 400M, 2G (used in\n'
                  '-Xmx argument to java)')
            )
    shared_options.add_argument(
            '-nogui',
            action='store_true',
            default=DEFAULTS['nogui'],
            help=('Suppress GUI,\n'
                  'i.e. show no plots, just save results')
            )

    shared_options.add_argument(
            'lems_file',
            type=str,
            metavar='<LEMS/NeuroML 2 file>',
            help='LEMS/NeuroML 2 file to process'
            )

    mut_exc_opts_grp = parser.add_argument_group(
            title='Mutually-exclusive options',
            description='Only one of these options can be selected'
            )
    mut_exc_opts = mut_exc_opts_grp.add_mutually_exclusive_group(required=False)

    mut_exc_opts.add_argument(
            '-sedml',
            action='store_true',
            help=('(Via jNeuroML) Load a LEMS file, and convert\n'
                  'simulation settings (duration, dt, what to save)\n'
                  'to SED-ML format')
            )
    mut_exc_opts.add_argument(
            '-neuron',
            nargs=argparse.REMAINDER,
            help=('(Via jNeuroML) Load a LEMS file, and convert it to\n'
                  'NEURON format.\n'
                  'The full format of the \'-neuron\' option is:\n'
                  '-neuron [-nogui] [-run] [-outputdir dir] <LEMS file>\n'
                  '    -nogui\n'
                  '        do not generate gtaphical elements in NEURON,\n'
                  '        just run, save data, and quit\n'
                  '    -run\n'
                  '        compile NMODL files and run the main NEURON\n'
                  '        hoc file (Linux only currently)\n'
                  '    -outputdir <dir>\n'
                  '        generate NEURON files in directory <dir>\n'
                  '    <LEMS file>\n'
                  '        the LEMS file to use')
            )
    mut_exc_opts.add_argument(
            '-svg',
            action='store_true',
            help=('(Via jNeuroML) Convert NeuroML2 file (network & cells)\n'
                  'to SVG format view of 3D structure')
            )
    mut_exc_opts.add_argument(
            '-png',
            action='store_true',
            help=('(Via jNeuroML) Convert NeuroML2 file (network & cells)\n'
                  'to PNG format view of 3D structure')
            )
    mut_exc_opts.add_argument(
            '-dlems',
            action='store_true',
            help=('(Via jNeuroML) Load a LEMS file, and convert it\n'
                  'to dLEMS format, a distilled form of LEMS in JSON')
            )
    mut_exc_opts.add_argument(
            '-vertex',
            action='store_true',
            help=('(Via jNeuroML) Load a LEMS file, and convert it\n'
                  'to VERTEX format')
            )
    mut_exc_opts.add_argument(
            '-xpp',
            action='store_true',
            help=('(Via jNeuroML) Load a LEMS file, and convert it\n'
                  'to XPPAUT format')
            )
    mut_exc_opts.add_argument(
            '-dnsim',
            action='store_true',
            help=('(Via jNeuroML) Load a LEMS file, and convert it\n'
                  'to DNsim format')
            )
    mut_exc_opts.add_argument(
            '-brian',
            action='store_true',
            help=('(Via jNeuroML) Load a LEMS file, and convert it\n'
                  'to Brian format')
            )
    mut_exc_opts.add_argument(
            '-sbml',
            action='store_true',
            help=('(Via jNeuroML) Load a LEMS file, and convert it\n'
                  'to SBML format')
            )
    mut_exc_opts.add_argument(
            '-matlab',
            action='store_true',
            help=('(Via jNeuroML) Load a LEMS file, and convert it\n'
                  'to MATLAB format')
            )
    mut_exc_opts.add_argument(
            '-cvode',
            action='store_true',
            help=('(Via jNeuroML) Load a LEMS file, and convert it\n'
                  'to C format using CVODE package')
            )
    mut_exc_opts.add_argument(
            '-nineml',
            action='store_true',
            help=('(Via jNeuroML) Load a LEMS file, and convert it\n'
                  'to NineML format')
            )
    mut_exc_opts.add_argument(
            '-spineml',
            action='store_true',
            help=('(Via jNeuroML) Load a LEMS file, and convert it\n'
                  'to SpineML format')
            )
    mut_exc_opts.add_argument(
            '-sbml-import',
            metavar=('<SBML file>', 'duration', 'dt'),
            nargs=3,
            help=('(Via jNeuroML) Load a SBML file, and convert it\n'
                  'toLEMS format using values for duration & dt\n'
                  'in ms (ignoring SBML units)')
            )
    mut_exc_opts.add_argument(
            '-sbml-import-units',
            metavar=('<SBML file>', 'duration', 'dt'),
            nargs=3,
            help=('(Via jNeuroML) Load a SBML file, and convert it\n'
                  'to LEMS format using values for duration & dt\n'
                  'in ms (attempt to extract SBML units; ensure units\n'
                  'are valid in the SBML!)')
            )
    mut_exc_opts.add_argument(
            '-vhdl',
            metavar=('neuronid', '<LEMS file>'),
            nargs=2,
            help=('(Via jNeuroML) Load a LEMS file, and convert it\n'
                  'to VHDL format')
            )
    mut_exc_opts.add_argument(
            '-graph',
            metavar=('level'),
            nargs=1,
            help=('Load a NeuroML file, and convert it to a graph using\n'
                  'GraphViz. Detail is set by level (1, 2, etc.)')
            )
    mut_exc_opts.add_argument(
            '-matrix',
            metavar=('level'),
            nargs=1,
            help=('Load a NeuroML file, and convert it to a matrix displaying\n'
                  'connectivity. Detail is set by level (1, 2, etc.)')
            )
    mut_exc_opts.add_argument(
            '-validate',
            action='store_true',
            help=('(Via jNeuroML) Validate NeuroML2 file(s) against the\n'
                  'latest Schema')
            )
    mut_exc_opts.add_argument(
            '-validatev1',
            action='store_true',
            help=('(Via jNeuroML) Validate NeuroML file(s) against the\n'
                  'v1.8.1 Schema')
            )

    return parser.parse_args()


Instruction:
Can you implement a function in Python 3 that
returns a string that can be used to display a summary of the contents of a NeuroML 2 document.

Response:
def quick_summary(nml2_doc):
    '''
    Or better just use nml2_doc.summary(show_includes=False)
    '''

    info = 'Contents of NeuroML 2 document: %s\n'%nml2_doc.id
    membs = inspect.getmembers(nml2_doc)

    for memb in membs:

        if isinstance(memb[1], list) and len(memb[1])>0 \
                and not memb[0].endswith('_'):
            info+='  %s:\n    ['%memb[0]
            for entry in memb[1]:
                extra = '???'
                extra = entry.name if hasattr(entry,'name') else extra
                extra = entry.href if hasattr(entry,'href') else extra
                extra = entry.id if hasattr(entry,'id') else extra

                info+=" %s (%s),"%(entry, extra)

            info+=']\n'
    return info


Instruction:
Can you create a Python 3 function that
executes a command in a specific working directory

Response:
def execute_command_in_dir(command, directory, verbose=DEFAULTS['v'],
                           prefix="Output: ", env=None):

    """Execute a command in specific working directory"""

    if os.name == 'nt':
        directory = os.path.normpath(directory)

    print_comment("Executing: (%s) in directory: %s" % (command, directory),
                  verbose)
    if env is not None:
        print_comment("Extra env variables %s" % (env), verbose)

    try:
        if os.name == 'nt':
            return_string = subprocess.check_output(command,
                                                    cwd=directory,
                                                    shell=True,
                                                    env=env,
                                                    close_fds=False)
        else:
            return_string = subprocess.check_output(command,
                                                    cwd=directory,
                                                    shell=True,
                                                    stderr=subprocess.STDOUT,
                                                    env=env,
                                                    close_fds=True)

        return_string = return_string.decode("utf-8") # For Python 3

        print_comment('Command completed. Output: \n %s%s' % \
                      (prefix,return_string.replace('\n','\n '+prefix)),
                      verbose)

        return return_string

    except AttributeError:
        # For python 2.6...
        print_comment_v('Assuming Python 2.6...')

        return_string = subprocess.Popen(command,
                                         cwd=directory,
                                         shell=True,
                                         stdout=subprocess.PIPE).communicate()[0]
        return return_string

    except subprocess.CalledProcessError as e:

        print_comment_v('*** Problem running command: \n       %s'%e)
        print_comment_v('%s%s'%(prefix,e.output.decode().replace('\n','\n'+prefix)))

        return None

    except:
        print_comment_v('*** Unknown problem running command: %s'%e)

        return None

    print_comment("Finished execution", verbose)


Instruction:
Make a summary of the following Python 3 code
def evaluate_component(comp_type, req_variables={}, parameter_values={}):

    print_comment('Evaluating %s with req:%s; params:%s'%(comp_type.name,req_variables,parameter_values))
    exec_str = ''
    return_vals = {}
    from math import exp
    for p in parameter_values:
        exec_str+='%s = %s\n'%(p, get_value_in_si(parameter_values[p]))
    for r in req_variables:
        exec_str+='%s = %s\n'%(r, get_value_in_si(req_variables[r]))
    for c in comp_type.Constant:
        exec_str+='%s = %s\n'%(c.name, get_value_in_si(c.value))
    for d in comp_type.Dynamics:
        for dv in d.DerivedVariable:
            exec_str+='%s = %s\n'%(dv.name, dv.value)
            exec_str+='return_vals["%s"] = %s\n'%(dv.name, dv.name)
        for cdv in d.ConditionalDerivedVariable:
            for case in cdv.Case:
                if case.condition:
                    cond = case.condition.replace('.neq.','!=').replace('.eq.','==').replace('.gt.','<').replace('.lt.','<')
                    exec_str+='if ( %s ): %s = %s \n'%(cond, cdv.name, case.value)
                else:
                    exec_str+='else: %s = %s \n'%(cdv.name, case.value)

            exec_str+='\n'

            exec_str+='return_vals["%s"] = %s\n'%(cdv.name, cdv.name)

    '''print_comment_v(exec_str)'''
    exec(exec_str)

    return return_vals

Response: Evaluate the component with the given set of parameters.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def after(self, context, exc=None):

		duration = context._duration = round((time.time() - context._start_time) * 1000)  # Convert to ms.
		delta = unicode(duration)

		# Default response augmentation.
		if self.header:
			context.response.headers[self.header] = delta

		if self.log:
			self.log("Response generated in " + delta + " seconds.", extra=dict(
					duration = duration,
					request = id(context)
				))

Response: Executed after dispatch has returned and the response populated prior to any other request.


Instruction:
How would you code a function in Python 3 to
apply a flat namespace transformation to recreate a rich structure.

Response:
def _process_flat_kwargs(source, kwargs):
		"""Apply a flat namespace transformation to recreate (in some respects) a rich structure.

		This applies several transformations, which may be nested:

		`foo` (singular): define a simple value named `foo`
		`foo` (repeated): define a simple value for placement in an array named `foo`
		`foo[]`: define a simple value for placement in an array, even if there is only one
		`foo.<id>`: define a simple value to place in the `foo` array at the identified index

		By nesting, you may define deeper, more complex structures:

		`foo.bar`: define a value for the named element `bar` of the `foo` dictionary
		`foo.<id>.bar`: define a `bar` dictionary element on the array element marked by that ID

		References to `<id>` represent numeric "attributes", which makes the parent reference be treated as an array,
		not a dictionary. Exact indexes might not be able to be preserved if there are voids; Python lists are not
		sparse.

		No validation of values is performed.
		"""

		ordered_arrays = []

		# Process arguments one at a time and apply them to the kwargs passed in.

		for name, value in source.items():
			container = kwargs

			if '.' in name:
				parts = name.split('.')
				name = name.rpartition('.')[2]

				for target, following in zip(parts[:-1], parts[1:]):
					if following.isnumeric():  # Prepare any use of numeric IDs.
						container.setdefault(target, [{}])
						if container[target] not in ordered_arrays:
							ordered_arrays.append(container[target])
						container = container[target][0]
						continue

					container = container.setdefault(target, {})

			if name.endswith('[]'):  # `foo[]` or `foo.bar[]` etc.
				name = name[:-2]
				container.setdefault(name, [])
				container[name].append(value)
				continue

			if name.isnumeric() and container is not kwargs:  # trailing identifiers, `foo.<id>`
				container[int(name)] = value
				continue

			if name in container:
				if not isinstance(container[name], list):
					container[name] = [container[name]]

				container[name].append(value)
				continue

			container[name] = value

		for container in ordered_arrays:
			elements = container[0]
			del container[:]
			container.extend(value for name, value in sorted(elements.items()))