Instruction:
How would you implement a function in Python 3 that
converts padding layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras layers

Response:
def convert_padding(params, w_name, scope_name, inputs, layers, weights, names):
    """
    Convert padding layer.

    Args:
        params: dictionary with layer parameters
        w_name: name prefix in state_dict
        scope_name: pytorch scope name
        inputs: pytorch node inputs
        layers: dictionary with keras tensors
        weights: pytorch state_dict
        names: use short names for keras layers
    """
    print('Converting padding...')

    if params['mode'] == 'constant':
        # raise AssertionError('Cannot convert non-constant padding')

        if params['value'] != 0.0:
            raise AssertionError('Cannot convert non-zero padding')

        if names:
            tf_name = 'PADD' + random_string(4)
        else:
            tf_name = w_name + str(random.random())

        # Magic ordering
        padding_name = tf_name
        padding_layer = keras.layers.ZeroPadding2D(
            padding=((params['pads'][2], params['pads'][6]), (params['pads'][3], params['pads'][7])),
            name=padding_name
        )

        layers[scope_name] = padding_layer(layers[inputs[0]])
    elif params['mode'] == 'reflect':

        def target_layer(x, pads=params['pads']):
            # x = tf.transpose(x, [0, 2, 3, 1])
            layer = tf.pad(x, [[0, 0], [0, 0], [pads[2], pads[6]], [pads[3], pads[7]]], 'REFLECT')
            # layer = tf.transpose(layer, [0, 3, 1, 2])
            return layer

        lambda_layer = keras.layers.Lambda(target_layer)
        layers[scope_name] = lambda_layer(layers[inputs[0]])


Instruction:
Can you tell what is the following Python 3 function doing
def convert_batchnorm(params, w_name, scope_name, inputs, layers, weights, names):
    print('Converting batchnorm ...')

    if names == 'short':
        tf_name = 'BN' + random_string(6)
    elif names == 'keep':
        tf_name = w_name
    else:
        tf_name = w_name + str(random.random())

    bias_name = '{0}.bias'.format(w_name)
    weights_name = '{0}.weight'.format(w_name)
    mean_name = '{0}.running_mean'.format(w_name)
    var_name = '{0}.running_var'.format(w_name)

    if bias_name in weights:
        beta = weights[bias_name].numpy()

    if weights_name in weights:
        gamma = weights[weights_name].numpy()

    mean = weights[mean_name].numpy()
    variance = weights[var_name].numpy()

    eps = params['epsilon']
    momentum = params['momentum']

    if weights_name not in weights:
        bn = keras.layers.BatchNormalization(
            axis=1, momentum=momentum, epsilon=eps,
            center=False, scale=False,
            weights=[mean, variance],
            name=tf_name
        )
    else:
        bn = keras.layers.BatchNormalization(
            axis=1, momentum=momentum, epsilon=eps,
            weights=[gamma, beta, mean, variance],
            name=tf_name
        )
    layers[scope_name] = bn(layers[inputs[0]])

Response: Convert batch normalization layer.


Instruction:
How would you implement a function in Python 3 that
converts instance normalization layer.

Response:
def convert_instancenorm(params, w_name, scope_name, inputs, layers, weights, names):
    """
    Convert instance normalization layer.

    Args:
        params: dictionary with layer parameters
        w_name: name prefix in state_dict
        scope_name: pytorch scope name
        inputs: pytorch node inputs
        layers: dictionary with keras tensors
        weights: pytorch state_dict
        names: use short names for keras layers
    """
    print('Converting instancenorm ...')

    if names == 'short':
        tf_name = 'IN' + random_string(6)
    elif names == 'keep':
        tf_name = w_name
    else:
        tf_name = w_name + str(random.random())

    assert(len(inputs) == 3)

    bias_name = '{0}.bias'.format(w_name)
    weights_name = '{0}.weight'.format(w_name)

    # Use previously taken constants
    if inputs[-2] + '_np' in layers:
        gamma = layers[inputs[-2] + '_np']
    else:
        gamma = weights[weights_name].numpy()

    if inputs[-1] + '_np' in layers:
        beta = layers[inputs[-1] + '_np']
    else:
        beta = weights[bias_name].numpy()

    def target_layer(x, epsilon=params['epsilon'], gamma=gamma, beta=beta):
        layer = tf.contrib.layers.instance_norm(
            x,
            param_initializers={'beta': tf.constant_initializer(beta), 'gamma': tf.constant_initializer(gamma)},
            epsilon=epsilon, data_format='NCHW',
            trainable=False
        )
        return layer

    lambda_layer = keras.layers.Lambda(target_layer, name=tf_name)
    layers[scope_name] = lambda_layer(layers[inputs[0]])


Instruction:
How would you explain what the following Python 3 function does
def convert_dropout(params, w_name, scope_name, inputs, layers, weights, names):
    print('Converting dropout ...')

    if names == 'short':
        tf_name = 'DO' + random_string(6)
    elif names == 'keep':
        tf_name = w_name
    else:
        tf_name = w_name + str(random.random())

    dropout = keras.layers.Dropout(rate=params['ratio'], name=tf_name)
    layers[scope_name] = dropout(layers[inputs[0]])

Response: Convert dropout to keras. layers. Dropout


Instruction:
Given the following Python 3 function, write the documentation
def convert_relu(params, w_name, scope_name, inputs, layers, weights, names):
    print('Converting relu ...')

    if names == 'short':
        tf_name = 'RELU' + random_string(4)
    elif names == 'keep':
        tf_name = w_name
    else:
        tf_name = w_name + str(random.random())

    relu = keras.layers.Activation('relu', name=tf_name)
    layers[scope_name] = relu(layers[inputs[0]])

Response: Convert a keras relu layer.


Instruction:
How would you implement a function in Python 3 that
converts a leaky relu layer.

Response:
def convert_lrelu(params, w_name, scope_name, inputs, layers, weights, names):
    """
    Convert leaky relu layer.

   Args:
        params: dictionary with layer parameters
        w_name: name prefix in state_dict
        scope_name: pytorch scope name
        inputs: pytorch node inputs
        layers: dictionary with keras tensors
        weights: pytorch state_dict
        names: use short names for keras layers
    """
    print('Converting lrelu ...')

    if names == 'short':
        tf_name = 'lRELU' + random_string(3)
    elif names == 'keep':
        tf_name = w_name
    else:
        tf_name = w_name + str(random.random())

    leakyrelu = \
        keras.layers.LeakyReLU(alpha=params['alpha'], name=tf_name)
    layers[scope_name] = leakyrelu(layers[inputs[0]])


Instruction:
Can you write a function in Python 3 where it
converts a sigmoid layer.

Response:
def convert_sigmoid(params, w_name, scope_name, inputs, layers, weights, names):
    """
    Convert sigmoid layer.

    Args:
        params: dictionary with layer parameters
        w_name: name prefix in state_dict
        scope_name: pytorch scope name
        inputs: pytorch node inputs
        layers: dictionary with keras tensors
        weights: pytorch state_dict
        names: use short names for keras layers
    """
    print('Converting sigmoid ...')

    if names == 'short':
        tf_name = 'SIGM' + random_string(4)
    elif names == 'keep':
        tf_name = w_name
    else:
        tf_name = w_name + str(random.random())

    sigmoid = keras.layers.Activation('sigmoid', name=tf_name)
    layers[scope_name] = sigmoid(layers[inputs[0]])


Instruction:
Here you have a function in Python 3, explain what it does
def convert_softmax(params, w_name, scope_name, inputs, layers, weights, names):
    print('Converting softmax ...')

    if names == 'short':
        tf_name = 'SMAX' + random_string(4)
    elif names == 'keep':
        tf_name = w_name
    else:
        tf_name = w_name + str(random.random())

    def target_layer(x, dim=params['dim']):
        import keras
        return keras.activations.softmax(x, axis=dim)

    lambda_layer = keras.layers.Lambda(target_layer)
    layers[scope_name] = lambda_layer(layers[inputs[0]])

Response:
Convert softmax layer.

    Args:
        params: dictionary with layer parameters
        w_name: name prefix in state_dict
        scope_name: pytorch scope name
        inputs: pytorch node inputs
        layers: dictionary with keras tensors
        weights: pytorch state_dict
        names: use short names for keras layers


Instruction:
Here you have a function in Python 3, explain what it does
def convert_tanh(params, w_name, scope_name, inputs, layers, weights, names):
    print('Converting tanh ...')

    if names == 'short':
        tf_name = 'TANH' + random_string(4)
    elif names == 'keep':
        tf_name = w_name
    else:
        tf_name = w_name + str(random.random())

    tanh = keras.layers.Activation('tanh', name=tf_name)
    layers[scope_name] = tanh(layers[inputs[0]])

Response:
Convert tanh layer.

    Args:
        params: dictionary with layer parameters
        w_name: name prefix in state_dict
        scope_name: pytorch scope name
        inputs: pytorch node inputs
        layers: dictionary with keras tensors
        weights: pytorch state_dict
        names: use short names for keras layers


Instruction:
Write a Python 3 function that can
convert a hardtanh layer.

Response:
def convert_hardtanh(params, w_name, scope_name, inputs, layers, weights, names):
    """
    Convert hardtanh layer.

    Args:
        params: dictionary with layer parameters
        w_name: name prefix in state_dict
        scope_name: pytorch scope name
        inputs: pytorch node inputs
        layers: dictionary with keras tensors
        weights: pytorch state_dict
        names: use short names for keras layers
    """
    print('Converting hardtanh (clip) ...')

    def target_layer(x, max_val=float(params['max_val']), min_val=float(params['min_val'])):
        return tf.minimum(max_val, tf.maximum(min_val, x))

    lambda_layer = keras.layers.Lambda(target_layer)
    layers[scope_name] = lambda_layer(layers[inputs[0]])


Instruction:
How would you code a function in Python 3 to
convert selu layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras layers

Response:
def convert_selu(params, w_name, scope_name, inputs, layers, weights, names):
    """
    Convert selu layer.

    Args:
        params: dictionary with layer parameters
        w_name: name prefix in state_dict
        scope_name: pytorch scope name
        inputs: pytorch node inputs
        layers: dictionary with keras tensors
        weights: pytorch state_dict
        names: use short names for keras layers
    """
    print('Converting selu ...')

    if names == 'short':
        tf_name = 'SELU' + random_string(4)
    elif names == 'keep':
        tf_name = w_name
    else:
        tf_name = w_name + str(random.random())

    selu = keras.layers.Activation('selu', name=tf_name)
    layers[scope_name] = selu(layers[inputs[0]])


Instruction:
How would you explain what the following Python 3 function does
def convert_upsample_bilinear(params, w_name, scope_name, inputs, layers, weights, names):
    print('Converting upsample...')

    if names == 'short':
        tf_name = 'UPSL' + random_string(4)
    elif names == 'keep':
        tf_name = w_name
    else:
        tf_name = w_name + str(random.random())

    output_size = params['output_size']
    align_corners = params['align_corners'] > 0

    def target_layer(x, size=output_size, align_corners=align_corners):
        import tensorflow as tf
        x = tf.transpose(x, [0, 2, 3, 1])
        x = tf.image.resize_images(x, size, align_corners=align_corners)
        x = tf.transpose(x, [0, 3, 1, 2])
        return x

    lambda_layer = keras.layers.Lambda(target_layer)
    layers[scope_name] = lambda_layer(layers[inputs[0]])

