Instruction:
Can you tell what is the following Python 3 function doing
def calculate_order_parameter(self, start_iteration = None, stop_iteration = None):

        (start_iteration, stop_iteration) = self.__get_start_stop_iterations(start_iteration, stop_iteration);

        if (self._ccore_sync_dynamic_pointer is not None):
            return wrapper.sync_dynamic_calculate_order(self._ccore_sync_dynamic_pointer, start_iteration, stop_iteration);

        sequence_order = [];
        for index in range(start_iteration, stop_iteration):
            sequence_order.append(order_estimator.calculate_sync_order(self.output[index]));

        return sequence_order;

Response: Calculates the level of global synchronization in the current time series.


Instruction:
Can you create a Python 3 function that
calculates the local order parameter of the given oscillatory network.

Response:
def calculate_local_order_parameter(self, oscillatory_network, start_iteration = None, stop_iteration = None):
        """!
        @brief Calculates local order parameter.
        @details Local order parameter or so-called level of local or partial synchronization is calculated by following expression:

        \f[
        r_{c}=\left | \sum_{i=0}^{N} \frac{1}{N_{i}} \sum_{j=0}e^{ \theta_{j} - \theta_{i} } \right |;
        \f]

        where N - total amount of oscillators in the network and \f$N_{i}\f$ - amount of neighbors of oscillator with index \f$i\f$.

        @param[in] oscillatory_network (sync): Sync oscillatory network whose structure of connections is required for calculation.
        @param[in] start_iteration (uint): The first iteration that is used for calculation, if 'None' then the last iteration is used.
        @param[in] stop_iteration (uint): The last iteration that is used for calculation, if 'None' then 'start_iteration' + 1 is used.

        @return (list) List of levels of local (partial) synchronization (local order parameter evolution).

        """

        (start_iteration, stop_iteration) = self.__get_start_stop_iterations(start_iteration, stop_iteration);

        if (self._ccore_sync_dynamic_pointer is not None):
            network_pointer = oscillatory_network._ccore_network_pointer;
            return wrapper.sync_dynamic_calculate_local_order(self._ccore_sync_dynamic_pointer, network_pointer, start_iteration, stop_iteration);

        sequence_local_order = [];
        for index in range(start_iteration, stop_iteration):
            sequence_local_order.append(order_estimator.calculate_local_sync_order(self.output[index], oscillatory_network));

        return sequence_local_order;


Instruction:
Create a Python 3 function for
returning the start and stop iteration values.

Response:
def __get_start_stop_iterations(self, start_iteration, stop_iteration):
        """!
        @brief Aplly rules for start_iteration and stop_iteration parameters.

        @param[in] start_iteration (uint): The first iteration that is used for calculation.
        @param[in] stop_iteration (uint): The last iteration that is used for calculation.

        @return (tuple) New the first iteration and the last.

        """
        if (start_iteration is None):
            start_iteration = len(self) - 1;

        if (stop_iteration is None):
            stop_iteration = start_iteration + 1;

        return (start_iteration, stop_iteration);


Instruction:
How would you implement a function in Python 3 that
shows dynamic output of each oscillator during simulation.

Response:
def show_output_dynamic(sync_output_dynamic):
        """!
        @brief Shows output dynamic (output of each oscillator) during simulation.

        @param[in] sync_output_dynamic (sync_dynamic): Output dynamic of the Sync network.

        @see show_output_dynamics

        """

        draw_dynamics(sync_output_dynamic.time, sync_output_dynamic.output, x_title = "t", y_title = "phase", y_lim = [0, 2 * 3.14]);


Instruction:
Can you create a Python 3 function that
shows the correlation matrix between oscillators at the specified iteration.

Response:
def show_correlation_matrix(sync_output_dynamic, iteration = None):
        """!
        @brief Shows correlation matrix between oscillators at the specified iteration.

        @param[in] sync_output_dynamic (sync_dynamic): Output dynamic of the Sync network.
        @param[in] iteration (uint): Number of interation of simulation for which correlation matrix should be allocated.
                                      If iternation number is not specified, the last step of simulation is used for the matrix allocation.

        """

        _ = plt.figure();
        correlation_matrix = sync_output_dynamic.allocate_correlation_matrix(iteration);

        plt.imshow(correlation_matrix, cmap = plt.get_cmap('cool'), interpolation='kaiser', vmin = 0.0, vmax = 1.0);
        plt.show();


Instruction:
Can you tell what is the following Python 3 function doing
def show_phase_matrix(sync_output_dynamic, grid_width = None, grid_height = None, iteration = None):

        _ = plt.figure();
        phase_matrix = sync_output_dynamic.allocate_phase_matrix(grid_width, grid_height, iteration);

        plt.imshow(phase_matrix, cmap = plt.get_cmap('jet'), interpolation='kaiser', vmin = 0.0, vmax = 2.0 * math.pi);
        plt.show();

Response: Shows the 2D matrix of phase values of oscillators at the specified iteration.


Instruction:
Given the following Python 3 function, write the documentation
def show_order_parameter(sync_output_dynamic, start_iteration = None, stop_iteration = None):

        (start_iteration, stop_iteration) = sync_visualizer.__get_start_stop_iterations(sync_output_dynamic, start_iteration, stop_iteration);

        order_parameter = sync_output_dynamic.calculate_order_parameter(start_iteration, stop_iteration);
        axis = plt.subplot(111);
        plt.plot(sync_output_dynamic.time[start_iteration:stop_iteration], order_parameter, 'b-', linewidth = 2.0);
        set_ax_param(axis, "t", "R (order parameter)", None, [0.0, 1.05]);

        plt.show();

Response: Displays evolution of order parameter of global synchronization in the network.


Instruction:
Implement a Python 3 function for
showing evolution of local order parameter in the network.

Response:
def show_local_order_parameter(sync_output_dynamic, oscillatory_network, start_iteration = None, stop_iteration = None):
        """!
        @brief Shows evolution of local order parameter (level of local synchronization in the network).

        @param[in] sync_output_dynamic (sync_dynamic): Output dynamic of the Sync network whose evolution of global synchronization should be visualized.
        @param[in] oscillatory_network (sync): Sync oscillatory network whose structure of connections is required for calculation.
        @param[in] start_iteration (uint): The first iteration that is used for calculation, if 'None' then the first is used
        @param[in] stop_iteration (uint): The last iteration that is used for calculation, if 'None' then the last is used.

        """
        (start_iteration, stop_iteration) = sync_visualizer.__get_start_stop_iterations(sync_output_dynamic, start_iteration, stop_iteration);

        order_parameter = sync_output_dynamic.calculate_local_order_parameter(oscillatory_network, start_iteration, stop_iteration);
        axis = plt.subplot(111);
        plt.plot(sync_output_dynamic.time[start_iteration:stop_iteration], order_parameter, 'b-', linewidth = 2.0);
        set_ax_param(axis, "t", "R (local order parameter)", None, [0.0, 1.05]);

        plt.show();


Instruction:
Can you tell what is the following Python 3 function doing
def animate_output_dynamic(sync_output_dynamic, animation_velocity = 75, save_movie = None):

        figure = plt.figure();

        dynamic = sync_output_dynamic.output[0];
        artist, = plt.polar(dynamic, [1.0] * len(dynamic), 'o', color = 'blue');

        def init_frame():
            return [ artist ];

        def frame_generation(index_dynamic):
            dynamic = sync_output_dynamic.output[index_dynamic];
            artist.set_data(dynamic, [1.0] * len(dynamic));

            return [ artist ];

        phase_animation = animation.FuncAnimation(figure, frame_generation, len(sync_output_dynamic), interval = animation_velocity, init_func = init_frame, repeat_delay = 5000);

        if (save_movie is not None):
            phase_animation.save(save_movie, writer = 'ffmpeg', fps = 15, bitrate = 1500);
        else:
            plt.show();

Response: Animate the output of each oscillator in a Sync network.


Instruction:
Given the following Python 3 function, write the documentation
def animate_correlation_matrix(sync_output_dynamic, animation_velocity = 75, colormap = 'cool', save_movie = None):

        figure = plt.figure()

        correlation_matrix = sync_output_dynamic.allocate_correlation_matrix(0)
        artist = plt.imshow(correlation_matrix, cmap = plt.get_cmap(colormap), interpolation='kaiser', vmin = 0.0, vmax = 1.0)

        def init_frame():
            return [ artist ]

        def frame_generation(index_dynamic):
            correlation_matrix = sync_output_dynamic.allocate_correlation_matrix(index_dynamic)
            artist.set_data(correlation_matrix)

            return [ artist ]

        correlation_animation = animation.FuncAnimation(figure, frame_generation, len(sync_output_dynamic), init_func = init_frame, interval = animation_velocity , repeat_delay = 1000, blit = True)

        if (save_movie is not None):
            correlation_animation.save(save_movie, writer = 'ffmpeg', fps = 15, bitrate = 1500)
        else:
            plt.show()

Response: Animate the correlation matrix between oscillators during simulation.


Instruction:
How would you implement a function in Python 3 that
animates the phase matrix between oscillators during simulation on 2D stage.

Response:
def animate_phase_matrix(sync_output_dynamic, grid_width = None, grid_height = None, animation_velocity = 75, colormap = 'jet', save_movie = None):
        """!
        @brief Shows animation of phase matrix between oscillators during simulation on 2D stage.
        @details If grid_width or grid_height are not specified than phase matrix size will by calculated automatically by square root.

        @param[in] sync_output_dynamic (sync_dynamic): Output dynamic of the Sync network.
        @param[in] grid_width (uint): Width of the phase matrix.
        @param[in] grid_height (uint): Height of the phase matrix.
        @param[in] animation_velocity (uint): Interval between frames in milliseconds.
        @param[in] colormap (string): Name of colormap that is used by matplotlib ('gray', 'pink', 'cool', spring', etc.).
        @param[in] save_movie (string): If it is specified then animation will be stored to file that is specified in this parameter.

        """

        figure = plt.figure();

        def init_frame():
            return frame_generation(0);

        def frame_generation(index_dynamic):
            figure.clf();
            axis = figure.add_subplot(111);

            phase_matrix = sync_output_dynamic.allocate_phase_matrix(grid_width, grid_height, index_dynamic);
            axis.imshow(phase_matrix, cmap = plt.get_cmap(colormap), interpolation='kaiser', vmin = 0.0, vmax = 2.0 * math.pi);
            artist = figure.gca();

            return [ artist ];

        phase_animation = animation.FuncAnimation(figure, frame_generation, len(sync_output_dynamic), init_func = init_frame, interval = animation_velocity , repeat_delay = 1000);

        if (save_movie is not None):
            phase_animation.save(save_movie, writer = 'ffmpeg', fps = 15, bitrate = 1500);
        else:
            plt.show();


Instruction:
Implement a Python 3 function for
returning start and stop iteration values.

Response:
def __get_start_stop_iterations(sync_output_dynamic, start_iteration, stop_iteration):
        """!
        @brief Apply rule of preparation for start iteration and stop iteration values.

        @param[in] sync_output_dynamic (sync_dynamic): Output dynamic of the Sync network.
        @param[in] start_iteration (uint): The first iteration that is used for calculation.
        @param[in] stop_iteration (uint): The last iteration that is used for calculation.

        @return (tuple) New values of start and stop iterations.

        """
        if (start_iteration is None):
            start_iteration = 0;

        if (stop_iteration is None):
            stop_iteration = len(sync_output_dynamic);

        return (start_iteration, stop_iteration);


Instruction:
Can you write a function in Python 3 where it
displays the animation of phase coordinates and animation of correlation matrix together for the Sync output dynamic.

Response:
def animate(sync_output_dynamic, title = None, save_movie = None):
        """!
        @brief Shows animation of phase coordinates and animation of correlation matrix together for the Sync dynamic output on the same figure.

        @param[in] sync_output_dynamic (sync_dynamic): Output dynamic of the Sync network.
        @param[in] title (string): Title of the animation that is displayed on a figure if it is specified.
        @param[in] save_movie (string): If it is specified then animation will be stored to file that is specified in this parameter.

        """

        dynamic = sync_output_dynamic.output[0];
        correlation_matrix = sync_output_dynamic.allocate_correlation_matrix(0);

        figure = plt.figure(1);
        if (title is not None):
            figure.suptitle(title, fontsize = 26, fontweight = 'bold')

        ax1 = figure.add_subplot(121, projection='polar');
        ax2 = figure.add_subplot(122);

        artist1, = ax1.plot(dynamic, [1.0] * len(dynamic), marker = 'o', color = 'blue', ls = '');
        artist2 = ax2.imshow(correlation_matrix, cmap = plt.get_cmap('Accent'), interpolation='kaiser');

        def init_frame():
            return [ artist1, artist2 ];

        def frame_generation(index_dynamic):
            dynamic = sync_output_dynamic.output[index_dynamic];
            artist1.set_data(dynamic, [1.0] * len(dynamic));

            correlation_matrix = sync_output_dynamic.allocate_correlation_matrix(index_dynamic);
            artist2.set_data(correlation_matrix);

            return [ artist1, artist2 ];

        dynamic_animation = animation.FuncAnimation(figure, frame_generation, len(sync_output_dynamic), interval = 75, init_func = init_frame, repeat_delay = 5000);

        if (save_movie is not None):
            dynamic_animation.save(save_movie, writer = 'ffmpeg', fps = 15, bitrate = 1500);
        else:
            plt.show();


Instruction:
Write a Python 3 script for
calculating the current level of global synchronization in the network.

Response:
def sync_order(self):
        """!
        @brief Calculates current level of global synchorization (order parameter) in the network.
        @details This parameter is tend 1.0 when the oscillatory network close to global synchronization and it tend to 0.0 when
                  desynchronization is observed in the network. Order parameter is calculated using following equation:

                  \f[
                  r_{c}=\frac{1}{Ne^{i\varphi }}\sum_{j=0}^{N}e^{i\theta_{j}};
                  \f]

                  where \f$\varphi\f$ is a average phase coordinate in the network, \f$N\f$ is an amount of oscillators in the network.

        Example:
        @code
            oscillatory_network = sync(16, type_conn = conn_type.ALL_TO_ALL);
            output_dynamic = oscillatory_network.simulate_static(100, 10);

            if (oscillatory_network.sync_order() < 0.9): print("Global synchronization is not reached yet.");
            else: print("Global synchronization is reached.");
        @endcode

        @return (double) Level of global synchronization (order parameter).

        @see sync_local_order()

        """

        if (self._ccore_network_pointer is not None):
            return wrapper.sync_order(self._ccore_network_pointer);

        return order_estimator.calculate_sync_order(self._phases);


Instruction:
Can you generate the documentation for the following Python 3 function
def sync_local_order(self):

        if (self._ccore_network_pointer is not None):
            return wrapper.sync_local_order(self._ccore_network_pointer);

        return order_estimator.calculate_local_sync_order(self._phases, self);

Response: Calculates the current local synchronization order of the local system.


Instruction:
Here you have a function in Python 3, explain what it does
def _phase_kuramoto(self, teta, t, argv):

        index = argv;
        phase = 0;
        for k in range(0, self._num_osc):
            if (self.has_connection(index, k) == True):
                phase += math.sin(self._phases[k] - teta);

        return ( self._freq[index] + (phase * self._weight / self._num_osc) );

Response: Returns the new phase for the specified oscillator in the network.


Instruction:
Here you have a function in Python 3, explain what it does
def simulate(self, steps, time, solution = solve_type.FAST, collect_dynamic = True):

        return self.simulate_static(steps, time, solution, collect_dynamic);

Response: Simulate a set of dynamic dynamics.


Instruction:
Here you have a function in Python 3, explain what it does
def simulate_dynamic(self, order = 0.998, solution = solve_type.FAST, collect_dynamic = False, step = 0.1, int_step = 0.01, threshold_changes = 0.0000001):

        if (self._ccore_network_pointer is not None):
            ccore_instance_dynamic = wrapper.sync_simulate_dynamic(self._ccore_network_pointer, order, solution, collect_dynamic, step, int_step, threshold_changes);
            return sync_dynamic(None, None, ccore_instance_dynamic);

        # For statistics and integration
        time_counter = 0;

        # Prevent infinite loop. It's possible when required state cannot be reached.
        previous_order = 0;
        current_order = self.sync_local_order();

        # If requested input dynamics
        dyn_phase = [];
        dyn_time = [];
        if (collect_dynamic == True):
            dyn_phase.append(self._phases);
            dyn_time.append(0);

        # Execute until sync state will be reached
        while (current_order < order):
            # update states of oscillators
            self._phases = self._calculate_phases(solution, time_counter, step, int_step);

            # update time
            time_counter += step;

            # if requested input dynamic
            if (collect_dynamic == True):
                dyn_phase.append(self._phases);
                dyn_time.append(time_counter);

            # update orders
            previous_order = current_order;
            current_order = self.sync_local_order();

            # hang prevention
            if (abs(current_order - previous_order) < threshold_changes):
                # print("Warning: sync_network::simulate_dynamic - simulation is aborted due to low level of convergence rate (order = " + str(current_order) + ").");
                break;

        if (collect_dynamic != True):
            dyn_phase.append(self._phases);
            dyn_time.append(time_counter);

        output_sync_dynamic = sync_dynamic(dyn_phase, dyn_time, None);
        return output_sync_dynamic;

Response: A method that performs dynamic simulation of the oscillatory network.


Instruction:
Can you tell what is the following Python 3 function doing
def _calculate_phases(self, solution, t, step, int_step):

        next_phases = [0.0] * self._num_osc;    # new oscillator _phases

        for index in range (0, self._num_osc, 1):
            if (solution == solve_type.FAST):
                result = self._phases[index] + self._phase_kuramoto(self._phases[index], 0, index);
                next_phases[index] = self._phase_normalization(result);

            elif ( (solution == solve_type.RK4) or (solution == solve_type.RKF45) ):
                result = odeint(self._phase_kuramoto, self._phases[index], numpy.arange(t - step, t, int_step), (index , ));
                next_phases[index] = self._phase_normalization(result[len(result) - 1][0]);

            else:
                raise NameError("Solver '" + str(solution) + "' is not supported");

        return next_phases;

Response: Calculates new phases for the given solution at the given time.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _phase_normalization(self, teta):

        norm_teta = teta;
        while (norm_teta > (2.0 * pi)) or (norm_teta < 0):
            if (norm_teta > (2.0 * pi)):
                norm_teta -= 2.0 * pi;
            else:
                norm_teta += 2.0 * pi;

        return norm_teta;

Response: This function normalizes the phase of the object.


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

        if ( (self._ccore_network_pointer is not None) and (self._osc_conn is None) ):
            self._osc_conn = wrapper.sync_connectivity_matrix(self._ccore_network_pointer);

        return super().get_neighbors(index);

Response: Returns a list of the neighbors of the specified oscillator with the specified index.


Instruction:
Can you create a Python 3 function that
returns True if there is a connection between i and j oscillators and False otherwise.

Response:
def has_connection(self, i, j):
        """!
        @brief Returns True if there is connection between i and j oscillators and False - if connection doesn't exist.

        @param[in] i (uint): index of an oscillator in the network.
        @param[in] j (uint): index of an oscillator in the network.

        """

        if ( (self._ccore_network_pointer is not None) and (self._osc_conn is None) ):
            self._osc_conn = wrapper.sync_connectivity_matrix(self._ccore_network_pointer);

        return super().has_connection(i, j);


Instruction:
Write a Python 3 script to
create a distance calculator function that returns the distance of the current object.

Response:
def __create_distance_calculator(self):
        """!
        @brief Creates distance calculator in line with algorithms parameters.

        @return (callable) Distance calculator.

        """
        if self.__data_type == 'points':
            return lambda index1, index2: self.__metric(self.__pointer_data[index1], self.__pointer_data[index2])

        elif self.__data_type == 'distance_matrix':
            if isinstance(self.__pointer_data, numpy.matrix):
                return lambda index1, index2: self.__pointer_data.item((index1, index2))

            return lambda index1, index2: self.__pointer_data[index1][index2]

        else:
            raise TypeError("Unknown type of data is specified '%s'" % self.__data_type)


Instruction:
Given the following Python 3 function, write the documentation
def __update_clusters(self):

        clusters = [[self.__medoid_indexes[i]] for i in range(len(self.__medoid_indexes))]
        for index_point in range(len(self.__pointer_data)):
            if index_point in self.__medoid_indexes:
                continue

            index_optim = -1
            dist_optim = float('Inf')

            for index in range(len(self.__medoid_indexes)):
                dist = self.__distance_calculator(index_point, self.__medoid_indexes[index])

                if dist < dist_optim:
                    index_optim = index
                    dist_optim = dist

            clusters[index_optim].append(index_point)

        return clusters

Response: Updates the clusters in the database with the distance to each point from the each cluster.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def __update_medoids(self):

        medoid_indexes = [-1] * len(self.__clusters)

        for index in range(len(self.__clusters)):
            medoid_index = medoid(self.__pointer_data, self.__clusters[index], metric=self.__metric, data_type=self.__data_type)
            medoid_indexes[index] = medoid_index

        return medoid_indexes

Response: Updates the list of medoids in the line with contained objects.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def __create_sync_layer(self, weights):
        sync_layer = syncnet(weights, 0.0, initial_phases = initial_type.RANDOM_GAUSSIAN, ccore = False);

        for oscillator_index1 in range(0, len(sync_layer)):
            for oscillator_index2 in range(oscillator_index1 + 1, len(sync_layer)):
                if (self.__has_object_connection(oscillator_index1, oscillator_index2)):
                    sync_layer.set_connection(oscillator_index1, oscillator_index2);

        return sync_layer;