Response: Convert a bilinear 2d layer from keras to a single 2d layer.


Instruction:
Can you write a function in Python 3 where it
converts nearest upsampling layer.

Response:
def convert_upsample(params, w_name, scope_name, inputs, layers, weights, names):
    """
    Convert nearest upsampling layer.

    Args:
        params: dictionary with layer parameters
        w_name: name prefix in state_dict
        scope_name: pytorch scope name
        inputs: pytorch node inputs
        layers: dictionary with keras tensors
        weights: pytorch state_dict
        names: use short names for keras layers
    """
    print('Converting upsample...')

    if params['mode'] != 'nearest':
        raise AssertionError('Cannot convert non-nearest upsampling')

    if names == 'short':
        tf_name = 'UPSL' + random_string(4)
    elif names == 'keep':
        tf_name = w_name
    else:
        tf_name = w_name + str(random.random())

    if 'height_scale' in params:
        scale = (params['height_scale'], params['width_scale'])
    elif len(inputs) == 2:
        scale = layers[inputs[-1] + '_np'][-2:]

    upsampling = keras.layers.UpSampling2D(
        size=scale, name=tf_name
    )
    layers[scope_name] = upsampling(layers[inputs[0]])


Instruction:
Write a Python 3 function that can
convert gather (embedding) layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras layers

Response:
def convert_gather(params, w_name, scope_name, inputs, layers, weights, names):
    """
    Convert gather (embedding) layer.

    Args:
        params: dictionary with layer parameters
        w_name: name prefix in state_dict
        scope_name: pytorch scope name
        inputs: pytorch node inputs
        layers: dictionary with keras tensors
        weights: pytorch state_dict
        names: use short names for keras layers
    """
    print('Converting embedding ...')

    if names == 'short':
        tf_name = 'EMBD' + random_string(4)
    elif names == 'keep':
        tf_name = w_name
    else:
        tf_name = w_name + str(random.random())

    weights_name = '{0}.weight'.format(w_name)

    W = weights[weights_name].numpy()
    input_channels, output_channels = W.shape

    keras_weights = [W]

    dense = keras.layers.Embedding(
        input_channels,
        weights=keras_weights, output_dim=output_channels, name=tf_name
    )
    layers[scope_name] = dense(layers[inputs[1]])


Instruction:
Write a Python 3 function that can
convert a PyTorch model to keras model.

Response:
def pytorch_to_keras(
    model, args, input_shapes,
    change_ordering=False, training=False, verbose=False, names=False,
):
    """
    By given pytorch model convert layers with specified convertors.

    Args:
        model: pytorch model
        args: pytorch model arguments
        input_shapes: keras input shapes (using for each InputLayer)
        change_ordering: change CHW to HWC
        training: switch model to training mode
        verbose: verbose output
        names: use short names, use random-suffix or keep original names for keras layers

    Returns:
        model: created keras model.
    """

    # PyTorch JIT tracing
    if isinstance(args, torch.autograd.Variable):
        args = (args, )

    # Workaround for previous versions
    if isinstance(input_shapes, tuple):
        input_shapes = [input_shapes]

    orig_state_dict_keys = _unique_state_dict(model).keys()

    with set_training(model, training):
        trace, torch_out = torch.jit.get_trace_graph(model, tuple(args))

    if orig_state_dict_keys != _unique_state_dict(model).keys():
        raise RuntimeError("state_dict changed after running the tracer; "
                           "something weird is happening in your model!")

    # _optimize_trace(trace, False)
    if version.parse('0.4.0') < version.parse(torch.__version__):
        trace.set_graph(_optimize_graph(trace.graph(), OperatorExportTypes.ONNX))
    else:
        trace.set_graph(_optimize_graph(trace.graph(), False))

    trace.graph().lint()

    if verbose:
        print(trace.graph())

    # Get all graph nodes
    nodes = list(trace.graph().nodes())

    # Optimize Flatten:
    # When we have something loke that:
    #
    # %523 : Long() = onnx::Constant[value={0}](), scope: ResNet
    # %524 : Dynamic = onnx::Shape(%522), scope: ResNet
    # %526 : Long() = onnx::Gather[axis=0](%524, %523), scope: ResNet
    # %527 : Long() = onnx::Constant[value={-1}](), scope: ResNet
    # %534 : Dynamic = onnx::Unsqueeze[axes=[0]](%526)
    # %535 : Dynamic = onnx::Unsqueeze[axes=[0]](%527)
    # %536 : Dynamic = onnx::Concat[axis=0](%534, %535)
    # %529 : Float(1, 512) = onnx::Reshape(%522, %536), scope: ResNet
    #
    # It's better to replace it with onnx::Flatten
    if six.PY3:
        from types import SimpleNamespace
        seq_to_find = \
            ['onnx::Constant', 'onnx::Shape', 'onnx::Gather',
             'onnx::Constant', 'onnx::Unsqueeze', 'onnx::Unsqueeze', 'onnx::Concat', 'onnx::Reshape']
        k = 0
        s = 0
        for i, node in enumerate(nodes):
            if node.kind() == seq_to_find[k]:
                if k == 0:
                    s = i
                k += 1
                if k == len(seq_to_find):
                    reshape_op = nodes[s + k - 1]
                    flatten_op = {
                        'kind': (lambda: 'onnx::Flatten'),
                        'attributeNames': (lambda: {}),
                        'outputs':  (lambda: list(reshape_op.outputs())),
                        'scopeName': (lambda: reshape_op.scopeName()),
                        'inputs': (lambda: list(reshape_op.inputs())[:1]),
                        '__str__': (lambda: reshape_op.__str__()),
                    }
                    nodes = nodes[:s] + [SimpleNamespace(**flatten_op)] + nodes[s+k:]
                    break
            else:
                k = 0
                s = -1

    # Collect graph inputs and outputs
    graph_outputs = [get_leaf_id(n) for n in trace.graph().outputs()]
    graph_inputs = [get_leaf_id(n) for n in trace.graph().inputs()]

    # Collect model state dict
    state_dict = _unique_state_dict(model)
    if verbose:
        print('Graph inputs:', graph_inputs)
        print('Graph outputs:', graph_outputs)
        print('State dict:', list(state_dict))

    import re
    import keras
    from keras import backend as K
    K.set_image_data_format('channels_first')

    layers = dict()
    keras_inputs = []
    for i in range(len(args)):
        layers[graph_inputs[i]] = keras.layers.InputLayer(
            input_shape=input_shapes[i], name='input{0}'.format(i)
        ).output
        keras_inputs.append(layers[graph_inputs[i]])

    outputs = []
    group_indices = defaultdict(lambda: 0, {})

    for node in nodes:
        node_inputs = list(node.inputs())
        node_input_names = []

        for node_input in node_inputs:
            node_input_names.append(get_leaf_id(node_input))

        node_type = node.kind()

        node_scope_name = node.scopeName()
        node_id = get_node_id(node)
        node_name_regex = re.findall(r'\[([\w\d.\-\[\]\s]+)\]', node_scope_name)

        try:
            int(node_name_regex[-1])
            node_weigth_group_name = '.'.join(
                node_name_regex[:-1]
            )
            node_weights_name = node_weigth_group_name + '.' + str(group_indices[node_weigth_group_name])
            group_indices[node_weigth_group_name] += 1

        except ValueError:
            node_weights_name = '.'.join(
                node_name_regex
            )
        except IndexError:
            node_weights_name = '.'.join(node_input_names)

        node_attrs = {k: node[k] for k in node.attributeNames()}

        node_outputs = list(node.outputs())
        node_outputs_names = []
        for node_output in node_outputs:
            if node_output.node().scopeName():
                node_outputs_names.append(node_output.node().scopeName())

        if verbose:
            print(' ____ ')
            print('graph node:', node_scope_name)
            print('node id:', node_id)
            print('type:', node_type)
            print('inputs:', node_input_names)
            print('outputs:', node_outputs_names)
            print('name in state_dict:', node_weights_name)
            print('attrs:', node_attrs)
            print('is_terminal:', node_id in graph_outputs)
        AVAILABLE_CONVERTERS[node_type](
            node_attrs,
            node_weights_name, node_id,
            node_input_names,
            layers, state_dict,
            names
        )
        if node_id in graph_outputs:
            outputs.append(layers[node_id])

    model = keras.models.Model(inputs=keras_inputs, outputs=outputs)

    if change_ordering:
        import numpy as np
        conf = model.get_config()

        for layer in conf['layers']:
            if layer['config'] and 'batch_input_shape' in layer['config']:
                layer['config']['batch_input_shape'] = \
                    tuple(np.reshape(np.array(
                        [
                            [None] +
                            list(layer['config']['batch_input_shape'][2:][:]) +
                            [layer['config']['batch_input_shape'][1]]
                        ]), -1
                    ))
            if layer['config'] and 'target_shape' in layer['config']:
                if len(list(layer['config']['target_shape'][1:][:])) > 0:
                    layer['config']['target_shape'] = \
                        tuple(np.reshape(np.array(
                            [
                                list(layer['config']['target_shape'][1:][:]),
                                layer['config']['target_shape'][0]
                            ]), -1
                        ),)

            if layer['config'] and 'data_format' in layer['config']:
                layer['config']['data_format'] = 'channels_last'
            if layer['config'] and 'axis' in layer['config']:
                layer['config']['axis'] = 3

        K.set_image_data_format('channels_last')
        model_tf_ordering = keras.models.Model.from_config(conf)

        # from keras.utils.layer_utils import convert_all_kernels_in_model
        # convert_all_kernels_in_model(model)

        for dst_layer, src_layer in zip(
            model_tf_ordering.layers, model.layers
        ):
            dst_layer.set_weights(src_layer.get_weights())

        model = model_tf_ordering

    print('Your model was (probably) successfully converted! '
          'Please, follow the repository https://github.com/nerox8664/pytorch2keras and give a star :)')
    return model


Instruction:
How would you code a function in Python 3 to
attempt to return a PWM instance for the current platform.

Response:
def get_platform_pwm(**keywords):
    """Attempt to return a PWM instance for the platform which the code is being
    executed on.  Currently supports only the Raspberry Pi using the RPi.GPIO
    library and Beaglebone Black using the Adafruit_BBIO library.  Will throw an
    exception if a PWM instance can't be created for the current platform.  The
    returned PWM object has the same interface as the RPi_PWM_Adapter and
    BBIO_PWM_Adapter classes.
    """
    plat = Platform.platform_detect()
    if plat == Platform.RASPBERRY_PI:
        import RPi.GPIO
        return RPi_PWM_Adapter(RPi.GPIO, **keywords)
    elif plat == Platform.BEAGLEBONE_BLACK:
        import Adafruit_BBIO.PWM
        return BBIO_PWM_Adapter(Adafruit_BBIO.PWM, **keywords)
    elif plat == Platform.UNKNOWN:
        raise RuntimeError('Could not determine platform.')