Response: Creates a second layer of the network.


Instruction:
Can you tell what is the following Python 3 function doing
def __has_object_connection(self, oscillator_index1, oscillator_index2):
        som_neuron_index1 = self._som_osc_table[oscillator_index1];
        som_neuron_index2 = self._som_osc_table[oscillator_index2];

        for index_object1 in self._som.capture_objects[som_neuron_index1]:
            for index_object2 in self._som.capture_objects[som_neuron_index2]:
                distance = euclidean_distance_square(self._data[index_object1], self._data[index_object2]);
                if (distance <= self._radius):
                    return True;

        return False;

Response: Returns true if there is a pair of connected objects encoded by the first oscillator in the second layer.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_som_clusters(self):

        sync_clusters = self._analyser.allocate_clusters();

        # Decode it to indexes of SOM neurons
        som_clusters = list();
        for oscillators in sync_clusters:
            cluster = list();
            for index_oscillator in oscillators:
                index_neuron = self._som_osc_table[index_oscillator];
                cluster.append(index_neuron);

            som_clusters.append(cluster);

        return som_clusters;

Response: Returns a list of clusters with SOM neurons that encode input features in line with result of synchronization in the second Sync layer.


Instruction:
Implement a function in Python 3 to
return a list of clusters in line with ensembles of synchronous oscillators where each synchronous ensemble corresponds to only one cluster.

Response:
def get_clusters(self, eps = 0.1):
        """!
        @brief Returns clusters in line with ensembles of synchronous oscillators where each synchronous ensemble corresponds to only one cluster.

        @param[in] eps (double): Maximum error for allocation of synchronous ensemble oscillators.

        @return (list) List of grours (lists) of indexes of synchronous oscillators that corresponds to index of objects.

        @see process()
        @see get_som_clusters()

        """

        sync_clusters = self._analyser.allocate_clusters(eps)       # it isn't indexes of SOM neurons

        clusters = list()
        for oscillators in sync_clusters:
            cluster = list()
            for index_oscillator in oscillators:
                index_neuron = self._som_osc_table[index_oscillator]

                cluster += self._som.capture_objects[index_neuron]

            clusters.append(cluster)

        return clusters


Instruction:
Given the following Python 3 function, write the documentation
def __process_by_ccore(self):
        cure_data_pointer = wrapper.cure_algorithm(self.__pointer_data, self.__number_cluster,
                                                   self.__number_represent_points, self.__compression)

        self.__clusters = wrapper.cure_get_clusters(cure_data_pointer)
        self.__representors = wrapper.cure_get_representors(cure_data_pointer)
        self.__means = wrapper.cure_get_means(cure_data_pointer)

        wrapper.cure_data_destroy(cure_data_pointer)

Response: This method is called by the pyclustering library when the cluster is created.


Instruction:
Can you write a function in Python 3 where it
processes the cluster by python code.

Response:
def __process_by_python(self):
        """!
        @brief Performs cluster analysis using python code.

        """
        self.__create_queue()  # queue
        self.__create_kdtree()  # create k-d tree

        while len(self.__queue) > self.__number_cluster:
            cluster1 = self.__queue[0]  # cluster that has nearest neighbor.
            cluster2 = cluster1.closest  # closest cluster.

            self.__queue.remove(cluster1)
            self.__queue.remove(cluster2)

            self.__delete_represented_points(cluster1)
            self.__delete_represented_points(cluster2)

            merged_cluster = self.__merge_clusters(cluster1, cluster2)

            self.__insert_represented_points(merged_cluster)

            # Pointers to clusters that should be relocated is stored here.
            cluster_relocation_requests = []

            # Check for the last cluster
            if len(self.__queue) > 0:
                merged_cluster.closest = self.__queue[0]  # arbitrary cluster from queue
                merged_cluster.distance = self.__cluster_distance(merged_cluster, merged_cluster.closest)

                for item in self.__queue:
                    distance = self.__cluster_distance(merged_cluster, item)
                    # Check if distance between new cluster and current is the best than now.
                    if distance < merged_cluster.distance:
                        merged_cluster.closest = item
                        merged_cluster.distance = distance

                    # Check if current cluster has removed neighbor.
                    if (item.closest is cluster1) or (item.closest is cluster2):
                        # If previous distance was less then distance to new cluster then nearest cluster should
                        # be found in the tree.
                        if item.distance < distance:
                            (item.closest, item.distance) = self.__closest_cluster(item, distance)

                            # TODO: investigation is required. There is assumption that itself and merged cluster
                            # should be always in list of neighbors in line with specified radius. But merged cluster
                            # may not be in list due to error calculation, therefore it should be added manually.
                            if item.closest is None:
                                item.closest = merged_cluster
                                item.distance = distance

                        else:
                            item.closest = merged_cluster
                            item.distance = distance

                        cluster_relocation_requests.append(item)

            # New cluster and updated clusters should relocated in queue
            self.__insert_cluster(merged_cluster)
            for item in cluster_relocation_requests:
                self.__relocate_cluster(item)

        # Change cluster representation
        self.__clusters = [cure_cluster_unit.indexes for cure_cluster_unit in self.__queue]
        self.__representors = [cure_cluster_unit.rep for cure_cluster_unit in self.__queue]
        self.__means = [cure_cluster_unit.mean for cure_cluster_unit in self.__queue]


Instruction:
Can you create a Python 3 function that
prepares data points for clustering.

Response:
def __prepare_data_points(self, sample):
        """!
        @brief Prepare data points for clustering.
        @details In case of numpy.array there are a lot of overloaded basic operators, such as __contains__, __eq__.

        @return (list) Returns sample in list format.

        """
        if isinstance(sample, numpy.ndarray):
            return sample.tolist()

        return sample


Instruction:
Implement a Python 3 function for
validating the input arguments of the BANG algorithm.

Response:
def __validate_arguments(self):
        """!
        @brief Check input arguments of BANG algorithm and if one of them is not correct then appropriate exception
                is thrown.

        """

        if len(self.__pointer_data) == 0:
            raise ValueError("Empty input data. Data should contain at least one point.")

        if self.__number_cluster <= 0:
            raise ValueError("Incorrect amount of clusters '%d'. Amount of cluster should be greater than 0." % self.__number_cluster)

        if self.__compression < 0:
            raise ValueError("Incorrect compression level '%f'. Compression should not be negative." % self.__compression)

        if self.__number_represent_points <= 0:
            raise ValueError("Incorrect amount of representatives '%d'. Amount of representatives should be greater than 0." % self.__number_cluster)


Instruction:
Here you have a function in Python 3, explain what it does
def __insert_cluster(self, cluster):

        for index in range(len(self.__queue)):
            if cluster.distance < self.__queue[index].distance:
                self.__queue.insert(index, cluster)
                return

        self.__queue.append(cluster)

Response: Insert a cluster into the queue in line with sequence order.


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

        self.__queue.remove(cluster)
        self.__insert_cluster(cluster)

Response: Relocate a cluster in the list in line with distance order.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def __closest_cluster(self, cluster, distance):

        nearest_cluster = None
        nearest_distance = float('inf')

        real_euclidean_distance = distance ** 0.5

        for point in cluster.rep:
            # Nearest nodes should be returned (at least it will return itself).
            nearest_nodes = self.__tree.find_nearest_dist_nodes(point, real_euclidean_distance)
            for (candidate_distance, kdtree_node) in nearest_nodes:
                if (candidate_distance < nearest_distance) and (kdtree_node is not None) and (kdtree_node.payload is not cluster):
                    nearest_distance = candidate_distance
                    nearest_cluster = kdtree_node.payload

        return (nearest_cluster, nearest_distance)

Response: Find the closest cluster to the specified cluster in line with distance.


Instruction:
Can you create a Python 3 function that
inserts representation points into the k - d tree.

Response:
def __insert_represented_points(self, cluster):
        """!
        @brief Insert representation points to the k-d tree.

        @param[in] cluster (cure_cluster): Cluster whose representation points should be inserted.

        """

        for point in cluster.rep:
            self.__tree.insert(point, cluster)


Instruction:
Can you write a function in Python 3 where it
removes representation points of clusters from the k - d tree

Response:
def __delete_represented_points(self, cluster):
        """!
        @brief Remove representation points of clusters from the k-d tree

        @param[in] cluster (cure_cluster): Cluster whose representation points should be removed.

        """

        for point in cluster.rep:
            self.__tree.remove(point, payload=cluster)


Instruction:
Implement a function in Python 3 to
merge two clusters and returns a new cluster.

Response:
def __merge_clusters(self, cluster1, cluster2):
        """!
        @brief Merges two clusters and returns new merged cluster. Representation points and mean points are calculated for the new cluster.

        @param[in] cluster1 (cure_cluster): Cluster that should be merged.
        @param[in] cluster2 (cure_cluster): Cluster that should be merged.

        @return (cure_cluster) New merged CURE cluster.

        """

        merged_cluster = cure_cluster(None, None)

        merged_cluster.points = cluster1.points + cluster2.points
        merged_cluster.indexes = cluster1.indexes + cluster2.indexes

        # merged_cluster.mean = ( len(cluster1.points) * cluster1.mean + len(cluster2.points) * cluster2.mean ) / ( len(cluster1.points) + len(cluster2.points) );
        dimension = len(cluster1.mean)
        merged_cluster.mean = [0] * dimension
        if merged_cluster.points[1:] == merged_cluster.points[:-1]:
            merged_cluster.mean = merged_cluster.points[0]
        else:
            for index in range(dimension):
                merged_cluster.mean[index] = ( len(cluster1.points) * cluster1.mean[index] + len(cluster2.points) * cluster2.mean[index] ) / ( len(cluster1.points) + len(cluster2.points) );

        temporary = list()

        for index in range(self.__number_represent_points):
            maximal_distance = 0
            maximal_point = None

            for point in merged_cluster.points:
                minimal_distance = 0
                if index == 0:
                    minimal_distance = euclidean_distance_square(point, merged_cluster.mean)
                    #minimal_distance = euclidean_distance_sqrt(point, merged_cluster.mean);
                else:
                    minimal_distance = min([euclidean_distance_square(point, p) for p in temporary])
                    #minimal_distance = cluster_distance(cure_cluster(point), cure_cluster(temporary[0]));

                if minimal_distance >= maximal_distance:
                    maximal_distance = minimal_distance
                    maximal_point = point

            if maximal_point not in temporary:
                temporary.append(maximal_point)

        for point in temporary:
            representative_point = [0] * dimension
            for index in range(dimension):
                representative_point[index] = point[index] + self.__compression * (merged_cluster.mean[index] - point[index])

            merged_cluster.rep.append(representative_point)

        return merged_cluster


Instruction:
Can you generate the documentation for the following Python 3 function
def __create_queue(self):

        self.__queue = [cure_cluster(self.__pointer_data[index_point], index_point) for index_point in range(len(self.__pointer_data))]

        # set closest clusters
        for i in range(0, len(self.__queue)):
            minimal_distance = float('inf')
            closest_index_cluster = -1

            for k in range(0, len(self.__queue)):
                if i != k:
                    dist = self.__cluster_distance(self.__queue[i], self.__queue[k])
                    if dist < minimal_distance:
                        minimal_distance = dist
                        closest_index_cluster = k

            self.__queue[i].closest = self.__queue[closest_index_cluster]
            self.__queue[i].distance = minimal_distance

        # sort clusters
        self.__queue.sort(key = lambda x: x.distance, reverse = False)

Response: Create a queue of sorted clusters by distance between them.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def __create_kdtree(self):

        self.__tree = kdtree()
        for current_cluster in self.__queue:
            for representative_point in current_cluster.rep:
                self.__tree.insert(representative_point, current_cluster)

Response: Create a k - d tree in line with created clusters.


Instruction:
Can you tell what is the following Python 3 function doing
def __cluster_distance(self, cluster1, cluster2):

        distance = float('inf')
        for i in range(0, len(cluster1.rep)):
            for k in range(0, len(cluster2.rep)):
                dist = euclidean_distance_square(cluster1.rep[i], cluster2.rep[k]);   # Fast mode
                #dist = euclidean_distance(cluster1.rep[i], cluster2.rep[k])        # Slow mode
                if dist < distance:
                    distance = dist

        return distance

Response: Calculates the minimal distance between two clusters using representative points.


Instruction:
How would you explain what the following Python 3 function does
def allocate_observation_matrix(self):
        number_neurons = len(self.output[0])
        observation_matrix = []

        for iteration in range(len(self.output)):
            obervation_column = []
            for index_neuron in range(number_neurons):
                obervation_column.append(heaviside(self.output[iteration][index_neuron]))

            observation_matrix.append(obervation_column)

        return observation_matrix

Response: Allocates the observation matrix in line with output dynamic of the network.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def __allocate_neuron_patterns(self, start_iteration, stop_iteration):

        pattern_matrix = []
        for index_neuron in range(len(self.output[0])):
            pattern_neuron = []
            for iteration in range(start_iteration, stop_iteration):
                pattern_neuron.append(heaviside(self.output[iteration][index_neuron]))

            pattern_matrix.append(pattern_neuron)

        return pattern_matrix

Response: Allocates observation transposed matrix of neurons that are limited by zero or one in line with Heaviside function on each iteration.


Instruction:
Given the following Python 3 function, write the documentation
def allocate_sync_ensembles(self, steps):

        iterations = steps
        if iterations >= len(self.output):
            iterations = len(self.output)

        ensembles = []

        start_iteration = len(self.output) - iterations
        end_iteration = len(self.output)

        pattern_matrix = self.__allocate_neuron_patterns(start_iteration, end_iteration)

        ensembles.append( [0] )

        for index_neuron in range(1, len(self.output[0])):
            neuron_pattern = pattern_matrix[index_neuron][:]

            neuron_assigned = False

            for ensemble in ensembles:
                ensemble_pattern = pattern_matrix[ensemble[0]][:]

                if neuron_pattern == ensemble_pattern:
                    ensemble.append(index_neuron)
                    neuron_assigned = True
                    break

            if neuron_assigned is False:
                ensembles.append( [index_neuron] )

        return ensembles

Response: Allocate clusters in line with ensembles of synchronous oscillators where each synchronous ensemble corresponds to only one cluster.


Instruction:
Can you implement a function in Python 3 that
shows the dynamic matrix of the chaotic neural network.

Response:
def show_dynamic_matrix(cnn_output_dynamic):
        """!
        @brief Shows output dynamic as matrix in grey colors.
        @details This type of visualization is convenient for observing allocated clusters.

        @param[in] cnn_output_dynamic (cnn_dynamic): Output dynamic of the chaotic neural network.

        @see show_output_dynamic
        @see show_observation_matrix

        """

        network_dynamic = numpy.array(cnn_output_dynamic.output)

        plt.imshow(network_dynamic.T, cmap = plt.get_cmap('gray'), interpolation='None', vmin = 0.0, vmax = 1.0)
        plt.show()


Instruction:
Can you generate the documentation for the following Python 3 function
def show_observation_matrix(cnn_output_dynamic):

        observation_matrix = numpy.array(cnn_output_dynamic.allocate_observation_matrix())
        plt.imshow(observation_matrix.T, cmap = plt.get_cmap('gray'), interpolation='None', vmin = 0.0, vmax = 1.0)
        plt.show()

Response: Show the observation matrix of the given chaotic neural network.


Instruction:
Write a Python 3 script for
simulating a chaotic neural network with extrnal stimulus at specified steps.

Response:
def simulate(self, steps, stimulus):
        """!
        @brief Simulates chaotic neural network with extrnal stimulus during specified steps.
        @details Stimulus are considered as a coordinates of neurons and in line with that weights
                 are initialized.

        @param[in] steps (uint): Amount of steps for simulation.
        @param[in] stimulus (list): Stimulus that are used for simulation.

        @return (cnn_dynamic) Output dynamic of the chaotic neural network.

        """

        self.__create_weights(stimulus)
        self.__location = stimulus

        dynamic = cnn_dynamic([], [])
        dynamic.output.append(self.__output)
        dynamic.time.append(0)

        for step in range(1, steps, 1):
            self.__output = self.__calculate_states()

            dynamic.output.append(self.__output)
            dynamic.time.append(step)

        return dynamic


Instruction:
Explain what the following Python 3 code does
def __calculate_states(self):

        output = [ 0.0 for _ in range(self.__num_osc) ]

        for i in range(self.__num_osc):
            output[i] = self.__neuron_evolution(i)

        return output

Response: Calculates the new state of each neuron.


Instruction:
Make a summary of the following Python 3 code
def __neuron_evolution(self, index):
        value = 0.0

        for index_neighbor in range(self.__num_osc):
            value += self.__weights[index][index_neighbor] * (1.0 - 2.0 * (self.__output[index_neighbor] ** 2))

        return value / self.__weights_summary[index]

Response: Calculates the evolution of the specified neuron with specified index.


Instruction:
Create a Python 3 function to
create weights between neurons in line with stimulus.

Response:
def __create_weights(self, stimulus):
        """!
        @brief Create weights between neurons in line with stimulus.

        @param[in] stimulus (list): External stimulus for the chaotic neural network.

        """

        self.__average_distance = average_neighbor_distance(stimulus, self.__amount_neighbors)

        self.__weights = [ [ 0.0 for _ in range(len(stimulus)) ] for _ in range(len(stimulus)) ]
        self.__weights_summary = [ 0.0 for _ in range(self.__num_osc) ]

        if self.__conn_type == type_conn.ALL_TO_ALL:
            self.__create_weights_all_to_all(stimulus)

        elif self.__conn_type == type_conn.TRIANGULATION_DELAUNAY:
            self.__create_weights_delaunay_triangulation(stimulus)


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

        for i in range(len(stimulus)):
            for j in range(i + 1, len(stimulus)):
                weight = self.__calculate_weight(stimulus[i], stimulus[j])

                self.__weights[i][j] = weight
                self.__weights[j][i] = weight

                self.__weights_summary[i] += weight
                self.__weights_summary[j] += weight

Response: Create weight all - to - all structures between the given stimulus and the current chaotic neural network.


Instruction:
Can you write a function in Python 3 where it
creates the weights for a Delaunay triangulation structure between two neurons.

Response:
def __create_weights_delaunay_triangulation(self, stimulus):
        """!
        @brief Create weight Denlauny triangulation structure between neurons in line with stimulus.

        @param[in] stimulus (list): External stimulus for the chaotic neural network.

        """

        points = numpy.array(stimulus)
        triangulation = Delaunay(points)

        for triangle in triangulation.simplices:
            for index_tri_point1 in range(len(triangle)):
                for index_tri_point2 in range(index_tri_point1 + 1, len(triangle)):
                    index_point1 = triangle[index_tri_point1]
                    index_point2 = triangle[index_tri_point2]

                    weight = self.__calculate_weight(stimulus[index_point1], stimulus[index_point2])

                    self.__weights[index_point1][index_point2] = weight
                    self.__weights[index_point2][index_point1] = weight

                    self.__weights_summary[index_point1] += weight
                    self.__weights_summary[index_point2] += weight


Instruction:
Given the following Python 3 function, write the documentation
def __calculate_weight(self, stimulus1, stimulus2):

        distance = euclidean_distance_square(stimulus1, stimulus2)
        return math.exp(-distance / (2.0 * self.__average_distance))

Response: Calculates the weight between two external stimulies.


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

        dimension = len(self.__location[0])
        if (dimension != 3) and (dimension != 2):
            raise NameError('Network that is located in different from 2-d and 3-d dimensions can not be represented')

        (fig, axes) = self.__create_surface(dimension)

        for i in range(0, self.__num_osc, 1):
            if dimension == 2:
                axes.plot(self.__location[i][0], self.__location[i][1], 'bo')
                for j in range(i, self.__num_osc, 1):    # draw connection between two points only one time
                    if self.__weights[i][j] > 0.0:
                        axes.plot([self.__location[i][0], self.__location[j][0]], [self.__location[i][1], self.__location[j][1]], 'b-', linewidth = 0.5)

            elif dimension == 3:
                axes.scatter(self.__location[i][0], self.__location[i][1], self.__location[i][2], c = 'b', marker = 'o')

                for j in range(i, self.__num_osc, 1):    # draw connection between two points only one time
                    if self.__weights[i][j] > 0.0:
                        axes.plot([self.__location[i][0], self.__location[j][0]], [self.__location[i][1], self.__location[j][1]], [self.__location[i][2], self.__location[j][2]], 'b-', linewidth = 0.5)

        plt.grid()
        plt.show()

Response: Show the structure of the network.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def __create_surface(self, dimension):

        rcParams['font.sans-serif'] = ['Arial']
        rcParams['font.size'] = 12

        fig = plt.figure()
        axes = None
        if dimension == 2:
            axes = fig.add_subplot(111)
        elif dimension == 3:
            axes = fig.gca(projection='3d')

        surface_font = FontProperties()
        surface_font.set_name('Arial')
        surface_font.set_size('12')

        return (fig, axes)

Response: Creates a surface for showing the network structure in line with specified dimension.


Instruction:
How would you implement a function in Python 3 that
displays evolution of phase oscillators as set of patterns where the last one means final result of recognition.