Instruction:
Given the following Python 3 function, write the documentation
def start(self, pin, dutycycle, frequency_hz=2000):
        if dutycycle < 0.0 or dutycycle > 100.0:
            raise ValueError('Invalid duty cycle value, must be between 0.0 to 100.0 (inclusive).')
        # Make pin an output.
        self.rpi_gpio.setup(pin, self.rpi_gpio.OUT)
        # Create PWM instance and save a reference for later access.
        self.pwm[pin] = self.rpi_gpio.PWM(pin, frequency_hz)
        # Start the PWM at the specified duty cycle.
        self.pwm[pin].start(dutycycle)

Response: Enable PWM output on specified pin.


Instruction:
Make a summary of the following Python 3 code
def set_duty_cycle(self, pin, dutycycle):
        if dutycycle < 0.0 or dutycycle > 100.0:
            raise ValueError('Invalid duty cycle value, must be between 0.0 to 100.0 (inclusive).')
        if pin not in self.pwm:
            raise ValueError('Pin {0} is not configured as a PWM.  Make sure to first call start for the pin.'.format(pin))
        self.pwm[pin].ChangeDutyCycle(dutycycle)

Response: Set percent duty cycle of PWM output on specified pin.


Instruction:
Can you generate the documentation for the following Python 3 function
def set_frequency(self, pin, frequency_hz):
        if pin not in self.pwm:
            raise ValueError('Pin {0} is not configured as a PWM.  Make sure to first call start for the pin.'.format(pin))
        self.pwm[pin].ChangeFrequency(frequency_hz)

Response: Set frequency of PWM output on specified pin.


Instruction:
How would you code a function in Python 3 to
stop PWM output on specified pin.

Response:
def stop(self, pin):
        """Stop PWM output on specified pin."""
        if pin not in self.pwm:
            raise ValueError('Pin {0} is not configured as a PWM.  Make sure to first call start for the pin.'.format(pin))
        self.pwm[pin].stop()
        del self.pwm[pin]


Instruction:
Make a summary of the following Python 3 code
def start(self, pin, dutycycle, frequency_hz=2000):
        if dutycycle < 0.0 or dutycycle > 100.0:
            raise ValueError('Invalid duty cycle value, must be between 0.0 to 100.0 (inclusive).')
        self.bbio_pwm.start(pin, dutycycle, frequency_hz)

Response: Enable PWM output on specified pin.


Instruction:
Make a summary of the following Python 3 code
def set_duty_cycle(self, pin, dutycycle):
        if dutycycle < 0.0 or dutycycle > 100.0:
            raise ValueError('Invalid duty cycle value, must be between 0.0 to 100.0 (inclusive).')
        self.bbio_pwm.set_duty_cycle(pin, dutycycle)

Response: Set percent duty cycle of PWM output on specified pin.


Instruction:
Can you write a function in Python 3 where it
detects if running on the Raspberry Pi or Beaglebone Black and return the platform type. Will return RASPBERRY_PI BEAGLEBONE_BLACK or UNKNOWN.

Response:
def platform_detect():
    """Detect if running on the Raspberry Pi or Beaglebone Black and return the
    platform type.  Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN."""
    # Handle Raspberry Pi
    pi = pi_version()
    if pi is not None:
        return RASPBERRY_PI

    # Handle Beaglebone Black
    # TODO: Check the Beaglebone Black /proc/cpuinfo value instead of reading
    # the platform.
    plat = platform.platform()
    if plat.lower().find('armv7l-with-debian') > -1:
        return BEAGLEBONE_BLACK
    elif plat.lower().find('armv7l-with-ubuntu') > -1:
        return BEAGLEBONE_BLACK
    elif plat.lower().find('armv7l-with-glibc2.4') > -1:
        return BEAGLEBONE_BLACK
    elif plat.lower().find('tegra-aarch64-with-ubuntu') > -1:
        return JETSON_NANO

    # Handle Minnowboard
    # Assumption is that mraa is installed
    try:
        import mraa
        if mraa.getPlatformName()=='MinnowBoard MAX':
            return MINNOWBOARD
    except ImportError:
        pass

    # Couldn't figure out the platform, just return unknown.
    return UNKNOWN


Instruction:
How would you implement a function in Python 3 that
sets the bit order of bits in the serial lines.

Response:
def set_bit_order(self, order):
        """Set order of bits to be read/written over serial lines.  Should be
        either MSBFIRST for most-significant first, or LSBFIRST for
        least-signifcant first.
        """
        if order == MSBFIRST:
            self._device.lsbfirst = False
        elif order == LSBFIRST:
            self._device.lsbfirst = True
        else:
            raise ValueError('Order must be MSBFIRST or LSBFIRST.')


Instruction:
Can you generate the documentation for the following Python 3 function
def set_mode(self,mode):
        if mode < 0 or mode > 3:
            raise ValueError('Mode must be a value 0, 1, 2, or 3.')
        self._device.mode(mode)

Response: Set SPI mode which controls clock polarity and phase.


Instruction:
Implement a function in Python 3 to
set the SPI mode.

Response:
def set_mode(self, mode):
        """Set SPI mode which controls clock polarity and phase.  Should be a
        numeric value 0, 1, 2, or 3.  See wikipedia page for details on meaning:
        http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
        """
        if mode < 0 or mode > 3:
            raise ValueError('Mode must be a value 0, 1, 2, or 3.')
        if mode & 0x02:
            # Clock is normally high in mode 2 and 3.
            self._clock_base = GPIO.HIGH
        else:
            # Clock is normally low in mode 0 and 1.
            self._clock_base = GPIO.LOW
        if mode & 0x01:
            # Read on trailing edge in mode 1 and 3.
            self._read_leading = False
        else:
            # Read on leading edge in mode 0 and 2.
            self._read_leading = True
        # Put clock into its base state.
        self._gpio.output(self._sclk, self._clock_base)


Instruction:
Can you generate the documentation for the following Python 3 function
def set_bit_order(self, order):
        # Set self._mask to the bitmask which points at the appropriate bit to
        # read or write, and appropriate left/right shift operator function for
        # reading/writing.
        if order == MSBFIRST:
            self._mask = 0x80
            self._write_shift = operator.lshift
            self._read_shift = operator.rshift
        elif order == LSBFIRST:
            self._mask = 0x01
            self._write_shift = operator.rshift
            self._read_shift = operator.lshift
        else:
            raise ValueError('Order must be MSBFIRST or LSBFIRST.')

Response: Sets the bit order of bits in the internal state of the object.


Instruction:
Given the following Python 3 function, write the documentation
def write(self, data, assert_ss=True, deassert_ss=True):
        # Fail MOSI is not specified.
        if self._mosi is None:
            raise RuntimeError('Write attempted with no MOSI pin specified.')
        if assert_ss and self._ss is not None:
            self._gpio.set_low(self._ss)
        for byte in data:
            for i in range(8):
                # Write bit to MOSI.
                if self._write_shift(byte, i) & self._mask:
                    self._gpio.set_high(self._mosi)
                else:
                    self._gpio.set_low(self._mosi)
                # Flip clock off base.
                self._gpio.output(self._sclk, not self._clock_base)
                # Return clock to base.
                self._gpio.output(self._sclk, self._clock_base)
        if deassert_ss and self._ss is not None:
            self._gpio.set_high(self._ss)

Response: Write a set of bytes to the SPI.


Instruction:
Write a Python 3 script for
reading a set of bytes from the SPI and return them as a bytearray.

Response:
def read(self, length, assert_ss=True, deassert_ss=True):
        """Half-duplex SPI read.  If assert_ss is true, the SS line will be
        asserted low, the specified length of bytes will be clocked in the MISO
        line, and if deassert_ss is true the SS line will be put back high.
        Bytes which are read will be returned as a bytearray object.
        """
        if self._miso is None:
            raise RuntimeError('Read attempted with no MISO pin specified.')
        if assert_ss and self._ss is not None:
            self._gpio.set_low(self._ss)
        result = bytearray(length)
        for i in range(length):
            for j in range(8):
                # Flip clock off base.
                self._gpio.output(self._sclk, not self._clock_base)
                # Handle read on leading edge of clock.
                if self._read_leading:
                    if self._gpio.is_high(self._miso):
                        # Set bit to 1 at appropriate location.
                        result[i] |= self._read_shift(self._mask, j)
                    else:
                        # Set bit to 0 at appropriate location.
                        result[i] &= ~self._read_shift(self._mask, j)
                # Return clock to base.
                self._gpio.output(self._sclk, self._clock_base)
                # Handle read on trailing edge of clock.
                if not self._read_leading:
                    if self._gpio.is_high(self._miso):
                        # Set bit to 1 at appropriate location.
                        result[i] |= self._read_shift(self._mask, j)
                    else:
                        # Set bit to 0 at appropriate location.
                        result[i] &= ~self._read_shift(self._mask, j)
        if deassert_ss and self._ss is not None:
            self._gpio.set_high(self._ss)
        return result


Instruction:
Implement a Python 3 function for
fulling - duplex SPI read and write.

Response:
def transfer(self, data, assert_ss=True, deassert_ss=True):
        """Full-duplex SPI read and write.  If assert_ss is true, the SS line
        will be asserted low, the specified bytes will be clocked out the MOSI
        line while bytes will also be read from the MISO line, and if
        deassert_ss is true the SS line will be put back high.  Bytes which are
        read will be returned as a bytearray object.
        """
        if self._mosi is None:
            raise RuntimeError('Write attempted with no MOSI pin specified.')
        if self._miso is None:
            raise RuntimeError('Read attempted with no MISO pin specified.')
        if assert_ss and self._ss is not None:
            self._gpio.set_low(self._ss)
        result = bytearray(len(data))
        for i in range(len(data)):
            for j in range(8):
                # Write bit to MOSI.
                if self._write_shift(data[i], j) & self._mask:
                    self._gpio.set_high(self._mosi)
                else:
                    self._gpio.set_low(self._mosi)
                # Flip clock off base.
                self._gpio.output(self._sclk, not self._clock_base)
                # Handle read on leading edge of clock.
                if self._read_leading:
                    if self._gpio.is_high(self._miso):
                        # Set bit to 1 at appropriate location.
                        result[i] |= self._read_shift(self._mask, j)
                    else:
                        # Set bit to 0 at appropriate location.
                        result[i] &= ~self._read_shift(self._mask, j)
                # Return clock to base.
                self._gpio.output(self._sclk, self._clock_base)
                # Handle read on trailing edge of clock.
                if not self._read_leading:
                    if self._gpio.is_high(self._miso):
                        # Set bit to 1 at appropriate location.
                        result[i] |= self._read_shift(self._mask, j)
                    else:
                        # Set bit to 0 at appropriate location.
                        result[i] &= ~self._read_shift(self._mask, j)
        if deassert_ss and self._ss is not None:
            self._gpio.set_high(self._ss)
        return result