Response:
def show_pattern(syncpr_output_dynamic, image_height, image_width):
        """!
        @brief Displays evolution of phase oscillators as set of patterns where the last one means final result of recognition.

        @param[in] syncpr_output_dynamic (syncpr_dynamic): Output dynamic of a syncpr network.
        @param[in] image_height (uint): Height of the pattern (image_height * image_width should be equal to number of oscillators).
        @param[in] image_width (uint): Width of the pattern.

        """
        number_pictures = len(syncpr_output_dynamic);
        iteration_math_step = 1.0;
        if (number_pictures > 50):
            iteration_math_step = number_pictures / 50.0;
            number_pictures = 50;

        number_cols = int(numpy.ceil(number_pictures ** 0.5));
        number_rows = int(numpy.ceil(number_pictures / number_cols));

        real_index = 0, 0;
        double_indexer = True;
        if ( (number_cols == 1) or (number_rows == 1) ):
            real_index = 0;
            double_indexer = False;

        (_, axarr) = plt.subplots(number_rows, number_cols);

        if (number_pictures > 1):
            plt.setp([ax for ax in axarr], visible = False);

        iteration_display = 0.0;
        for iteration in range(len(syncpr_output_dynamic)):
            if (iteration >= iteration_display):
                iteration_display += iteration_math_step;

                ax_handle = axarr;
                if (number_pictures > 1):
                    ax_handle = axarr[real_index];

                syncpr_visualizer.__show_pattern(ax_handle, syncpr_output_dynamic, image_height, image_width, iteration);

                if (double_indexer is True):
                    real_index = real_index[0], real_index[1] + 1;
                    if (real_index[1] >= number_cols):
                        real_index = real_index[0] + 1, 0;
                else:
                    real_index += 1;

        plt.show();


Instruction:
Explain what the following Python 3 code does
def animate_pattern_recognition(syncpr_output_dynamic, image_height, image_width, animation_velocity = 75, title = None, save_movie = None):
        figure = plt.figure();

        def init_frame():
            return frame_generation(0);

        def frame_generation(index_dynamic):
            figure.clf();

            if (title is not None):
                figure.suptitle(title, fontsize = 26, fontweight = 'bold')

            ax1 = figure.add_subplot(121, projection='polar');
            ax2 = figure.add_subplot(122);

            dynamic = syncpr_output_dynamic.output[index_dynamic];

            artist1, = ax1.plot(dynamic, [1.0] * len(dynamic), marker = 'o', color = 'blue', ls = '');
            artist2 = syncpr_visualizer.__show_pattern(ax2, syncpr_output_dynamic, image_height, image_width, index_dynamic);

            return [ artist1, artist2 ];

        cluster_animation = animation.FuncAnimation(figure, frame_generation, len(syncpr_output_dynamic), interval = animation_velocity, init_func = init_frame, repeat_delay = 5000);

        if (save_movie is not None):
#             plt.rcParams['animation.ffmpeg_path'] = 'C:\\Users\\annoviko\\programs\\ffmpeg-win64-static\\bin\\ffmpeg.exe';
#             ffmpeg_writer = animation.FFMpegWriter();
#             cluster_animation.save(save_movie, writer = ffmpeg_writer, fps = 15);
            cluster_animation.save(save_movie, writer = 'ffmpeg', fps = 15, bitrate = 1500);
        else:
            plt.show();

Response: Animate the pattern recognition process that has been preformed by the oscillatory network.


Instruction:
Explain what the following Python 3 code does
def __show_pattern(ax_handle, syncpr_output_dynamic, image_height, image_width, iteration):

        current_dynamic = syncpr_output_dynamic.output[iteration];
        stage_picture = [(255, 255, 255)] * (image_height * image_width);
        for index_phase in range(len(current_dynamic)):
            phase = current_dynamic[index_phase];

            pixel_color = math.floor( phase * (255 / (2 * math.pi)) );
            stage_picture[index_phase] = (pixel_color, pixel_color, pixel_color);

        stage = numpy.array(stage_picture, numpy.uint8);
        stage = numpy.reshape(stage, (image_height, image_width) + ((3),)); # ((3),) it's size of RGB - third dimension.

        image_cluster = Image.fromarray(stage);

        artist = ax_handle.imshow(image_cluster, interpolation = 'none');
        plt.setp(ax_handle, visible = True);

        ax_handle.xaxis.set_ticklabels([]);
        ax_handle.yaxis.set_ticklabels([]);
        ax_handle.xaxis.set_ticks_position('none');
        ax_handle.yaxis.set_ticks_position('none');

        return artist;

Response: Displays a pattern on the specified axes.


Instruction:
Can you implement a function in Python 3 that
trains syncpr network using Hebbian rule for adjusting strength of connections between oscillators during training.

Response:
def train(self, samples):
        """!
        @brief Trains syncpr network using Hebbian rule for adjusting strength of connections between oscillators during training.

        @param[in] samples (list): list of patterns where each pattern is represented by list of features that are equal to [-1; 1].

        """

        # Verify pattern for learning
        for pattern in samples:
            self.__validate_pattern(pattern);

        if (self._ccore_network_pointer is not None):
            return wrapper.syncpr_train(self._ccore_network_pointer, samples);

        length = len(self);
        number_samples = len(samples);

        for i in range(length):
            for j in range(i + 1, len(self), 1):

                # go through via all patterns
                for p in range(number_samples):
                    value1 = samples[p][i];
                    value2 = samples[p][j];

                    self._coupling[i][j] += value1 * value2;

                self._coupling[i][j] /= length;
                self._coupling[j][i] = self._coupling[i][j];


Instruction:
Write a Python 3 script to
simulate dynamic features of a given pattern.

Response:
def simulate_dynamic(self, pattern, order = 0.998, solution = solve_type.RK4, collect_dynamic = False, step = 0.1, int_step = 0.01, threshold_changes = 0.0000001):
        """!
        @brief Performs dynamic simulation of the network until stop condition is not reached.
        @details In other words network performs pattern recognition during simulation.
                 Stop condition is defined by input argument 'order' that represents memory order, but
                 process of simulation can be stopped if convergance rate is low whose threshold is defined
                 by the argument 'threshold_changes'.

        @param[in] pattern (list): Pattern for recognition represented by list of features that are equal to [-1; 1].
        @param[in] order (double): Order of process synchronization, distributed 0..1.
        @param[in] solution (solve_type): Type of solution.
        @param[in] collect_dynamic (bool): If True - returns whole dynamic of oscillatory network, otherwise returns only last values of dynamics.
        @param[in] step (double): Time step of one iteration of simulation.
        @param[in] int_step (double): Integration step, should be less than step.
        @param[in] threshold_changes (double): Additional stop condition that helps prevent infinite simulation, defines limit of changes of oscillators between current and previous steps.

        @return (list) Dynamic of oscillatory network. If argument 'collect_dynamic' = True, than return dynamic for the whole simulation time,
                otherwise returns only last values (last step of simulation) of dynamic.

        @see simulate()
        @see simulate_static()

        """

        self.__validate_pattern(pattern);

        if (self._ccore_network_pointer is not None):
            ccore_instance_dynamic = wrapper.syncpr_simulate_dynamic(self._ccore_network_pointer, pattern, order, solution, collect_dynamic, step);
            return syncpr_dynamic(None, None, ccore_instance_dynamic);

        for i in range(0, len(pattern), 1):
            if (pattern[i] > 0.0):
                self._phases[i] = 0.0;
            else:
                self._phases[i] = math.pi / 2.0;

        # For statistics and integration
        time_counter = 0;

        # Prevent infinite loop. It's possible when required state cannot be reached.
        previous_order = 0;
        current_order = self.__calculate_memory_order(pattern);

        # If requested input dynamics
        dyn_phase = [];
        dyn_time = [];
        if (collect_dynamic == True):
            dyn_phase.append(self._phases);
            dyn_time.append(0);

        # Execute until sync state will be reached
        while (current_order < order):
            # update states of oscillators
            self._phases = self._calculate_phases(solution, time_counter, step, int_step);

            # update time
            time_counter += step;

            # if requested input dynamic
            if (collect_dynamic == True):
                dyn_phase.append(self._phases);
                dyn_time.append(time_counter);

            # update orders
            previous_order = current_order;
            current_order = self.__calculate_memory_order(pattern);

            # hang prevention
            if (abs(current_order - previous_order) < threshold_changes):
                break;

        if (collect_dynamic != True):
            dyn_phase.append(self._phases);
            dyn_time.append(time_counter);

        output_sync_dynamic = syncpr_dynamic(dyn_phase, dyn_time, None);
        return output_sync_dynamic;


Instruction:
Given the following Python 3 function, write the documentation
def memory_order(self, pattern):

        self.__validate_pattern(pattern);

        if (self._ccore_network_pointer is not None):
            return wrapper.syncpr_memory_order(self._ccore_network_pointer, pattern);

        else:
            return self.__calculate_memory_order(pattern);

Response: This method calculates the memory order of the specified pattern.


Instruction:
Write a Python 3 script for
calculating the memory order of the recognition for the specified pattern.

Response:
def __calculate_memory_order(self, pattern):
        """!
        @brief Calculates function of the memorized pattern without any pattern validation.

        @param[in] pattern (list): Pattern for recognition represented by list of features that are equal to [-1; 1].

        @return (double) Order of memory for the specified pattern.

        """

        memory_order = 0.0;
        for index in range(len(self)):
            memory_order += pattern[index] * cmath.exp( 1j * self._phases[index] );

        memory_order /= len(self);
        return abs(memory_order);


Instruction:
Can you generate the documentation for the following Python 3 function
def _phase_kuramoto(self, teta, t, argv):

        index = argv;

        phase = 0.0;
        term = 0.0;

        for k in range(0, self._num_osc):
            if (k != index):
                phase_delta = self._phases[k] - teta;

                phase += self._coupling[index][k] * math.sin(phase_delta);

                term1 = self._increase_strength1 * math.sin(2.0 * phase_delta);
                term2 = self._increase_strength2 * math.sin(3.0 * phase_delta);

                term += (term1 - term2);

        return ( phase + term / len(self) );

Response: This function calculates the phase of the specified oscillator in the simulation.


Instruction:
Make a summary of the following Python 3 code
def __validate_pattern(self, pattern):
        if (len(pattern) != len(self)):
            raise NameError('syncpr: length of the pattern (' + len(pattern) + ') should be equal to size of the network');

        for feature in pattern:
            if ( (feature != -1.0) and (feature != 1.0) ):
                raise NameError('syncpr: patten feature (' + feature + ') should be distributed in [-1; 1]');

Response:
!
        @brief Validates pattern.
        @details Throws exception if length of pattern is not equal to size of the network or if it consists feature with value that are not equal to [-1; 1].

        @param[in] pattern (list): Pattern for recognition represented by list of features that are equal to [-1; 1].


Instruction:
Given the following Python 3 function, write the documentation
def process(self):

        if self.__ccore is True:
            ccore_metric = metric_wrapper.create_instance(self.__metric)
            self.__clusters, self.__medians = wrapper.kmedians(self.__pointer_data, self.__medians, self.__tolerance, self.__itermax, ccore_metric.get_pointer())

        else:
            changes = float('inf')

            # Check for dimension
            if len(self.__pointer_data[0]) != len(self.__medians[0]):
                raise NameError('Dimension of the input data and dimension of the initial medians must be equal.')

            iterations = 0
            while changes > self.__tolerance and iterations < self.__itermax:
                self.__clusters = self.__update_clusters()
                updated_centers = self.__update_medians()

                changes = max([self.__metric(self.__medians[index], updated_centers[index]) for index in range(len(updated_centers))])

                self.__medians = updated_centers

                iterations += 1

        return self

Response: A method that processes the cluster analysis in line with rules of K - Medians algorithm.


Instruction:
Make a summary of the following Python 3 code
def __update_clusters(self):

        clusters = [[] for i in range(len(self.__medians))]
        for index_point in range(len(self.__pointer_data)):
            index_optim = -1
            dist_optim = 0.0

            for index in range(len(self.__medians)):
                dist = self.__metric(self.__pointer_data[index_point], self.__medians[index])

                if (dist < dist_optim) or (index == 0):
                    index_optim = index
                    dist_optim = dist

            clusters[index_optim].append(index_point)

        # If cluster is not able to capture object it should be removed
        clusters = [cluster for cluster in clusters if len(cluster) > 0]

        return clusters

Response: Updates the list of clusters where each cluster contains the same number of objects from data.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def __update_medians(self):

        medians = [[] for i in range(len(self.__clusters))]

        for index in range(len(self.__clusters)):
            medians[index] = [0.0 for i in range(len(self.__pointer_data[0]))]
            length_cluster = len(self.__clusters[index])

            for index_dimension in range(len(self.__pointer_data[0])):
                sorted_cluster = sorted(self.__clusters[index], key=lambda x: self.__pointer_data[x][index_dimension])

                relative_index_median = int(math.floor((length_cluster - 1) / 2))
                index_median = sorted_cluster[relative_index_median]

                if (length_cluster % 2) == 0:
                    index_median_second = sorted_cluster[relative_index_median + 1]
                    medians[index][index_dimension] = (self.__pointer_data[index_median][index_dimension] + self.__pointer_data[index_median_second][index_dimension]) / 2.0

                else:
                    medians[index][index_dimension] = self.__pointer_data[index_median][index_dimension]

        return medians

Response: Updates the list of medians for the current number of clusters in line with contained objects.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def cleanup_old_versions(
    src, keep_last_versions,
    config_file='config.yaml', profile_name=None,
):
    """Deletes old deployed versions of the function in AWS Lambda.

    Won't delete $Latest and any aliased version

    :param str src:
        The path to your Lambda ready project (folder must contain a valid
        config.yaml and handler module (e.g.: service.py).
    :param int keep_last_versions:
        The number of recent versions to keep and not delete
    """
    if keep_last_versions <= 0:
        print("Won't delete all versions. Please do this manually")
    else:
        path_to_config_file = os.path.join(src, config_file)
        cfg = read_cfg(path_to_config_file, profile_name)

        profile_name = cfg.get('profile')
        aws_access_key_id = cfg.get('aws_access_key_id')
        aws_secret_access_key = cfg.get('aws_secret_access_key')

        client = get_client(
            'lambda', profile_name, aws_access_key_id, aws_secret_access_key,
            cfg.get('region'),
        )

        response = client.list_versions_by_function(
            FunctionName=cfg.get('function_name'),
        )
        versions = response.get('Versions')
        if len(response.get('Versions')) < keep_last_versions:
            print('Nothing to delete. (Too few versions published)')
        else:
            version_numbers = [elem.get('Version') for elem in
                               versions[1:-keep_last_versions]]
            for version_number in version_numbers:
                try:
                    client.delete_function(
                        FunctionName=cfg.get('function_name'),
                        Qualifier=version_number,
                    )
                except botocore.exceptions.ClientError as e:
                    print('Skipping Version {}: {}'
                          .format(version_number, e.message))

Response: Delete old deployed versions of the function in AWS Lambda.


Instruction:
Here you have a function in Python 3, explain what it does
def deploy(
        src, requirements=None, local_package=None,
        config_file='config.yaml', profile_name=None,
        preserve_vpc=False
):
    """Deploys a new function to AWS Lambda.

    :param str src:
        The path to your Lambda ready project (folder must contain a valid
        config.yaml and handler module (e.g.: service.py).
    :param str local_package:
        The path to a local package with should be included in the deploy as
        well (and/or is not available on PyPi)
    """
    # Load and parse the config file.
    path_to_config_file = os.path.join(src, config_file)
    cfg = read_cfg(path_to_config_file, profile_name)

    # Copy all the pip dependencies required to run your code into a temporary
    # folder then add the handler file in the root of this directory.
    # Zip the contents of this folder into a single file and output to the dist
    # directory.
    path_to_zip_file = build(
        src, config_file=config_file,
        requirements=requirements,
        local_package=local_package,
    )

    existing_config = get_function_config(cfg)
    if existing_config:
        update_function(cfg, path_to_zip_file, existing_config, preserve_vpc=preserve_vpc)
    else:
        create_function(cfg, path_to_zip_file)

Response: Deploys a new function to AWS Lambda.


Instruction:
Implement a function in Python 3 to
deploy a new function via AWS S3.

Response:
def deploy_s3(
    src, requirements=None, local_package=None,
    config_file='config.yaml', profile_name=None,
    preserve_vpc=False
):
    """Deploys a new function via AWS S3.

    :param str src:
        The path to your Lambda ready project (folder must contain a valid
        config.yaml and handler module (e.g.: service.py).
    :param str local_package:
        The path to a local package with should be included in the deploy as
        well (and/or is not available on PyPi)
    """
    # Load and parse the config file.
    path_to_config_file = os.path.join(src, config_file)
    cfg = read_cfg(path_to_config_file, profile_name)

    # Copy all the pip dependencies required to run your code into a temporary
    # folder then add the handler file in the root of this directory.
    # Zip the contents of this folder into a single file and output to the dist
    # directory.
    path_to_zip_file = build(
        src, config_file=config_file, requirements=requirements,
        local_package=local_package,
    )

    use_s3 = True
    s3_file = upload_s3(cfg, path_to_zip_file, use_s3)
    existing_config = get_function_config(cfg)
    if existing_config:
        update_function(cfg, path_to_zip_file, existing_config, use_s3=use_s3,
                        s3_file=s3_file, preserve_vpc=preserve_vpc)
    else:
        create_function(cfg, path_to_zip_file, use_s3=use_s3, s3_file=s3_file)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def upload(
        src, requirements=None, local_package=None,
        config_file='config.yaml', profile_name=None,
):
    """Uploads a new function to AWS S3.

    :param str src:
        The path to your Lambda ready project (folder must contain a valid
        config.yaml and handler module (e.g.: service.py).
    :param str local_package:
        The path to a local package with should be included in the deploy as
        well (and/or is not available on PyPi)
    """
    # Load and parse the config file.
    path_to_config_file = os.path.join(src, config_file)
    cfg = read_cfg(path_to_config_file, profile_name)

    # Copy all the pip dependencies required to run your code into a temporary
    # folder then add the handler file in the root of this directory.
    # Zip the contents of this folder into a single file and output to the dist
    # directory.
    path_to_zip_file = build(
        src, config_file=config_file, requirements=requirements,
        local_package=local_package,
    )

    upload_s3(cfg, path_to_zip_file)

Response: Uploads a new function to AWS Lambda ready project.


Instruction:
Write a Python 3 function for
invoking a function in Lambda ready project.

Response:
def invoke(
    src, event_file='event.json',
    config_file='config.yaml', profile_name=None,
    verbose=False,
):
    """Simulates a call to your function.

    :param str src:
        The path to your Lambda ready project (folder must contain a valid
        config.yaml and handler module (e.g.: service.py).
    :param str alt_event:
        An optional argument to override which event file to use.
    :param bool verbose:
        Whether to print out verbose details.
    """
    # Load and parse the config file.
    path_to_config_file = os.path.join(src, config_file)
    cfg = read_cfg(path_to_config_file, profile_name)

    # Set AWS_PROFILE environment variable based on `--profile` option.
    if profile_name:
        os.environ['AWS_PROFILE'] = profile_name

    # Load environment variables from the config file into the actual
    # environment.
    env_vars = cfg.get('environment_variables')
    if env_vars:
        for key, value in env_vars.items():
            os.environ[key] = get_environment_variable_value(value)

    # Load and parse event file.
    path_to_event_file = os.path.join(src, event_file)
    event = read(path_to_event_file, loader=json.loads)

    # Tweak to allow module to import local modules
    try:
        sys.path.index(src)
    except ValueError:
        sys.path.append(src)

    handler = cfg.get('handler')
    # Inspect the handler string (<module>.<function name>) and translate it
    # into a function we can execute.
    fn = get_callable_handler_function(src, handler)

    timeout = cfg.get('timeout')
    if timeout:
        context = LambdaContext(cfg.get('function_name'),timeout)
    else:
        context = LambdaContext(cfg.get('function_name'))

    start = time.time()
    results = fn(event, context)
    end = time.time()

    print('{0}'.format(results))
    if verbose:
        print('\nexecution time: {:.8f}s\nfunction execution '
              'timeout: {:2}s'.format(end - start, cfg.get('timeout', 15)))


Instruction:
Create a Python 3 function to
copy template files to a given directory.

Response:
def init(src, minimal=False):
    """Copies template files to a given directory.

    :param str src:
        The path to output the template lambda project files.
    :param bool minimal:
        Minimal possible template files (excludes event.json).
    """

    templates_path = os.path.join(
        os.path.dirname(os.path.abspath(__file__)), 'project_templates',
    )
    for filename in os.listdir(templates_path):
        if (minimal and filename == 'event.json') or filename.endswith('.pyc'):
            continue
        dest_path = os.path.join(templates_path, filename)

        if not os.path.isdir(dest_path):
            copy(dest_path, src)