Instruction:
Explain what the following Python 3 code does
def setup(self, pin, value):
        self._validate_pin(pin)
        # Set bit to 1 for input or 0 for output.
        if value == GPIO.IN:
            self.iodir[int(pin/8)] |= 1 << (int(pin%8))
        elif value == GPIO.OUT:
            self.iodir[int(pin/8)] &= ~(1 << (int(pin%8)))
        else:
            raise ValueError('Unexpected value.  Must be GPIO.IN or GPIO.OUT.')
        self.write_iodir()

Response: Set the input or output mode for a specified pin.


Instruction:
Implement a Python 3 function for
setting multiple pins high or low at once.

Response:
def output_pins(self, pins):
        """Set multiple pins high or low at once.  Pins should be a dict of pin
        name to pin value (HIGH/True for 1, LOW/False for 0).  All provided pins
        will be set to the given values.
        """
        [self._validate_pin(pin) for pin in pins.keys()]
        # Set each changed pin's bit.
        for pin, value in iter(pins.items()):
            if value:
                self.gpio[int(pin/8)] |= 1 << (int(pin%8))
            else:
                self.gpio[int(pin/8)] &= ~(1 << (int(pin%8)))
        # Write GPIO state.
        self.write_gpio()


Instruction:
Create a Python 3 function to
read multiple pins specified in the given list and return list of pin values GPIO. HIGH or GPIO. LOW if the pin is pulled low or GPIO. HIGH or GPIO. LOW if the pin is pulled high or GPIO. HIGH or GPIO. LOW if the pin is pulled low.

Response:
def input_pins(self, pins):
        """Read multiple pins specified in the given list and return list of pin values
        GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low.
        """
        [self._validate_pin(pin) for pin in pins]
        # Get GPIO state.
        self.gpio = self._device.readList(self.GPIO, self.gpio_bytes)
        # Return True if pin's bit is set.
        return [(self.gpio[int(pin/8)] & 1 << (int(pin%8))) > 0 for pin in pins]


Instruction:
Write a Python 3 function for
turning on the pull - up resistor for the specified pin.

Response:
def pullup(self, pin, enabled):
        """Turn on the pull-up resistor for the specified pin if enabled is True,
        otherwise turn off the pull-up resistor.
        """
        self._validate_pin(pin)
        if enabled:
            self.gppu[int(pin/8)] |= 1 << (int(pin%8))
        else:
            self.gppu[int(pin/8)] &= ~(1 << (int(pin%8)))
        self.write_gppu()


Instruction:
Can you create a Python 3 function that
writes the specified byte value to the GPIO registor.

Response:
def write_gpio(self, gpio=None):
        """Write the specified byte value to the GPIO registor.  If no value
        specified the current buffered value will be written.
        """
        if gpio is not None:
            self.gpio = gpio
        self._device.writeList(self.GPIO, self.gpio)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write_iodir(self, iodir=None):
        if iodir is not None:
            self.iodir = iodir
        self._device.writeList(self.IODIR, self.iodir)

Response: Writes the specified byte value to the IODIR registor.


Instruction:
Given the following Python 3 function, write the documentation
def write_gppu(self, gppu=None):
        if gppu is not None:
            self.gppu = gppu
        self._device.writeList(self.GPPU, self.gppu)

Response: Writes the specified byte value to the GPPU registor.


Instruction:
Can you generate the documentation for the following Python 3 function
def disable_FTDI_driver():
    logger.debug('Disabling FTDI driver.')
    if sys.platform == 'darwin':
        logger.debug('Detected Mac OSX')
        # Mac OS commands to disable FTDI driver.
        _check_running_as_root()
        subprocess.call('kextunload -b com.apple.driver.AppleUSBFTDI', shell=True)
        subprocess.call('kextunload /System/Library/Extensions/FTDIUSBSerialDriver.kext', shell=True)
    elif sys.platform.startswith('linux'):
        logger.debug('Detected Linux')
        # Linux commands to disable FTDI driver.
        _check_running_as_root()
        subprocess.call('modprobe -r -q ftdi_sio', shell=True)
        subprocess.call('modprobe -r -q usbserial', shell=True)

Response: Disable the FTDI driver for the current platform.


Instruction:
Can you generate the documentation for the following Python 3 function
def enumerate_device_serials(vid=FT232H_VID, pid=FT232H_PID):
    try:
        # Create a libftdi context.
        ctx = None
        ctx = ftdi.new()
        # Enumerate FTDI devices.
        device_list = None
        count, device_list = ftdi.usb_find_all(ctx, vid, pid)
        if count < 0:
            raise RuntimeError('ftdi_usb_find_all returned error {0}: {1}'.format(count, ftdi.get_error_string(self._ctx)))
        # Walk through list of devices and assemble list of serial numbers.
        devices = []
        while device_list is not None:
            # Get USB device strings and add serial to list of devices.
            ret, manufacturer, description, serial = ftdi.usb_get_strings(ctx, device_list.dev, 256, 256, 256)
            if serial is not None:
                devices.append(serial)
            device_list = device_list.next
        return devices
    finally:
        # Make sure to clean up list and context when done.
        if device_list is not None:
            ftdi.list_free(device_list)
        if ctx is not None:
            ftdi.free(ctx)

Response: Enumerate all USB device serial numbers connected to the FT232H machine.


Instruction:
Can you implement a function in Python 3 that
closes the FTDI device.

Response:
def close(self):
        """Close the FTDI device.  Will be automatically called when the program ends."""
        if self._ctx is not None:
            ftdi.free(self._ctx)
        self._ctx = None


Instruction:
Given the following Python 3 function, write the documentation
def _write(self, string):
        # Get modem status. Useful to enable for debugging.
        #ret, status = ftdi.poll_modem_status(self._ctx)
        #if ret == 0:
        #	logger.debug('Modem status {0:02X}'.format(status))
        #else:
        #	logger.debug('Modem status error {0}'.format(ret))
        length = len(string)
        try:
            ret = ftdi.write_data(self._ctx, string, length)
        except TypeError:
            ret = ftdi.write_data(self._ctx, string); #compatible with libFtdi 1.3
        # Log the string that was written in a python hex string format using a very
        # ugly one-liner list comprehension for brevity.
        #logger.debug('Wrote {0}'.format(''.join(['\\x{0:02X}'.format(ord(x)) for x in string])))
        if ret < 0:
            raise RuntimeError('ftdi_write_data failed with error {0}: {1}'.format(ret, ftdi.get_error_string(self._ctx)))
        if ret != length:
            raise RuntimeError('ftdi_write_data expected to write {0} bytes but actually wrote {1}!'.format(length, ret))

Response: Write a string to the FTDI device and verify it succeeds.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _check(self, command, *args):
        ret = command(self._ctx, *args)
        logger.debug('Called ftdi_{0} and got response {1}.'.format(command.__name__, ret))
        if ret != 0:
            raise RuntimeError('ftdi_{0} failed with error {1}: {2}'.format(command.__name__, ret, ftdi.get_error_string(self._ctx)))

Response: Helper function to call the provided command on the FTDI device and verify the response matches the expected value.


Instruction:
Create a Python 3 function for
enabling MPSSE mode on the FTDI device.

Response:
def _mpsse_enable(self):
        """Enable MPSSE mode on the FTDI device."""
        # Reset MPSSE by sending mask = 0 and mode = 0
        self._check(ftdi.set_bitmode, 0, 0)
        # Enable MPSSE by sending mask = 0 and mode = 2
        self._check(ftdi.set_bitmode, 0, 2)


Instruction:
Given the following Python 3 function, write the documentation
def _mpsse_sync(self, max_retries=10):
        # Send a bad/unknown command (0xAB), then read buffer until bad command
        # response is found.
        self._write('\xAB')
        # Keep reading until bad command response (0xFA 0xAB) is returned.
        # Fail if too many read attempts are made to prevent sticking in a loop.
        tries = 0
        sync = False
        while not sync:
            data = self._poll_read(2)
            if data == '\xFA\xAB':
                sync = True
            tries += 1
            if tries >= max_retries:
                raise RuntimeError('Could not synchronize with FT232H!')

Response:
Synchronize buffers with MPSSE by sending a bad opcode and reading expected
        error response. Should be called once after enabling MPSSE.


Instruction:
How would you explain what the following Python 3 function does
def mpsse_set_clock(self, clock_hz, adaptive=False, three_phase=False):
        # Disable clock divisor by 5 to enable faster speeds on FT232H.
        self._write('\x8A')
        # Turn on/off adaptive clocking.
        if adaptive:
            self._write('\x96')
        else:
            self._write('\x97')
        # Turn on/off three phase clock (needed for I2C).
        # Also adjust the frequency for three-phase clocking as specified in section 2.2.4
        # of this document:
        #   http://www.ftdichip.com/Support/Documents/AppNotes/AN_255_USB%20to%20I2C%20Example%20using%20the%20FT232H%20and%20FT201X%20devices.pdf
        if three_phase:
            self._write('\x8C')
        else:
            self._write('\x8D')
        # Compute divisor for requested clock.
        # Use equation from section 3.8.1 of:
        #  http://www.ftdichip.com/Support/Documents/AppNotes/AN_108_Command_Processor_for_MPSSE_and_MCU_Host_Bus_Emulation_Modes.pdf
        # Note equation is using 60mhz master clock instead of 12mhz.
        divisor = int(math.ceil((30000000.0-float(clock_hz))/float(clock_hz))) & 0xFFFF
        if three_phase:
            divisor = int(divisor*(2.0/3.0))
        logger.debug('Setting clockspeed with divisor value {0}'.format(divisor))
        # Send command to set divisor from low and high byte values.
        self._write(str(bytearray((0x86, divisor & 0xFF, (divisor >> 8) & 0xFF))))

Response: Set the clock speed of the MPSSE engine.


Instruction:
Create a Python 3 function for
reading both GPIO states and return a 16 bit value with their state.

Response:
def mpsse_read_gpio(self):
        """Read both GPIO bus states and return a 16 bit value with their state.
        D0-D7 are the lower 8 bits and C0-C7 are the upper 8 bits.
        """
        # Send command to read low byte and high byte.
        self._write('\x81\x83')
        # Wait for 2 byte response.
        data = self._poll_read(2)
        # Assemble response into 16 bit value.
        low_byte = ord(data[0])
        high_byte = ord(data[1])
        logger.debug('Read MPSSE GPIO low byte = {0:02X} and high byte = {1:02X}'.format(low_byte, high_byte))
        return (high_byte << 8) | low_byte


Instruction:
Create a Python 3 function to
return command to update the MPSSE GPIO state to the current direction and level.

Response:
def mpsse_gpio(self):
        """Return command to update the MPSSE GPIO state to the current direction
        and level.
        """
        level_low  = chr(self._level & 0xFF)
        level_high = chr((self._level >> 8) & 0xFF)
        dir_low  = chr(self._direction & 0xFF)
        dir_high = chr((self._direction >> 8) & 0xFF)
        return str(bytearray((0x80, level_low, dir_low, 0x82, level_high, dir_high)))