Instruction:
Can you tell what is the following Python 3 function doing
def build(
    src, requirements=None, local_package=None,
    config_file='config.yaml', profile_name=None,
):
    """Builds the file bundle.

    :param str src:
       The path to your Lambda ready project (folder must contain a valid
        config.yaml and handler module (e.g.: service.py).
    :param str local_package:
        The path to a local package with should be included in the deploy as
        well (and/or is not available on PyPi)
    """
    # Load and parse the config file.
    path_to_config_file = os.path.join(src, config_file)
    cfg = read_cfg(path_to_config_file, profile_name)

    # Get the absolute path to the output directory and create it if it doesn't
    # already exist.
    dist_directory = cfg.get('dist_directory', 'dist')
    path_to_dist = os.path.join(src, dist_directory)
    mkdir(path_to_dist)

    # Combine the name of the Lambda function with the current timestamp to use
    # for the output filename.
    function_name = cfg.get('function_name')
    output_filename = '{0}-{1}.zip'.format(timestamp(), function_name)

    path_to_temp = mkdtemp(prefix='aws-lambda')
    pip_install_to_target(
        path_to_temp,
        requirements=requirements,
        local_package=local_package,
    )

    # Hack for Zope.
    if 'zope' in os.listdir(path_to_temp):
        print(
            'Zope packages detected; fixing Zope package paths to '
            'make them importable.',
        )
        # Touch.
        with open(os.path.join(path_to_temp, 'zope/__init__.py'), 'wb'):
            pass

    # Gracefully handle whether ".zip" was included in the filename or not.
    output_filename = (
        '{0}.zip'.format(output_filename)
        if not output_filename.endswith('.zip')
        else output_filename
    )

    # Allow definition of source code directories we want to build into our
    # zipped package.
    build_config = defaultdict(**cfg.get('build', {}))
    build_source_directories = build_config.get('source_directories', '')
    build_source_directories = (
        build_source_directories
        if build_source_directories is not None
        else ''
    )
    source_directories = [
        d.strip() for d in build_source_directories.split(',')
    ]

    files = []
    for filename in os.listdir(src):
        if os.path.isfile(filename):
            if filename == '.DS_Store':
                continue
            if filename == config_file:
                continue
            print('Bundling: %r' % filename)
            files.append(os.path.join(src, filename))
        elif os.path.isdir(filename) and filename in source_directories:
            print('Bundling directory: %r' % filename)
            files.append(os.path.join(src, filename))

    # "cd" into `temp_path` directory.
    os.chdir(path_to_temp)
    for f in files:
        if os.path.isfile(f):
            _, filename = os.path.split(f)

            # Copy handler file into root of the packages folder.
            copyfile(f, os.path.join(path_to_temp, filename))
            copystat(f, os.path.join(path_to_temp, filename))
        elif os.path.isdir(f):
            destination_folder = os.path.join(path_to_temp, f[len(src) + 1:])
            copytree(f, destination_folder)

    # Zip them together into a single file.
    # TODO: Delete temp directory created once the archive has been compiled.
    path_to_zip_file = archive('./', path_to_dist, output_filename)
    return path_to_zip_file

Response: Builds a new Lambda ready project.


Instruction:
Explain what the following Python 3 code does
def get_callable_handler_function(src, handler):

    # "cd" into `src` directory.
    os.chdir(src)

    module_name, function_name = handler.split('.')
    filename = get_handler_filename(handler)

    path_to_module_file = os.path.join(src, filename)
    module = load_source(module_name, path_to_module_file)
    return getattr(module, function_name)

Response:
Tranlate a string of the form module. function into a callable
    function.


Instruction:
Make a summary of the following Python 3 code
def _install_packages(path, packages):
    def _filter_blacklist(package):
        blacklist = ['-i', '#', 'Python==', 'python-lambda==']
        return all(package.startswith(entry) is False for entry in blacklist)
    filtered_packages = filter(_filter_blacklist, packages)
    for package in filtered_packages:
        if package.startswith('-e '):
            package = package.replace('-e ', '')

        print('Installing {package}'.format(package=package))
        subprocess.check_call([sys.executable, '-m', 'pip', 'install', package, '-t', path, '--ignore-installed'])
    print ('Install directory contents are now: {directory}'.format(directory=os.listdir(path)))

Response: Install all packages listed to the target directory.


Instruction:
Can you tell what is the following Python 3 function doing
def pip_install_to_target(path, requirements=None, local_package=None):
    packages = []
    if not requirements:
        print('Gathering pip packages')
        pkgStr = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
        packages.extend(pkgStr.decode('utf-8').splitlines())
    else:
        if os.path.exists(requirements):
            print('Gathering requirement packages')
            data = read(requirements)
            packages.extend(data.splitlines())

    if not packages:
        print('No dependency packages installed!')

    if local_package is not None:
        if not isinstance(local_package, (list, tuple)):
            local_package = [local_package]
        for l_package in local_package:
            packages.append(l_package)
    _install_packages(path, packages)

Response: This function installs all installed pip packages to the target path.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_role_name(region, account_id, role):
    prefix = ARN_PREFIXES.get(region, 'aws')
    return 'arn:{0}:iam::{1}:role/{2}'.format(prefix, account_id, role)

Response: Shortcut to insert the account_id and role into the iam string.


Instruction:
Can you implement a function in Python 3 that
queries STS for a users account_id

Response:
def get_account_id(
    profile_name, aws_access_key_id, aws_secret_access_key,
    region=None,
):
    """Query STS for a users' account_id"""
    client = get_client(
        'sts', profile_name, aws_access_key_id, aws_secret_access_key,
        region,
    )
    return client.get_caller_identity().get('Account')


Instruction:
Write a Python 3 function for
creating a new Lambda function.

Response:
def create_function(cfg, path_to_zip_file, use_s3=False, s3_file=None):
    """Register and upload a function to AWS Lambda."""

    print('Creating your new Lambda function')
    byte_stream = read(path_to_zip_file, binary_file=True)
    profile_name = cfg.get('profile')
    aws_access_key_id = cfg.get('aws_access_key_id')
    aws_secret_access_key = cfg.get('aws_secret_access_key')

    account_id = get_account_id(
        profile_name, aws_access_key_id, aws_secret_access_key, cfg.get(
            'region',
        ),
    )
    role = get_role_name(
        cfg.get('region'), account_id,
        cfg.get('role', 'lambda_basic_execution'),
    )

    client = get_client(
        'lambda', profile_name, aws_access_key_id, aws_secret_access_key,
        cfg.get('region'),
    )

    # Do we prefer development variable over config?
    buck_name = (
        os.environ.get('S3_BUCKET_NAME') or cfg.get('bucket_name')
    )
    func_name = (
        os.environ.get('LAMBDA_FUNCTION_NAME') or cfg.get('function_name')
    )
    print('Creating lambda function with name: {}'.format(func_name))

    if use_s3:
        kwargs = {
            'FunctionName': func_name,
            'Runtime': cfg.get('runtime', 'python2.7'),
            'Role': role,
            'Handler': cfg.get('handler'),
            'Code': {
                'S3Bucket': '{}'.format(buck_name),
                'S3Key': '{}'.format(s3_file),
            },
            'Description': cfg.get('description', ''),
            'Timeout': cfg.get('timeout', 15),
            'MemorySize': cfg.get('memory_size', 512),
            'VpcConfig': {
                'SubnetIds': cfg.get('subnet_ids', []),
                'SecurityGroupIds': cfg.get('security_group_ids', []),
            },
            'Publish': True,
        }
    else:
        kwargs = {
            'FunctionName': func_name,
            'Runtime': cfg.get('runtime', 'python2.7'),
            'Role': role,
            'Handler': cfg.get('handler'),
            'Code': {'ZipFile': byte_stream},
            'Description': cfg.get('description', ''),
            'Timeout': cfg.get('timeout', 15),
            'MemorySize': cfg.get('memory_size', 512),
            'VpcConfig': {
                'SubnetIds': cfg.get('subnet_ids', []),
                'SecurityGroupIds': cfg.get('security_group_ids', []),
            },
            'Publish': True,
        }

    if 'tags' in cfg:
        kwargs.update(
            Tags={
                key: str(value)
                for key, value in cfg.get('tags').items()
            }
        )

    if 'environment_variables' in cfg:
        kwargs.update(
            Environment={
                'Variables': {
                    key: get_environment_variable_value(value)
                    for key, value
                    in cfg.get('environment_variables').items()
                },
            },
        )

    client.create_function(**kwargs)

    concurrency = get_concurrency(cfg)
    if concurrency > 0:
        client.put_function_concurrency(FunctionName=func_name, ReservedConcurrentExecutions=concurrency)


Instruction:
Implement a Python 3 function for
updating the code of an existing Lambda function

Response:
def update_function(
        cfg, path_to_zip_file, existing_cfg, use_s3=False, s3_file=None, preserve_vpc=False
):
    """Updates the code of an existing Lambda function"""

    print('Updating your Lambda function')
    byte_stream = read(path_to_zip_file, binary_file=True)
    profile_name = cfg.get('profile')
    aws_access_key_id = cfg.get('aws_access_key_id')
    aws_secret_access_key = cfg.get('aws_secret_access_key')

    account_id = get_account_id(
        profile_name, aws_access_key_id, aws_secret_access_key, cfg.get(
            'region',
        ),
    )
    role = get_role_name(
        cfg.get('region'), account_id,
        cfg.get('role', 'lambda_basic_execution'),
    )

    client = get_client(
        'lambda', profile_name, aws_access_key_id, aws_secret_access_key,
        cfg.get('region'),
    )

    # Do we prefer development variable over config?
    buck_name = (
        os.environ.get('S3_BUCKET_NAME') or cfg.get('bucket_name')
    )

    if use_s3:
        client.update_function_code(
            FunctionName=cfg.get('function_name'),
            S3Bucket='{}'.format(buck_name),
            S3Key='{}'.format(s3_file),
            Publish=True,
        )
    else:
        client.update_function_code(
            FunctionName=cfg.get('function_name'),
            ZipFile=byte_stream,
            Publish=True,
        )

    kwargs = {
        'FunctionName': cfg.get('function_name'),
        'Role': role,
        'Runtime': cfg.get('runtime'),
        'Handler': cfg.get('handler'),
        'Description': cfg.get('description', ''),
        'Timeout': cfg.get('timeout', 15),
        'MemorySize': cfg.get('memory_size', 512),
    }

    if preserve_vpc:
        kwargs['VpcConfig'] = existing_cfg.get('Configuration', {}).get('VpcConfig')
        if kwargs['VpcConfig'] is None:
            kwargs['VpcConfig'] = {
                'SubnetIds': cfg.get('subnet_ids', []),
                'SecurityGroupIds': cfg.get('security_group_ids', []),
            }
        else:
            del kwargs['VpcConfig']['VpcId']
    else:
        kwargs['VpcConfig'] = {
            'SubnetIds': cfg.get('subnet_ids', []),
            'SecurityGroupIds': cfg.get('security_group_ids', []),
        }

    if 'environment_variables' in cfg:
        kwargs.update(
            Environment={
                'Variables': {
                    key: str(get_environment_variable_value(value))
                    for key, value
                    in cfg.get('environment_variables').items()
                },
            },
        )

    ret = client.update_function_configuration(**kwargs)

    concurrency = get_concurrency(cfg)
    if concurrency > 0:
        client.put_function_concurrency(FunctionName=cfg.get('function_name'), ReservedConcurrentExecutions=concurrency)
    elif 'Concurrency' in existing_cfg:
        client.delete_function_concurrency(FunctionName=cfg.get('function_name'))

    if 'tags' in cfg:
        tags = {
            key: str(value)
            for key, value in cfg.get('tags').items()
        }
        if tags != existing_cfg.get('Tags'):
            if existing_cfg.get('Tags'):
                client.untag_resource(Resource=ret['FunctionArn'],
                                      TagKeys=list(existing_cfg['Tags'].keys()))
            client.tag_resource(Resource=ret['FunctionArn'], Tags=tags)


Instruction:
Can you tell what is the following Python 3 function doing
def upload_s3(cfg, path_to_zip_file, *use_s3):

    print('Uploading your new Lambda function')
    profile_name = cfg.get('profile')
    aws_access_key_id = cfg.get('aws_access_key_id')
    aws_secret_access_key = cfg.get('aws_secret_access_key')
    client = get_client(
        's3', profile_name, aws_access_key_id, aws_secret_access_key,
        cfg.get('region'),
    )
    byte_stream = b''
    with open(path_to_zip_file, mode='rb') as fh:
        byte_stream = fh.read()
    s3_key_prefix = cfg.get('s3_key_prefix', '/dist')
    checksum = hashlib.new('md5', byte_stream).hexdigest()
    timestamp = str(time.time())
    filename = '{prefix}{checksum}-{ts}.zip'.format(
        prefix=s3_key_prefix, checksum=checksum, ts=timestamp,
    )

    # Do we prefer development variable over config?
    buck_name = (
        os.environ.get('S3_BUCKET_NAME') or cfg.get('bucket_name')
    )
    func_name = (
        os.environ.get('LAMBDA_FUNCTION_NAME') or cfg.get('function_name')
    )
    kwargs = {
        'Bucket': '{}'.format(buck_name),
        'Key': '{}'.format(filename),
        'Body': byte_stream,
    }

    client.put_object(**kwargs)
    print('Finished uploading {} to S3 bucket {}'.format(func_name, buck_name))
    if use_s3:
        return filename

Response: Upload a file to AWS S3.


Instruction:
Can you implement a function in Python 3 that
checks whether a function exists or not and return its config

Response:
def get_function_config(cfg):
    """Check whether a function exists or not and return its config"""

    function_name = cfg.get('function_name')
    profile_name = cfg.get('profile')
    aws_access_key_id = cfg.get('aws_access_key_id')
    aws_secret_access_key = cfg.get('aws_secret_access_key')
    client = get_client(
        'lambda', profile_name, aws_access_key_id, aws_secret_access_key,
        cfg.get('region'),
    )

    try:
        return client.get_function(FunctionName=function_name)
    except client.exceptions.ResourceNotFoundException as e:
        if 'Function not found' in str(e):
            return False


Instruction:
Implement a Python 3 function for
downloading the data at a URL and cache it under the given name.

Response:
def cached_download(url, name):

    """Download the data at a URL, and cache it under the given name.

    The file is stored under `pyav/test` with the given name in the directory
    :envvar:`PYAV_TESTDATA_DIR`, or the first that is writeable of:

    - the current virtualenv
    - ``/usr/local/share``
    - ``/usr/local/lib``
    - ``/usr/share``
    - ``/usr/lib``
    - the user's home

    """

    clean_name = os.path.normpath(name)
    if clean_name != name:
        raise ValueError("{} is not normalized.".format(name))

    for dir_ in iter_data_dirs():
        path = os.path.join(dir_, name)
        if os.path.exists(path):
            return path

    dir_ = next(iter_data_dirs(True))
    path = os.path.join(dir_, name)

    log.info("Downloading {} to {}".format(url, path))

    response = urlopen(url)
    if response.getcode() != 200:
        raise ValueError("HTTP {}".format(response.getcode()))

    dir_ = os.path.dirname(path)
    try:
        os.makedirs(dir_)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

    tmp_path = path + '.tmp'
    with open(tmp_path, 'wb') as fh:
        while True:
            chunk = response.read(8196)
            if chunk:
                fh.write(chunk)
            else:
                break

    os.rename(tmp_path, path)

    return path


Instruction:
Can you write a function in Python 3 where it
downloads and return a path to a sample from the FFmpeg test suite.

Response:
def fate(name):
    """Download and return a path to a sample from the FFmpeg test suite.

    Data is handled by :func:`cached_download`.

    See the `FFmpeg Automated Test Environment <https://www.ffmpeg.org/fate.html>`_

    """
    return cached_download('http://fate.ffmpeg.org/fate-suite/' + name,
                           os.path.join('fate-suite', name.replace('/', os.path.sep)))


Instruction:
Here you have a function in Python 3, explain what it does
def curated(name):
    return cached_download('https://docs.mikeboers.com/pyav/samples/' + name,
                           os.path.join('pyav-curated', name.replace('/', os.path.sep)))

Response: Download and return a path to a sample that is curated by the PyAV developers.


Instruction:
Write a Python 3 function for
getting distutils - compatible extension extras for the given library.

Response:
def get_library_config(name):
    """Get distutils-compatible extension extras for the given library.

    This requires ``pkg-config``.

    """
    try:
        proc = Popen(['pkg-config', '--cflags', '--libs', name], stdout=PIPE, stderr=PIPE)
    except OSError:
        print('pkg-config is required for building PyAV')
        exit(1)

    raw_cflags, err = proc.communicate()
    if proc.wait():
        return

    known, unknown = parse_cflags(raw_cflags.decode('utf8'))
    if unknown:
        print("pkg-config returned flags we don't understand: {}".format(unknown))
        exit(1)

    return known


Instruction:
Make a summary of the following Python 3 code
def update_extend(dst, src):
    for k, v in src.items():
        existing = dst.setdefault(k, [])
        for x in v:
            if x not in existing:
                existing.append(x)

Response:
Update the dst with the src extending values where lists.
    Primiarily useful for integrating results from get_library_config.


Instruction:
Write a Python 3 function for
printing out all the config information we have so far.

Response:
def dump_config():
    """Print out all the config information we have so far (for debugging)."""
    print('PyAV:', version, git_commit or '(unknown commit)')
    print('Python:', sys.version.encode('unicode_escape' if PY3 else 'string-escape'))
    print('platform:', platform.platform())
    print('extension_extra:')
    for k, vs in extension_extra.items():
        print('\t%s: %s' % (k, [x.encode('utf8') for x in vs]))
    print('config_macros:')
    for x in sorted(config_macros.items()):
        print('\t%s=%s' % x)


Instruction:
Can you generate the documentation for the following Python 3 function
def _CCompiler_spawn_silent(cmd, dry_run=None):
    proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()
    if proc.returncode:
        raise DistutilsExecError(err)

Response: Spawn a process and eat the stdio.


Instruction:
Write a Python 3 script to
create a new C compiler.

Response:
def new_compiler(*args, **kwargs):
    """Create a C compiler.

    :param bool silent: Eat all stdio? Defaults to ``True``.

    All other arguments passed to ``distutils.ccompiler.new_compiler``.

    """
    make_silent = kwargs.pop('silent', True)
    cc = _new_compiler(*args, **kwargs)
    # If MSVC10, initialize the compiler here and add /MANIFEST to linker flags.
    # See Python issue 4431 (https://bugs.python.org/issue4431)
    if is_msvc(cc):
        from distutils.msvc9compiler import get_build_version
        if get_build_version() == 10:
            cc.initialize()
            for ldflags in [cc.ldflags_shared, cc.ldflags_shared_debug]:
                unique_extend(ldflags, ['/MANIFEST'])
        # If MSVC14, do not silence. As msvc14 requires some custom
        # steps before the process is spawned, we can't monkey-patch this.
        elif get_build_version() == 14:
            make_silent = False
    # monkey-patch compiler to suppress stdout and stderr.
    if make_silent:
        cc.spawn = _CCompiler_spawn_silent
    return cc


Instruction:
How would you implement a function in Python 3 that
yields all. pyx and. pxd files in the given root.

Response:
def iter_cython(path):
    '''Yield all ``.pyx`` and ``.pxd`` files in the given root.'''
    for dir_path, dir_names, file_names in os.walk(path):
        for file_name in file_names:
            if file_name.startswith('.'):
                continue
            if os.path.splitext(file_name)[1] not in ('.pyx', '.pxd'):
                continue
            yield os.path.join(dir_path, file_name)


Instruction:
Can you implement a function in Python 3 that
cleans up the given text.

Response:
def cleanup_text (text):
    """
    It scrubs the garbled from its stream...
    Or it gets the debugger again.
    """
    x = " ".join(map(lambda s: s.strip(), text.split("\n"))).strip()

    x = x.replace('“', '"').replace('”', '"')
    x = x.replace("‘", "'").replace("’", "'").replace("`", "'")
    x = x.replace('…', '...').replace('–', '-')

    x = str(unicodedata.normalize('NFKD', x).encode('ascii', 'ignore').decode('ascii'))

    # some content returns text in bytes rather than as a str ?
    try:
        assert type(x).__name__ == 'str'
    except AssertionError:
        print("not a string?", type(line), line)

    return x


Instruction:
Can you implement a function in Python 3 that
splits the raw text into paragraphs IUM

Response:
def split_grafs (lines):
    """
    segment the raw text into paragraphs
    """
    graf = []

    for line in lines:
        line = line.strip()

        if len(line) < 1:
            if len(graf) > 0:
                yield "\n".join(graf)
                graf = []
        else:
            graf.append(line)

    if len(graf) > 0:
        yield "\n".join(graf)


Instruction:
Can you create a Python 3 function that
filters the quoted text out of a message

Response:
def filter_quotes (text, is_email=True):
    """
    filter the quoted text out of a message
    """
    global DEBUG
    global PAT_FORWARD, PAT_REPLIED, PAT_UNSUBSC

    if is_email:
        text = filter(lambda x: x in string.printable, text)

        if DEBUG:
            print("text:", text)

        # strip off quoted text in a forward
        m = PAT_FORWARD.split(text, re.M)

        if m and len(m) > 1:
            text = m[0]

        # strip off quoted text in a reply
        m = PAT_REPLIED.split(text, re.M)

        if m and len(m) > 1:
            text = m[0]

        # strip off any trailing unsubscription notice
        m = PAT_UNSUBSC.split(text, re.M)

        if m:
            text = m[0]

    # replace any remaining quoted text with blank lines
    lines = []

    for line in text.split("\n"):
        if line.startswith(">"):
            lines.append("")
        else:
            lines.append(line)

    return list(split_grafs(lines))


Instruction:
Implement a function in Python 3 to
get the unique id for each word root

Response:
def get_word_id (root):
    """
    lookup/assign a unique identify for each word root
    """
    global UNIQ_WORDS

    # in practice, this should use a microservice via some robust
    # distributed cache, e.g., Redis, Cassandra, etc.
    if root not in UNIQ_WORDS:
        UNIQ_WORDS[root] = len(UNIQ_WORDS)

    return UNIQ_WORDS[root]