Instruction:
Make a summary of the following Python 3 code
def setup(self, pin, mode):
        self._setup_pin(pin, mode)
        self.mpsse_write_gpio()

Response: Set the input or output mode for a specified pin.


Instruction:
Can you write a function in Python 3 where it
sets the specified pin high or low value.

Response:
def output(self, pin, value):
        """Set the specified pin the provided high/low value.  Value should be
        either HIGH/LOW or a boolean (true = high)."""
        if pin < 0 or pin > 15:
            raise ValueError('Pin must be between 0 and 15 (inclusive).')
        self._output_pin(pin, value)
        self.mpsse_write_gpio()


Instruction:
Can you tell what is the following Python 3 function doing
def output_pins(self, pins, write=True):
        for pin, value in iter(pins.items()):
            self._output_pin(pin, value)
        if write:
            self.mpsse_write_gpio()

Response: Set multiple pins high or low at once.


Instruction:
Write a Python 3 function for
reading multiple pins specified in the given list and return list of pin values GPIO. HIGH or GPIO. LOW if the pin is pulled high or GPIO. HIGH or GPIO. LOW if the pin is pulled low or GPIO. HIGH or GPIO. LOW if the pin is pulled low.

Response:
def input_pins(self, pins):
        """Read multiple pins specified in the given list and return list of pin values
        GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low."""
        if [pin for pin in pins if pin < 0 or pin > 15]:
            raise ValueError('Pin must be between 0 and 15 (inclusive).')
        _pins = self.mpsse_read_gpio()
        return [((_pins >> pin) & 0x0001) == 1 for pin in pins]


Instruction:
Explain what the following Python 3 code does
def set_mode(self, mode):
        if mode < 0 or mode > 3:
            raise ValueError('Mode must be a value 0, 1, 2, or 3.')
        if mode == 0:
            # Mode 0 captures on rising clock, propagates on falling clock
            self.write_clock_ve = 1
            self.read_clock_ve  = 0
            # Clock base is low.
            clock_base = GPIO.LOW
        elif mode == 1:
            # Mode 1 capture of falling edge, propagate on rising clock
            self.write_clock_ve = 0
            self.read_clock_ve  = 1
            # Clock base is low.
            clock_base = GPIO.LOW
        elif mode == 2:
            # Mode 2 capture on rising clock, propagate on falling clock
            self.write_clock_ve = 1
            self.read_clock_ve  = 0
            # Clock base is high.
            clock_base = GPIO.HIGH
        elif mode == 3:
            # Mode 3 capture on falling edge, propagage on rising clock
            self.write_clock_ve = 0
            self.read_clock_ve  = 1
            # Clock base is high.
            clock_base = GPIO.HIGH
        # Set clock and DO as output, DI as input.  Also start clock at its base value.
        self._ft232h.setup_pins({0: GPIO.OUT, 1: GPIO.OUT, 2: GPIO.IN}, {0: clock_base})

Response:
Set SPI mode which controls clock polarity and phase.  Should be a
        numeric value 0, 1, 2, or 3.  See wikipedia page for details on meaning:
        http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus


Instruction:
Make a summary of the following Python 3 code
def set_bit_order(self, order):
        if order == MSBFIRST:
            self.lsbfirst = 0
        elif order == LSBFIRST:
            self.lsbfirst = 1
        else:
            raise ValueError('Order must be MSBFIRST or LSBFIRST.')

Response: Set the bit order of bits in the log file.


Instruction:
How would you explain what the following Python 3 function does
def read(self, length):
        #check for hardware limit of FT232H and similar MPSSE chips
        if (1 > length > 65536):
            print('the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!')
            print('use for loops for larger reads')
            exit(1)
        # Build command to read SPI data.
        command = 0x20 | (self.lsbfirst << 3) | (self.read_clock_ve << 2)
        logger.debug('SPI read with command {0:2X}.'.format(command))
        # Compute length low and high bytes.
        # NOTE: Must actually send length minus one because the MPSSE engine
        # considers 0 a length of 1 and FFFF a length of 65536
	#force odd numbers to round up instead of down
	lengthR = length
	if length % 2 == 1:
	    lengthR += 1
	lengthR = lengthR/2
	#when odd length requested, get the remainder instead of the same number
	lenremain = length - lengthR
        len_low  = (lengthR - 1) & 0xFF
        len_high = ((lengthR - 1) >> 8) & 0xFF
        self._assert_cs()
        # Send command and length.
        # Perform twice to prevent error from hardware defect/limits
        self._ft232h._write(str(bytearray((command, len_low, len_high))))
        payload1 = self._ft232h._poll_read(lengthR)
        self._ft232h._write(str(bytearray((command, len_low, len_high))))
        payload2 = self._ft232h._poll_read(lenremain)
        self._deassert_cs()
        # Read response bytes
        return bytearray(payload1 + payload2)

Response: Half - duplex SPI read.


Instruction:
Make a summary of the following Python 3 code
def _idle(self):
        # Put the I2C lines into an idle state with SCL and SDA high.
        self._ft232h.setup_pins({0: GPIO.OUT, 1: GPIO.OUT, 2: GPIO.IN},
                                {0: GPIO.HIGH, 1: GPIO.HIGH})

Response: Put the I2C lines into idle state.


Instruction:
Can you write a function in Python 3 where it
ends I2C transaction and get response bytes including ACKs.

Response:
def _transaction_end(self):
        """End I2C transaction and get response bytes, including ACKs."""
        # Ask to return response bytes immediately.
        self._command.append('\x87')
        # Send the entire command to the MPSSE.
        self._ft232h._write(''.join(self._command))
        # Read response bytes and return them.
        return bytearray(self._ft232h._poll_read(self._expected))


Instruction:
Can you tell what is the following Python 3 function doing
def _i2c_start(self):
        # Set SCL high and SDA low, repeat 4 times to stay in this state for a
        # short period of time.
        self._ft232h.output_pins({0: GPIO.HIGH, 1: GPIO.LOW}, write=False)
        self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
        # Now drop SCL to low (again repeat 4 times for short delay).
        self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.LOW}, write=False)
        self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)

Response: Send I2C start signal. Must be called within a transaction start or end.


Instruction:
Write a Python 3 script to
send I2C stop signal. Must be called within a transaction start or end.

Response:
def _i2c_stop(self):
        """Send I2C stop signal. Must be called within a transaction start/end.
        """
        # Set SCL low and SDA low for a short period.
        self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.LOW}, write=False)
        self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
        # Set SCL high and SDA low for a short period.
        self._ft232h.output_pins({0: GPIO.HIGH, 1: GPIO.LOW}, write=False)
        self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
        # Finally set SCL high and SDA high for a short period.
        self._ft232h.output_pins({0: GPIO.HIGH, 1: GPIO.HIGH}, write=False)
        self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)


Instruction:
How would you code a function in Python 3 to
read the specified number of bytes from the I2C bus.

Response:
def _i2c_read_bytes(self, length=1):
        """Read the specified number of bytes from the I2C bus.  Length is the
        number of bytes to read (must be 1 or more).
        """
        for i in range(length-1):
            # Read a byte and send ACK.
            self._command.append('\x20\x00\x00\x13\x00\x00')
            # Make sure pins are back in idle state with clock low and data high.
            self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.HIGH}, write=False)
            self._command.append(self._ft232h.mpsse_gpio())
        # Read last byte and send NAK.
        self._command.append('\x20\x00\x00\x13\x00\xFF')
        # Make sure pins are back in idle state with clock low and data high.
        self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.HIGH}, write=False)
        self._command.append(self._ft232h.mpsse_gpio())
        # Increase expected number of bytes.
        self._expected += length


Instruction:
Write a Python 3 function for
writing the specified number of bytes to the chip.

Response:
def _i2c_write_bytes(self, data):
        """Write the specified number of bytes to the chip."""
        for byte in data:
            # Write byte.
            self._command.append(str(bytearray((0x11, 0x00, 0x00, byte))))
            # Make sure pins are back in idle state with clock low and data high.
            self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.HIGH}, write=False)
            self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
            # Read bit for ACK/NAK.
            self._command.append('\x22\x00')
        # Increase expected response bytes.
        self._expected += len(data)


Instruction:
Explain what the following Python 3 code does
def ping(self):
        self._idle()
        self._transaction_start()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(False)])
        self._i2c_stop()
        response = self._transaction_end()
        if len(response) != 1:
            raise RuntimeError('Expected 1 response byte but received {0} byte(s).'.format(len(response)))
        return ((response[0] & 0x01) == 0x00)

Response:
Attempts to detect if a device at this address is present on the I2C
        bus. Returns True if the device is present and False otherwise.


Instruction:
Can you tell what is the following Python 3 function doing
def writeRaw8(self, value):
        value = value & 0xFF
        self._idle()
        self._transaction_start()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(False), value])
        self._i2c_stop()
        response = self._transaction_end()
        self._verify_acks(response)

Response: Write an 8 - bit value on the bus.


Instruction:
Implement a function in Python 3 to
write a 16 - bit value to the specified register.

Response:
def write16(self, register, value, little_endian=True):
        """Write a 16-bit value to the specified register."""
        value = value & 0xFFFF
        value_low  = value & 0xFF
        value_high = (value >> 8) & 0xFF
        if not little_endian:
            value_low, value_high = value_high, value_low
        self._idle()
        self._transaction_start()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(False), register, value_low,
                                value_high])
        self._i2c_stop()
        response = self._transaction_end()
        self._verify_acks(response)


Instruction:
Write a Python 3 script for
writing a list of bytes to the specified register.

Response:
def writeList(self, register, data):
        """Write bytes to the specified register."""
        self._idle()
        self._transaction_start()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(False), register] + data)
        self._i2c_stop()
        response = self._transaction_end()
        self._verify_acks(response)


Instruction:
Implement a function in Python 3 to
read a length number of bytes from the specified register.

Response:
def readList(self, register, length):
        """Read a length number of bytes from the specified register.  Results
        will be returned as a bytearray."""
        if length <= 0:
            raise ValueError("Length must be at least 1 byte.")
        self._idle()
        self._transaction_start()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(True), register])
        self._i2c_stop()
        self._i2c_idle()
        self._i2c_start()
        self._i2c_read_bytes(length)
        self._i2c_stop()
        response = self._transaction_end()
        self._verify_acks(response[:-length])
        return response[-length:]


Instruction:
Implement a Python 3 function for
reading an 8 - bit value on the bus.

Response:
def readRaw8(self):
        """Read an 8-bit value on the bus (without register)."""
        self._idle()
        self._transaction_start()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(False)])
        self._i2c_stop()
        self._i2c_idle()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(True)])
        self._i2c_read_bytes(1)
        self._i2c_stop()
        response = self._transaction_end()
        self._verify_acks(response[:-1])
        return response[-1]


Instruction:
Can you tell what is the following Python 3 function doing
def readS8(self, register):
        result = self.readU8(register)
        if result > 127:
            result -= 256
        return result

Response: Read a signed byte from the specified register.


Instruction:
Create a Python 3 function for
reading a signed 16 - bit value from the specified register.

Response:
def readS16(self, register, little_endian=True):
        """Read a signed 16-bit value from the specified register, with the
        specified endianness (default little endian, or least significant byte
        first)."""
        result = self.readU16(register, little_endian)
        if result > 32767:
            result -= 65536
        return result


Instruction:
Here you have a function in Python 3, explain what it does
def get_default_bus():
    plat = Platform.platform_detect()
    if plat == Platform.RASPBERRY_PI:
        if Platform.pi_revision() == 1:
            # Revision 1 Pi uses I2C bus 0.
            return 0
        else:
            # Revision 2 Pi uses I2C bus 1.
            return 1
    elif plat == Platform.BEAGLEBONE_BLACK:
        # Beaglebone Black has multiple I2C buses, default to 1 (P9_19 and P9_20).
        return 1
    else:
        raise RuntimeError('Could not determine default I2C bus for platform.')

Response: Return the default bus number based on the device platform.


Instruction:
How would you code a function in Python 3 to
return an I2C device for the specified address and on the specified bus.

Response:
def get_i2c_device(address, busnum=None, i2c_interface=None, **kwargs):
    """Return an I2C device for the specified address and on the specified bus.
    If busnum isn't specified, the default I2C bus for the platform will attempt
    to be detected.
    """
    if busnum is None:
        busnum = get_default_bus()
    return Device(address, busnum, i2c_interface, **kwargs)


Instruction:
Write a Python 3 script to
enable repeated start conditions for I2C register reads.

Response:
def require_repeated_start():
    """Enable repeated start conditions for I2C register reads.  This is the
    normal behavior for I2C, however on some platforms like the Raspberry Pi
    there are bugs which disable repeated starts unless explicitly enabled with
    this function.  See this thread for more details:
      http://www.raspberrypi.org/forums/viewtopic.php?f=44&t=15840
    """
    plat = Platform.platform_detect()
    if plat == Platform.RASPBERRY_PI and os.path.exists('/sys/module/i2c_bcm2708/parameters/combined'):
        # On the Raspberry Pi there is a bug where register reads don't send a
        # repeated start condition like the kernel smbus I2C driver functions
        # define.  As a workaround this bit in the BCM2708 driver sysfs tree can
        # be changed to enable I2C repeated starts.
        subprocess.check_call('chmod 666 /sys/module/i2c_bcm2708/parameters/combined', shell=True)
        subprocess.check_call('echo -n 1 > /sys/module/i2c_bcm2708/parameters/combined', shell=True)


Instruction:
How would you implement a function in Python 3 that
writes an 8 - bit value on the bus.

Response:
def writeRaw8(self, value):
        """Write an 8-bit value on the bus (without register)."""
        value = value & 0xFF
        self._bus.write_byte(self._address, value)
        self._logger.debug("Wrote 0x%02X",
                     value)


Instruction:
Create a Python 3 function for
writing an 8 - bit value to the specified register.

Response:
def write8(self, register, value):
        """Write an 8-bit value to the specified register."""
        value = value & 0xFF
        self._bus.write_byte_data(self._address, register, value)
        self._logger.debug("Wrote 0x%02X to register 0x%02X",
                     value, register)


Instruction:
Explain what the following Python 3 code does
def write16(self, register, value):
        value = value & 0xFFFF
        self._bus.write_word_data(self._address, register, value)
        self._logger.debug("Wrote 0x%04X to register pair 0x%02X, 0x%02X",
                     value, register, register+1)

Response: Write a 16 - bit value to the specified register.


Instruction:
Implement a Python 3 function for
writing a list of bytes to the specified register.

Response:
def writeList(self, register, data):
        """Write bytes to the specified register."""
        self._bus.write_i2c_block_data(self._address, register, data)
        self._logger.debug("Wrote to register 0x%02X: %s",
                     register, data)


Instruction:
Write a Python 3 function that can
read a length number of bytes from the specified register.

Response:
def readList(self, register, length):
        """Read a length number of bytes from the specified register.  Results
        will be returned as a bytearray."""
        results = self._bus.read_i2c_block_data(self._address, register, length)
        self._logger.debug("Read the following from register 0x%02X: %s",
                     register, results)
        return results


Instruction:
Create a Python 3 function for
reading an 8 - bit value on the bus.

Response:
def readRaw8(self):
        """Read an 8-bit value on the bus (without register)."""
        result = self._bus.read_byte(self._address) & 0xFF
        self._logger.debug("Read 0x%02X",
                    result)
        return result


Instruction:
How would you implement a function in Python 3 that
reads an unsigned byte from the specified register.

Response:
def readU8(self, register):
        """Read an unsigned byte from the specified register."""
        result = self._bus.read_byte_data(self._address, register) & 0xFF
        self._logger.debug("Read 0x%02X from register 0x%02X",
                     result, register)
        return result


Instruction:
Create a Python 3 function to
read an unsigned 16 - bit value from the specified register.

Response:
def readU16(self, register, little_endian=True):
        """Read an unsigned 16-bit value from the specified register, with the
        specified endianness (default little endian, or least significant byte
        first)."""
        result = self._bus.read_word_data(self._address,register) & 0xFFFF
        self._logger.debug("Read 0x%04X from register pair 0x%02X, 0x%02X",
                           result, register, register+1)
        # Swap bytes if using big endian because read_word_data assumes little
        # endian on ARM (little endian) systems.
        if not little_endian:
            result = ((result << 8) & 0xFF00) + (result >> 8)
        return result


Instruction:
Create a Python 3 function to
attempt to return a GPIO instance for the current platform.

Response:
def get_platform_gpio(**keywords):
    """Attempt to return a GPIO instance for the platform which the code is being
    executed on.  Currently supports only the Raspberry Pi using the RPi.GPIO
    library and Beaglebone Black using the Adafruit_BBIO library.  Will throw an
    exception if a GPIO instance can't be created for the current platform.  The
    returned GPIO object is an instance of BaseGPIO.
    """
    plat = Platform.platform_detect()
    if plat == Platform.RASPBERRY_PI:
        import RPi.GPIO
        return RPiGPIOAdapter(RPi.GPIO, **keywords)
    elif plat == Platform.BEAGLEBONE_BLACK:
        import Adafruit_BBIO.GPIO
        return AdafruitBBIOAdapter(Adafruit_BBIO.GPIO, **keywords)
    elif plat == Platform.MINNOWBOARD:
        import mraa
        return AdafruitMinnowAdapter(mraa, **keywords)
    elif plat == Platform.JETSON_NANO:
        import Jetson.GPIO
        return RPiGPIOAdapter(Jetson.GPIO, **keywords)
    elif plat == Platform.UNKNOWN:
        raise RuntimeError('Could not determine platform.')


Instruction:
Implement a Python 3 function for
setting multiple pins high or low at once.

Response:
def output_pins(self, pins):
        """Set multiple pins high or low at once.  Pins should be a dict of pin
        name to pin value (HIGH/True for 1, LOW/False for 0).  All provided pins
        will be set to the given values.
        """
        # General implementation just loops through pins and writes them out
        # manually.  This is not optimized, but subclasses can choose to implement
        # a more optimal batch output implementation.  See the MCP230xx class for
        # example of optimized implementation.
        for pin, value in iter(pins.items()):
            self.output(pin, value)


Instruction:
Make a summary of the following Python 3 code
def setup_pins(self, pins):
        # General implementation that can be optimized by derived classes.
        for pin, value in iter(pins.items()):
            self.setup(pin, value)

Response: Setup multiple pins as inputs or outputs at once.


Instruction:
Can you generate the documentation for the following Python 3 function
def setup(self, pin, mode, pull_up_down=PUD_OFF):
        self.rpi_gpio.setup(pin, self._dir_mapping[mode],
                            pull_up_down=self._pud_mapping[pull_up_down])

Response: Set the input or output mode for a specified pin.


Instruction:
Can you generate the documentation for the following Python 3 function
def add_event_detect(self, pin, edge, callback=None, bouncetime=-1):
        kwargs = {}
        if callback:
            kwargs['callback']=callback
        if bouncetime > 0:
            kwargs['bouncetime']=bouncetime
        self.rpi_gpio.add_event_detect(pin, self._edge_mapping[edge], **kwargs)

Response: Enable edge detection events for a particular GPIO channel.


Instruction:
Can you create a Python 3 function that
waits for an edge. Pin should be type IN

Response:
def wait_for_edge(self, pin, edge):
        """Wait for an edge.   Pin should be type IN.  Edge must be RISING,
        FALLING or BOTH.
        """
        self.rpi_gpio.wait_for_edge(pin, self._edge_mapping[edge])


Instruction:
Here you have a function in Python 3, explain what it does
def cleanup(self, pin=None):
        if pin is None:
            self.rpi_gpio.cleanup()
        else:
            self.rpi_gpio.cleanup(pin)

Response: Clean up GPIO event detection for specific pin or all pins.


Instruction:
How would you implement a function in Python 3 that
adds a callback for an event that is detected by add_event_detect.

Response:
def add_event_callback(self, pin, callback, bouncetime=-1):
        """Add a callback for an event already defined using add_event_detect().
        Pin should be type IN.  Bouncetime is switch bounce timeout in ms for
        callback
        """
        kwargs = {}
        if bouncetime > 0:
            kwargs['bouncetime']=bouncetime
        self.bbio_gpio.add_event_callback(pin, callback, **kwargs)


Instruction:
Explain what the following Python 3 code does
def wait_for_edge(self, pin, edge):
        self.bbio_gpio.wait_for_edge(pin, self._edge_mapping[edge])

Response: Wait for an edge.   Pin should be type IN


Instruction:
Can you write a function in Python 3 where it
cleans up GPIO event detection for specific pin or all pins.

Response:
def cleanup(self, pin=None):
        """Clean up GPIO event detection for specific pin, or all pins if none
        is specified.
        """
        if pin is None:
            self.bbio_gpio.cleanup()
        else:
            self.bbio_gpio.cleanup(pin)


Instruction:
Write a Python 3 function that can
set the input or output mode for a specified pin.

Response:
def setup(self,pin,mode):
        """Set the input or output mode for a specified pin.  Mode should be
        either DIR_IN or DIR_OUT.
        """
        self.mraa_gpio.Gpio.dir(self.mraa_gpio.Gpio(pin),self._dir_mapping[mode])


Instruction:
Explain what the following Python 3 code does
def output(self,pin,value):
        self.mraa_gpio.Gpio.write(self.mraa_gpio.Gpio(pin), value)

Response: Set the specified pin high or low value.


Instruction:
Make a summary of the following Python 3 code
def input(self,pin):
        return self.mraa_gpio.Gpio.read(self.mraa_gpio.Gpio(pin))

Response: Read the specified pin and return HIGH or LOW if the pin is pulled high and LOW if the pin is pulled low.


Instruction:
Can you generate the documentation for the following Python 3 function
def add_event_detect(self, pin, edge, callback=None, bouncetime=-1):
        kwargs = {}
        if callback:
            kwargs['callback']=callback
        if bouncetime > 0:
            kwargs['bouncetime']=bouncetime
        self.mraa_gpio.Gpio.isr(self.mraa_gpio.Gpio(pin), self._edge_mapping[edge], **kwargs)

Response: Add an event detection event for a particular GPIO channel.


Instruction:
Can you generate the documentation for the following Python 3 function
def remove_event_detect(self, pin):
        self.mraa_gpio.Gpio.isrExit(self.mraa_gpio.Gpio(pin))

Response: Remove edge detection for a particular GPIO channel.


Instruction:
Make a summary of the following Python 3 code
def wait_for_edge(self, pin, edge):
        self.bbio_gpio.wait_for_edge(self.mraa_gpio.Gpio(pin), self._edge_mapping[edge])

Response: Wait for an edge.   Pin should be type IN


Instruction:
Here you have a function in Python 3, explain what it does
def all_info_files(self) :
        'Returns a generator of "Path"s'
        try :
            for info_file in list_files_in_dir(self.info_dir):
                if not os.path.basename(info_file).endswith('.trashinfo') :
                    self.on_non_trashinfo_found()
                else :
                    yield info_file
        except OSError: # when directory does not exist
            pass

Response: Returns a generator of Path s


Instruction:
Can you generate a brief explanation for the following Python 3 code
def describe(path):
    if os.path.islink(path):
        return 'symbolic link'
    elif os.path.isdir(path):
        if path == '.':
            return 'directory'
        elif path == '..':
            return 'directory'
        else:
            if os.path.basename(path) == '.':
                return "'.' directory"
            elif os.path.basename(path) == '..':
                return "'..' directory"
            else:
                return 'directory'
    elif os.path.isfile(path):
        if os.path.getsize(path) == 0:
            return 'regular empty file'
        else:
            return 'regular file'
    elif not os.path.exists(path):
        return 'non existent'
    else:
        return 'entry'

Response: Return a textual description of the file pointed by this path.


Instruction:
Write a Python 3 script to
trash a file in the appropriate trash directory.

Response:
def trash(self, file) :
        """
        Trash a file in the appropriate trash directory.
        If the file belong to the same volume of the trash home directory it
        will be trashed in the home trash directory.
        Otherwise it will be trashed in one of the relevant volume trash
        directories.

        Each volume can have two trash directories, they are
            - $volume/.Trash/$uid
            - $volume/.Trash-$uid

        Firstly the software attempt to trash the file in the first directory
        then try to trash in the second trash directory.
        """

        if self._should_skipped_by_specs(file):
            self.reporter.unable_to_trash_dot_entries(file)
            return

        volume_of_file_to_be_trashed = self.volume_of_parent(file)
        self.reporter.volume_of_file(volume_of_file_to_be_trashed)
        candidates = self._possible_trash_directories_for(
                        volume_of_file_to_be_trashed)

        self.try_trash_file_using_candidates(file,
                                             volume_of_file_to_be_trashed,
                                             candidates)


Instruction:
Write a Python 3 script to
persist the content of a TrashInfoFile to the trashinfo directory.

Response:
def persist_trash_info(self, basename, content, logger):
        """
        Create a .trashinfo file in the $trash/info directory.
        returns the created TrashInfoFile.
        """

        self.ensure_dir(self.info_dir, 0o700)

        # write trash info
        index = 0
        while True :
            if index == 0 :
                suffix = ""
            elif index < 100:
                suffix = "_%d" % index
            else :
                import random
                suffix = "_%d" % random.randint(0, 65535)

            base_id = basename
            trash_id = base_id + suffix
            trash_info_basename = trash_id+".trashinfo"

            dest = os.path.join(self.info_dir, trash_info_basename)
            try :
                self.atomic_write(dest, content)
                logger.debug(".trashinfo created as %s." % dest)
                return dest
            except OSError:
                logger.debug("Attempt for creating %s failed." % dest)

            index += 1

        raise IOError()


Instruction:
Can you generate the documentation for the following Python 3 function
def get_process_parser(self, process_id_or_name):
        if process_id_or_name in self.process_parsers_by_name:
            return self.process_parsers_by_name[process_id_or_name]
        else:
            return self.process_parsers[process_id_or_name]

Response: Returns the ProcessParser for the given process ID or name.


Instruction:
Here you have a function in Python 3, explain what it does
def add_bpmn_files(self, filenames):
        for filename in filenames:
            f = open(filename, 'r')
            try:
                self.add_bpmn_xml(ET.parse(f), filename=filename)
            finally:
                f.close()

Response: Add all files in the given list to the parser s set.


Instruction:
Write a Python 3 function for
adding the given lxml representation of the BPMN file to the parser s set.

Response:
def add_bpmn_xml(self, bpmn, svg=None, filename=None):
        """
        Add the given lxml representation of the BPMN file to the parser's set.

        :param svg: Optionally, provide the text data for the SVG of the BPMN
          file
        :param filename: Optionally, provide the source filename.
        """
        xpath = xpath_eval(bpmn)

        processes = xpath('.//bpmn:process')
        for process in processes:
            process_parser = self.PROCESS_PARSER_CLASS(
                self, process, svg, filename=filename, doc_xpath=xpath)
            if process_parser.get_id() in self.process_parsers:
                raise ValidationException(
                    'Duplicate process ID', node=process, filename=filename)
            if process_parser.get_name() in self.process_parsers_by_name:
                raise ValidationException(
                    'Duplicate process name', node=process, filename=filename)
            self.process_parsers[process_parser.get_id()] = process_parser
            self.process_parsers_by_name[
                process_parser.get_name()] = process_parser


Instruction:
Write a Python 3 function that can
return the first node in the given list.

Response:
def one(nodes, or_none=False):
    """
    Assert that there is exactly one node in the give list, and return it.
    """
    if not nodes and or_none:
        return None
    assert len(
        nodes) == 1, 'Expected 1 result. Received %d results.' % (len(nodes))
    return nodes[0]


Instruction:
Can you implement a function in Python 3 that
returns an XPathEvaluator that evaluates the given XPath node.

Response:
def xpath_eval(node, extra_ns=None):
    """
    Returns an XPathEvaluator, with namespace prefixes 'bpmn' for
    http://www.omg.org/spec/BPMN/20100524/MODEL, and additional specified ones
    """
    namespaces = {'bpmn': BPMN_MODEL_NS}
    if extra_ns:
        namespaces.update(extra_ns)
    return lambda path: node.findall(path, namespaces)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def serialize_attrib(self, op):
        elem = etree.Element('attribute')
        elem.text = op.name
        return elem

Response: Serializer for SpiffWorkflow. operators. Attr op


Instruction:
Create a Python 3 function to
serialize for SpiffWorkflow. operators. PathAttrib op.

Response:
def serialize_pathattrib(self, op):
        """
        Serializer for :meth:`SpiffWorkflow.operators.PathAttrib`.

        Example::

            <path>foobar</path>
        """
        elem = etree.Element('path')
        elem.text = op.path
        return elem


Instruction:
Can you tell what is the following Python 3 function doing
def serialize_assign(self, op):
        elem = etree.Element('assign')
        self.serialize_value(SubElement(elem, 'name'), op.left_attribute)
        if op.right:
            self.serialize_value(SubElement(elem, 'value'), op.right)
        if op.right_attribute:
            self.serialize_value(
                SubElement(elem, 'value-attribute'), op.right_attribute)
        return elem

Response: Serializes an Assign operator into an Element.


Instruction:
Can you tell what is the following Python 3 function doing
def serialize_value(self, parent_elem, value):
        if isinstance(value, (str, int)) or type(value).__name__ == 'str':
            parent_elem.text = str(value)
        elif value is None:
            parent_elem.text = None
        else:
            parent_elem.append(value.serialize(self))

Response: Serializes the value into the XML element.


Instruction:
Can you create a Python 3 function that
serializes a dictionary of key value pairs into a dictionary of key - value pairs.

Response:
def serialize_value_map(self, map_elem, thedict):
        """
        Serializes a dictionary of key/value pairs, where the values are
        either strings, or Attrib, or PathAttrib objects.

        Example::

            <variable>
                <name>foo</name>
                <value>text</value>
            </variable>
            <variable>
                <name>foo2</name>
                <value><attribute>foobar</attribute></value>
            </variable>
        """
        for key, value in sorted((str(k), v) for (k, v) in thedict.items()):
            var_elem = SubElement(map_elem, 'variable')
            SubElement(var_elem, 'name').text = str(key)
            value_elem = SubElement(var_elem, 'value')
            self.serialize_value(value_elem, value)
        return map_elem


Instruction:
Create a Python 3 function to
serialize a list of values into a list element.

Response:
def serialize_value_list(self, list_elem, thelist):
        """
        Serializes a list, where the values are objects of type
        str, Attrib, or PathAttrib.

        Example::

            <value>text</value>
            <value><attribute>foobar</attribute></value>
            <value><path>foobar</path></value>
        """
        for value in thelist:
            value_elem = SubElement(list_elem, 'value')
            self.serialize_value(value_elem, value)
        return list_elem


Instruction:
Can you implement a function in Python 3 that
serializes for SpiffWorkflow. operators. Equal.

Response:
def serialize_operator_equal(self, op):
        """
        Serializer for :meth:`SpiffWorkflow.operators.Equal`.

        Example::

            <equals>
                <value>text</value>
                <value><attribute>foobar</attribute></value>
                <value><path>foobar</path></value>
            </equals>
        """
        elem = etree.Element('equals')
        return self.serialize_value_list(elem, op.args)


Instruction:
Implement a function in Python 3 to
serialize the NotEqual operator into XML.

Response:
def serialize_operator_not_equal(self, op):
        """
        Serializer for :meth:`SpiffWorkflow.operators.NotEqual`.

        Example::

            <not-equals>
                <value>text</value>
                <value><attribute>foobar</attribute></value>
                <value><path>foobar</path></value>
            </not-equals>
        """
        elem = etree.Element('not-equals')
        return self.serialize_value_list(elem, op.args)


Instruction:
How would you explain what the following Python 3 function does
def serialize_operator_greater_than(self, op):
        elem = etree.Element('greater-than')
        return self.serialize_value_list(elem, op.args)

Response: Serializes the NotEqual operator into XML.


Instruction:
Explain what the following Python 3 code does
def serialize_operator_less_than(self, op):
        elem = etree.Element('less-than')
        return self.serialize_value_list(elem, op.args)

Response: Serializes the less - than operator into XML.


Instruction:
How would you explain what the following Python 3 function does
def serialize_operator_match(self, op):
        elem = etree.Element('matches')
        return self.serialize_value_list(elem, op.args)

Response: Serializer for SpiffWorkflow. operators. NotEqual.


Instruction:
Can you generate the documentation for the following Python 3 function
def serialize_task_spec(self, spec, elem):
        if spec.id is not None:
            SubElement(elem, 'id').text = str(spec.id)
        SubElement(elem, 'name').text = spec.name
        if spec.description:
            SubElement(elem, 'description').text = spec.description
        if spec.manual:
            SubElement(elem, 'manual')
        if spec.internal:
            SubElement(elem, 'internal')
        SubElement(elem, 'lookahead').text = str(spec.lookahead)
        inputs = [t.name for t in spec.inputs]
        outputs = [t.name for t in spec.outputs]
        self.serialize_value_list(SubElement(elem, 'inputs'), inputs)
        self.serialize_value_list(SubElement(elem, 'outputs'), outputs)
        self.serialize_value_map(SubElement(elem, 'data'), spec.data)
        self.serialize_value_map(SubElement(elem, 'defines'), spec.defines)
        self.serialize_value_list(SubElement(elem, 'pre-assign'),
                                  spec.pre_assign)
        self.serialize_value_list(SubElement(elem, 'post-assign'),
                                  spec.post_assign)

        # Note: Events are not serialized; this is documented in
        # the TaskSpec API docs.

        return elem

Response: Serializes a TaskSpec into an xml. etree. Element object.


Instruction:
How would you implement a function in Python 3 that
serializes a AcquireMutex task spec into an XML element.

Response:
def serialize_acquire_mutex(self, spec):
        """
        Serializer for :meth:`SpiffWorkflow.specs.AcquireMutex`.
        """
        elem = etree.Element('acquire-mutex')
        self.serialize_task_spec(spec, elem)
        SubElement(elem, 'mutex').text = spec.mutex
        return elem


Instruction:
Can you tell what is the following Python 3 function doing
def get_event_definition(self):
        messageEventDefinition = first(
            self.xpath('.//bpmn:messageEventDefinition'))
        if messageEventDefinition is not None:
            return self.get_message_event_definition(messageEventDefinition)

        timerEventDefinition = first(
            self.xpath('.//bpmn:timerEventDefinition'))
        if timerEventDefinition is not None:
            return self.get_timer_event_definition(timerEventDefinition)

        raise NotImplementedError(
            'Unsupported Intermediate Catch Event: %r', ET.tostring(self.node))

Response: Parse the event definition node and return an instance of Event


Instruction:
Can you generate the documentation for the following Python 3 function
def get_message_event_definition(self, messageEventDefinition):
        messageRef = first(self.xpath('.//bpmn:messageRef'))
        message = messageRef.get(
            'name') if messageRef is not None else self.node.get('name')
        return MessageEventDefinition(message)

Response: Parse the messageEventDefinition node and return an instance of MessageEventDefinition


Instruction:
Explain what the following Python 3 code does
def get_timer_event_definition(self, timerEventDefinition):
        timeDate = first(self.xpath('.//bpmn:timeDate'))
        return TimerEventDefinition(
            self.node.get('name', timeDate.text),
            self.parser.parse_condition(
                timeDate.text, None, None, None, None, self))

Response: Parse the timerEventDefinition node and return an instance of TimerEventDefinition


Instruction:
Can you implement a function in Python 3 that
returns a set of the distinct lane names used in the process including the activities that are called in the process.

Response:
def get_all_lanes(self):
        """
        Returns a set of the distinct lane names used in the process (including
        called activities)
        """

        done = set()
        lanes = set()

        def recursive_find(task_spec):
            if task_spec in done:
                return

            done.add(task_spec)

            if hasattr(task_spec, 'lane') and task_spec.lane:
                lanes.add(task_spec.lane)

            if hasattr(task_spec, 'spec'):
                recursive_find(task_spec.spec.start)

            for t in task_spec.outputs:
                recursive_find(t)

        recursive_find(self.start)

        return lanes


Instruction:
How would you explain what the following Python 3 function does
def get_specs_depth_first(self):

        done = set()
        specs = [self]

        def recursive_find(task_spec):
            if task_spec in done:
                return

            done.add(task_spec)

            if hasattr(task_spec, 'spec'):
                specs.append(task_spec.spec)
                recursive_find(task_spec.spec.start)

            for t in task_spec.outputs:
                recursive_find(t)

        recursive_find(self.start)

        return specs

Response: Get the specs for all processes in depth first order.


Instruction:
Write a Python 3 script for
returning an etree HTML node with a document describing the process. This method returns an etree HTML node with a document describing the process.

Response:
def to_html_string(self):
        """
        Returns an etree HTML node with a document describing the process. This
        is only supported if the editor provided an SVG representation.
        """
        html = ET.Element('html')
        head = ET.SubElement(html, 'head')
        title = ET.SubElement(head, 'title')
        title.text = self.description
        body = ET.SubElement(html, 'body')
        h1 = ET.SubElement(body, 'h1')
        h1.text = self.description
        span = ET.SubElement(body, 'span')
        span.text = '___CONTENT___'

        html_text = ET.tostring(html)

        svg_content = ''
        svg_done = set()
        for spec in self.get_specs_depth_first():
            if spec.svg and spec.svg not in svg_done:
                svg_content += '<p>' + spec.svg + "</p>"
                svg_done.add(spec.svg)
        return html_text.replace('___CONTENT___', svg_content)


Instruction:
Can you implement a function in Python 3 that
connects the given callback to the given event with the given args and kwargs.

Response:
def connect(self, callback, *args, **kwargs):
        """
        Connects the event with the given callback.
        When the signal is emitted, the callback is invoked.

        .. note::

            The signal handler is stored with a hard reference, so you
            need to make sure to call :class:`disconnect()` if you want the
            handler
            to be garbage collected.

        :type  callback: object
        :param callback: The callback function.
        :type  args: tuple
        :param args: Optional arguments passed to the callback.
        :type  kwargs: dict
        :param kwargs: Optional keyword arguments passed to the callback.
        """
        if self.is_connected(callback):
            raise AttributeError('callback is already connected')
        if self.hard_subscribers is None:
            self.hard_subscribers = []
        self.hard_subscribers.append((callback, args, kwargs))


Instruction:
Can you tell what is the following Python 3 function doing
def listen(self, callback, *args, **kwargs):
        if self.lock is None:
            self.lock = Lock()
        with self.lock:
            if self.is_connected(callback):
                raise AttributeError('callback is already connected')
            if self.weak_subscribers is None:
                self.weak_subscribers = []
            ref = weakmethod.ref(callback, self._try_disconnect)
            self.weak_subscribers.append((ref, args, kwargs))
        return ref

Response: Listen to a specific event.


Instruction:
How would you explain what the following Python 3 function does
def n_subscribers(self):
        hard = self.hard_subscribers and len(self.hard_subscribers) or 0
        weak = self.weak_subscribers and len(self.weak_subscribers) or 0
        return hard + weak

Response: Returns the number of connected subscribers.


Instruction:
Make a summary of the following Python 3 code
def is_connected(self, callback):
        index = self._weakly_connected_index(callback)
        if index is not None:
            return True
        if self.hard_subscribers is None:
            return False
        return callback in self._hard_callbacks()

Response: Returns True if the event is connected to the given function.


Instruction:
Write a Python 3 function for
trying to disconnect a weak reference.

Response:
def _try_disconnect(self, ref):
        """
        Called by the weak reference when its target dies.
        In other words, we can assert that self.weak_subscribers is not
        None at this time.
        """
        with self.lock:
            weak = [s[0] for s in self.weak_subscribers]
            try:
                index = weak.index(ref)
            except ValueError:
                # subscriber was already removed by a call to disconnect()
                pass
            else:
                self.weak_subscribers.pop(index)


Instruction:
Can you generate the documentation for the following Python 3 function
def disconnect(self, callback):
        if self.weak_subscribers is not None:
            with self.lock:
                index = self._weakly_connected_index(callback)
                if index is not None:
                    self.weak_subscribers.pop(index)[0]
        if self.hard_subscribers is not None:
            try:
                index = self._hard_callbacks().index(callback)
            except ValueError:
                pass
            else:
                self.hard_subscribers.pop(index)

Response: Disconnects the signal from the given function.


Instruction:
Create a Python 3 function for
parsing this node and returns the connected task spec.

Response:
def parse_node(self):
        """
        Parse this node, and all children, returning the connected task spec.
        """

        try:
            self.task = self.create_task()

            self.task.documentation = self.parser._parse_documentation(
                self.node, xpath=self.xpath, task_parser=self)

            boundary_event_nodes = self.process_xpath(
                './/bpmn:boundaryEvent[@attachedToRef="%s"]' % self.get_id())
            if boundary_event_nodes:
                parent_task = _BoundaryEventParent(
                    self.spec, '%s.BoundaryEventParent' % self.get_id(),
                    self.task, lane=self.task.lane)
                self.process_parser.parsed_nodes[
                    self.node.get('id')] = parent_task

                parent_task.connect_outgoing(
                    self.task, '%s.FromBoundaryEventParent' % self.get_id(),
                    None, None)
                for boundary_event in boundary_event_nodes:
                    b = self.process_parser.parse_node(boundary_event)
                    parent_task.connect_outgoing(
                        b,
                        '%s.FromBoundaryEventParent' % boundary_event.get(
                            'id'),
                        None, None)
            else:
                self.process_parser.parsed_nodes[
                    self.node.get('id')] = self.task

            children = []
            outgoing = self.process_xpath(
                './/bpmn:sequenceFlow[@sourceRef="%s"]' % self.get_id())
            if len(outgoing) > 1 and not self.handles_multiple_outgoing():
                raise ValidationException(
                    'Multiple outgoing flows are not supported for '
                    'tasks of type',
                    node=self.node,
                    filename=self.process_parser.filename)
            for sequence_flow in outgoing:
                target_ref = sequence_flow.get('targetRef')
                target_node = one(
                    self.process_xpath('.//*[@id="%s"]' % target_ref))
                c = self.process_parser.parse_node(target_node)
                children.append((c, target_node, sequence_flow))

            if children:
                default_outgoing = self.node.get('default')
                if not default_outgoing:
                    (c, target_node, sequence_flow) = children[0]
                    default_outgoing = sequence_flow.get('id')

                for (c, target_node, sequence_flow) in children:
                    self.connect_outgoing(
                        c, target_node, sequence_flow,
                        sequence_flow.get('id') == default_outgoing)

            return parent_task if boundary_event_nodes else self.task
        except ValidationException:
            raise
        except Exception as ex:
            exc_info = sys.exc_info()
            tb = "".join(traceback.format_exception(
                exc_info[0], exc_info[1], exc_info[2]))
            LOG.error("%r\n%s", ex, tb)
            raise ValidationException(
                "%r" % (ex), node=self.node,
                filename=self.process_parser.filename)


Instruction:
Create a Python 3 function for
creating an instance of the task appropriately.

Response:
def create_task(self):
        """
        Create an instance of the task appropriately. A subclass can override
        this method to get extra information from the node.
        """
        return self.spec_class(self.spec, self.get_task_spec_name(),
                               lane=self.get_lane(),
                               description=self.node.get('name', None))