text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_marshaller_for_type_string(self, type_string): """ Gets the appropriate marshaller for a type string. Retrieves the marshaller, if any, that can be used ...
if type_string in self._type_strings: index = self._type_strings[type_string] m = self._marshallers[index] if self._imported_required_modules[index]: return m, True if not self._has_required_modules[index]: return m, False ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_marshaller_for_matlab_class(self, matlab_class): """ Gets the appropriate marshaller for a MATLAB class string. Retrieves the marshaller, if any, that ca...
if matlab_class in self._matlab_classes: index = self._matlab_classes[matlab_class] m = self._marshallers[index] if self._imported_required_modules[index]: return m, True if not self._has_required_modules[index]: return m, False ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_node(self): """Adds a new, blank node to the graph. Returns the node id of the new node."""
node_id = self.generate_node_id() node = {'id': node_id, 'edges': [], 'data': {} } self.nodes[node_id] = node self._num_nodes += 1 return node_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_edge(self, node_a, node_b, cost=1): """Adds a new edge from node_a to node_b that has a cost. Returns the edge id of the new edge."""
# Verify that both nodes exist in the graph try: self.nodes[node_a] except KeyError: raise NonexistentNodeError(node_a) try: self.nodes[node_b] except KeyError: raise NonexistentNodeError(node_b) # Create the new edge ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjacent(self, node_a, node_b): """Determines whether there is an edge from node_a to node_b. Returns True if such an edge exists, otherwise returns False.""...
neighbors = self.neighbors(node_a) return node_b in neighbors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edge_cost(self, node_a, node_b): """Returns the cost of moving between the edge that connects node_a to node_b. Returns +inf if no such edge exists."""
cost = float('inf') node_object_a = self.get_node(node_a) for edge_id in node_object_a['edges']: edge = self.get_edge(edge_id) tpl = (node_a, node_b) if edge['vertices'] == tpl: cost = edge['cost'] break return cost
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_node(self, node_id): """Returns the node object identified by "node_id"."""
try: node_object = self.nodes[node_id] except KeyError: raise NonexistentNodeError(node_id) return node_object
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_edge(self, edge_id): """Returns the edge object identified by "edge_id"."""
try: edge_object = self.edges[edge_id] except KeyError: raise NonexistentEdgeError(edge_id) return edge_object
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_edge_by_nodes(self, node_a, node_b): """Removes all the edges from node_a to node_b from the graph."""
node = self.get_node(node_a) # Determine the edge ids edge_ids = [] for e_id in node['edges']: edge = self.get_edge(e_id) if edge['vertices'][1] == node_b: edge_ids.append(e_id) # Delete the edges for e in edge_ids: s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_node(self, node_id): """Removes the node identified by node_id from the graph."""
node = self.get_node(node_id) # Remove all edges from the node for e in node['edges']: self.delete_edge_by_id(e) # Remove all edges to the node edges = [edge_id for edge_id, edge in list(self.edges.items()) if edge['vertices'][1] == node_id] for e in edges:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_edge_source(self, edge_id, node_a, node_b): """Moves an edge originating from node_a so that it originates from node_b."""
# Grab the edge edge = self.get_edge(edge_id) # Alter the vertices edge['vertices'] = (node_b, edge['vertices'][1]) # Remove the edge from node_a node = self.get_node(node_a) node['edges'].remove(edge_id) # Add the edge to node_b node = self.ge...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_edge_ids_by_node_ids(self, node_a, node_b): """Returns a list of edge ids connecting node_a to node_b."""
# Check if the nodes are adjacent if not self.adjacent(node_a, node_b): return [] # They're adjacent, so pull the list of edges from node_a and determine which ones point to node_b node = self.get_node(node_a) return [edge_id for edge_id in node['edges'] if self.get...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_biconnected_components(graph): """Finds all the biconnected components in a graph. Returns a list of lists, each containing the edges that form a biconn...
list_of_components = [] # Run the algorithm on each of the connected components of the graph components = get_connected_components_as_subgraphs(graph) for component in components: # --Call the internal biconnnected components function to find # --the edge lists for this particular con...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_biconnected_components_as_subgraphs(graph): """Finds the biconnected components and returns them as subgraphs."""
list_of_graphs = [] list_of_components = find_biconnected_components(graph) for edge_list in list_of_components: subgraph = get_subgraph_from_edge_list(graph, edge_list) list_of_graphs.append(subgraph) return list_of_graphs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_articulation_vertices(graph): """Finds all of the articulation vertices within a graph. Returns a list of all articulation vertices within the graph. Re...
articulation_vertices = [] all_nodes = graph.get_all_node_ids() if len(all_nodes) == 0: return articulation_vertices # Run the algorithm on each of the connected components of the graph components = get_connected_components_as_subgraphs(graph) for component in components: # -...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def output_component(graph, edge_stack, u, v): """Helper function to pop edges off the stack and produce a list of them."""
edge_list = [] while len(edge_stack) > 0: edge_id = edge_stack.popleft() edge_list.append(edge_id) edge = graph.get_edge(edge_id) tpl_a = (u, v) tpl_b = (v, u) if tpl_a == edge['vertices'] or tpl_b == edge['vertices']: break return edge_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def depth_first_search_with_parent_data(graph, root_node = None, adjacency_lists = None): """Performs a depth-first search with visiting order of nodes determine...
ordering = [] parent_lookup = {} children_lookup = defaultdict(lambda: []) all_nodes = graph.get_all_node_ids() if not all_nodes: return ordering, parent_lookup, children_lookup stack = deque() discovered = defaultdict(lambda: False) unvisited_nodes = set(all_nodes) if ro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def graph_to_dot(graph, node_renderer=None, edge_renderer=None): """Produces a DOT specification string from the provided graph."""
node_pairs = list(graph.nodes.items()) edge_pairs = list(graph.edges.items()) if node_renderer is None: node_renderer_wrapper = lambda nid: '' else: node_renderer_wrapper = lambda nid: ' [%s]' % ','.join( ['%s=%s' % tpl for tpl in list(node_renderer(graph, nid).items())]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_connected_components(graph): """Finds all connected components of the graph. Returns a list of lists, each containing the nodes that form a connected com...
list_of_components = [] component = [] # Not strictly necessary due to the while loop structure, but it helps the automated analysis tools # Store a list of all unreached vertices unreached = set(graph.get_all_node_ids()) to_explore = deque() while len(unreached) > 0: # This happens...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_connected_components_as_subgraphs(graph): """Finds all connected components of the graph. Returns a list of graph objects, each representing a connected ...
components = get_connected_components(graph) list_of_graphs = [] for c in components: edge_ids = set() nodes = [graph.get_node(node) for node in c] for n in nodes: # --Loop through the edges in each node, to determine if it should be included for e in n['ed...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_edge(self, node_a, node_b, cost=1): """Adds a new, undirected edge between node_a and node_b with a cost. Returns the edge id of the new edge."""
edge_id = super(UndirectedGraph, self).new_edge(node_a, node_b, cost) self.nodes[node_b]['edges'].append(edge_id) return edge_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_edge_by_id(self, edge_id): """Removes the edge identified by "edge_id" from the graph."""
edge = self.get_edge(edge_id) # Remove the edge from the "from node" # --Determine the from node from_node_id = edge['vertices'][0] from_node = self.get_node(from_node_id) # --Remove the edge from it from_node['edges'].remove(edge_id) # Remove the edge...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_minimum_spanning_tree(graph): """Calculates a minimum spanning tree for a graph. Returns a list of edges that define the tree. Returns an empty list for...
mst = [] if graph.num_nodes() == 0: return mst if graph.num_edges() == 0: return mst connected_components = get_connected_components(graph) if len(connected_components) > 1: raise DisconnectedGraphError edge_list = kruskal_mst(graph) return edge_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_minimum_spanning_tree_as_subgraph(graph): """Calculates a minimum spanning tree and returns a graph representation."""
edge_list = find_minimum_spanning_tree(graph) subgraph = get_subgraph_from_edge_list(graph, edge_list) return subgraph
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_minimum_spanning_forest(graph): """Calculates the minimum spanning forest of a disconnected graph. Returns a list of lists, each containing the edges th...
msf = [] if graph.num_nodes() == 0: return msf if graph.num_edges() == 0: return msf connected_components = get_connected_components_as_subgraphs(graph) for subgraph in connected_components: edge_list = kruskal_mst(subgraph) msf.append(edge_list) return msf
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_minimum_spanning_forest_as_subgraphs(graph): """Calculates the minimum spanning forest and returns a list of trees as subgraphs."""
forest = find_minimum_spanning_forest(graph) list_of_subgraphs = [get_subgraph_from_edge_list(graph, edge_list) for edge_list in forest] return list_of_subgraphs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kruskal_mst(graph): """Implements Kruskal's Algorithm for finding minimum spanning trees. Assumes a non-empty, connected graph. """
edges_accepted = 0 ds = DisjointSet() pq = PriorityQueue() accepted_edges = [] label_lookup = {} nodes = graph.get_all_node_ids() num_vertices = len(nodes) for n in nodes: label = ds.add_set() label_lookup[n] = label edges = graph.get_all_edge_objects() for e i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __get_cycle(graph, ordering, parent_lookup): """Gets the main cycle of the dfs tree."""
root_node = ordering[0] for i in range(2, len(ordering)): current_node = ordering[i] if graph.adjacent(current_node, root_node): path = [] while current_node != root_node: path.append(current_node) current_node = parent_lookup[current_node...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __get_segments_from_node(node, graph): """Calculates the segments that can emanate from a particular node on the main cycle."""
list_of_segments = [] node_object = graph.get_node(node) for e in node_object['edges']: list_of_segments.append(e) return list_of_segments
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __get_segments_from_cycle(graph, cycle_path): """Calculates the segments that emanate from the main cycle."""
list_of_segments = [] # We work through the cycle in a bottom-up fashion for n in cycle_path[::-1]: segments = __get_segments_from_node(n, graph) if segments: list_of_segments.append(segments) return list_of_segments
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_subgraph(graph, vertices, edges): """Converts a subgraph given by a list of vertices and edges into a graph object."""
# Copy the entire graph local_graph = copy.deepcopy(graph) # Remove all the edges that aren't in the list edges_to_delete = [x for x in local_graph.get_all_edge_ids() if x not in edges] for e in edges_to_delete: local_graph.delete_edge_by_id(e) # Remove all the vertices that aren't in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_graph_directed_to_undirected(dg): """Converts a directed graph into an undirected graph. Directed edges are made undirected."""
udg = UndirectedGraph() # Copy the graph # --Copy nodes # --Copy edges udg.nodes = copy.deepcopy(dg.nodes) udg.edges = copy.deepcopy(dg.edges) udg.next_node_id = dg.next_node_id udg.next_edge_id = dg.next_edge_id # Convert the directed edges into undirected edges for edge_id ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_duplicate_edges_directed(dg): """Removes duplicate edges from a directed graph."""
# With directed edges, we can just hash the to and from node id tuples and if # a node happens to conflict with one that already exists, we delete it # --For aesthetic, we sort the edge ids so that lower edge ids are kept lookup = {} edges = sorted(dg.get_all_edge_ids()) for edge_id in edges: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_duplicate_edges_undirected(udg): """Removes duplicate edges from an undirected graph."""
# With undirected edges, we need to hash both combinations of the to-from node ids, since a-b and b-a are equivalent # --For aesthetic, we sort the edge ids so that lower edges ids are kept lookup = {} edges = sorted(udg.get_all_edge_ids()) for edge_id in edges: e = udg.get_edge(edge_id) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_vertices_from_edge_list(graph, edge_list): """Transforms a list of edges into a list of the nodes those edges connect. Returns a list of nodes, or an emp...
node_set = set() for edge_id in edge_list: edge = graph.get_edge(edge_id) a, b = edge['vertices'] node_set.add(a) node_set.add(b) return list(node_set)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_subgraph_from_edge_list(graph, edge_list): """Transforms a list of edges into a subgraph."""
node_list = get_vertices_from_edge_list(graph, edge_list) subgraph = make_subgraph(graph, node_list, edge_list) return subgraph
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_graphs(main_graph, addition_graph): """Merges an ''addition_graph'' into the ''main_graph''. Returns a tuple of dictionaries, mapping old node ids and ...
node_mapping = {} edge_mapping = {} for node in addition_graph.get_all_node_objects(): node_id = node['id'] new_id = main_graph.new_node() node_mapping[node_id] = new_id for edge in addition_graph.get_all_edge_objects(): edge_id = edge['id'] old_vertex_a_id, o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_graph_from_adjacency_matrix(adjacency_matrix): """Generates a graph from an adjacency matrix specification. Returns a tuple containing the graph and a...
if is_adjacency_matrix_symmetric(adjacency_matrix): graph = UndirectedGraph() else: graph = DirectedGraph() node_column_mapping = [] num_columns = len(adjacency_matrix) for _ in range(num_columns): node_id = graph.new_node() node_column_mapping.append(node_id) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_set(self): """Adds a new set to the forest. Returns a label by which the new set can be referenced """
self.__label_counter += 1 new_label = self.__label_counter self.__forest[new_label] = -1 # All new sets have their parent set to themselves self.__set_counter += 1 return new_label
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find(self, node_label): """Finds the set containing the node_label. Returns the set label. """
queue = [] current_node = node_label while self.__forest[current_node] >= 0: queue.append(current_node) current_node = self.__forest[current_node] root_node = current_node # Path compression for n in queue: self.__forest[n] = root_nod...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def union(self, label_a, label_b): """Joins two sets into a single new set. label_a, label_b can be any nodes within the sets """
# Base case to avoid work if label_a == label_b: return # Find the tree root of each node root_a = self.find(label_a) root_b = self.find(label_b) # Avoid merging a tree to itself if root_a == root_b: return self.__internal_union...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __internal_union(self, root_a, root_b): """Internal function to join two set trees specified by root_a and root_b. Assumes root_a and root_b are distinct. ""...
# Merge the trees, smaller to larger update_rank = False # --Determine the larger tree rank_a = self.__forest[root_a] rank_b = self.__forest[root_b] if rank_a < rank_b: larger = root_b smaller = root_a else: larger = root_a ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_planar(graph): """Determines whether a graph is planar or not."""
# Determine connected components as subgraphs; their planarity is independent of each other connected_components = get_connected_components_as_subgraphs(graph) for component in connected_components: # Biconnected components likewise have independent planarity biconnected_components = find_b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __is_subgraph_planar(graph): """Internal function to determine if a subgraph is planar."""
# --First pass: Determine edge and vertex counts validate Euler's Formula num_nodes = graph.num_nodes() num_edges = graph.num_edges() # --We can guarantee that if there are 4 or less nodes, then the graph is planar # --A 4-node simple graph has a maximum of 6 possible edges (K4); this will always ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __setup_dfs_data(graph, adj): """Sets up the dfs_data object, for consistency."""
dfs_data = __get_dfs_data(graph, adj) dfs_data['graph'] = graph dfs_data['adj'] = adj L1, L2 = __low_point_dfs(dfs_data) dfs_data['lowpoint_1_lookup'] = L1 dfs_data['lowpoint_2_lookup'] = L2 edge_weights = __calculate_edge_weights(dfs_data) dfs_data['edge_weights'] = edge_weights ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __calculate_edge_weights(dfs_data): """Calculates the weight of each edge, for embedding-order sorting."""
graph = dfs_data['graph'] weights = {} for edge_id in graph.get_all_edge_ids(): edge_weight = __edge_weight(edge_id, dfs_data) weights[edge_id] = edge_weight return weights
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __sort_adjacency_lists(dfs_data): """Sorts the adjacency list representation by the edge weights."""
new_adjacency_lists = {} adjacency_lists = dfs_data['adj'] edge_weights = dfs_data['edge_weights'] edge_lookup = dfs_data['edge_lookup'] for node_id, adj_list in list(adjacency_lists.items()): node_weight_lookup = {} frond_lookup = {} for node_b in adj_list: ed...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __branch_point_dfs_recursive(u, large_n, b, stem, dfs_data): """A recursive implementation of the BranchPtDFS function, as defined on page 14 of the paper.""...
first_vertex = dfs_data['adj'][u][0] large_w = wt(u, first_vertex, dfs_data) if large_w % 2 == 0: large_w += 1 v_I = 0 v_II = 0 for v in [v for v in dfs_data['adj'][u] if wt(u, v, dfs_data) <= large_w]: stem[u] = v # not in the original paper, but a logical extension based on pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __embed_branch(dfs_data): """Builds the combinatorial embedding of the graph. Returns whether the graph is planar."""
u = dfs_data['ordering'][0] dfs_data['LF'] = [] dfs_data['RF'] = [] dfs_data['FG'] = {} n = dfs_data['graph'].num_nodes() f0 = (0, n) g0 = (0, n) L0 = {'u': 0, 'v': n} R0 = {'x': 0, 'y': n} dfs_data['LF'].append(f0) dfs_data['RF'].append(g0) dfs_data['FG'][0] = [L0, R0] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __embed_branch_recursive(u, dfs_data): """A recursive implementation of the EmbedBranch function, as defined on pages 8 and 22 of the paper."""
#print "\nu: {}\nadj: {}".format(u, dfs_data['adj'][u]) #print 'Pre-inserts' #print "FG: {}".format(dfs_data['FG']) #print "LF: {}".format(dfs_data['LF']) #print "RF: {}".format(dfs_data['RF']) for v in dfs_data['adj'][u]: #print "\nu, v: {}, {}".format(u, v) #print "dfs_u, df...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __embed_frond(node_u, node_w, dfs_data, as_branch_marker=False): """Embeds a frond uw into either LF or RF. Returns whether the embedding was successful."""
d_u = D(node_u, dfs_data) d_w = D(node_w, dfs_data) comp_d_w = abs(d_w) if as_branch_marker: d_w *= -1 if dfs_data['last_inserted_side'] == 'LF': __insert_frond_RF(d_w, d_u, dfs_data) else: # We default to inserting a branch marker on the left side, unle...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __insert_frond_RF(d_w, d_u, dfs_data): """Encapsulates the process of inserting a frond uw into the right side frond group."""
# --Add the frond to the right side dfs_data['RF'].append( (d_w, d_u) ) dfs_data['FG']['r'] += 1 dfs_data['last_inserted_side'] = 'RF'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __insert_frond_LF(d_w, d_u, dfs_data): """Encapsulates the process of inserting a frond uw into the left side frond group."""
# --Add the frond to the left side dfs_data['LF'].append( (d_w, d_u) ) dfs_data['FG']['l'] += 1 dfs_data['last_inserted_side'] = 'LF'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_Fm(dfs_data): """Merges Fm-1 and Fm, as defined on page 19 of the paper."""
FG = dfs_data['FG'] m = FG['m'] FGm = FG[m] FGm1 = FG[m-1] if FGm[0]['u'] < FGm1[0]['u']: FGm1[0]['u'] = FGm[0]['u'] if FGm[0]['v'] > FGm1[0]['v']: FGm1[0]['v'] = FGm[0]['v'] if FGm[1]['x'] < FGm1[1]['x']: FGm1[1]['x'] = FGm[1]['x'] if FGm[1]['y'] > FGm1[1]['...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __check_left_side_conflict(x, y, dfs_data): """Checks to see if the frond xy will conflict with a frond on the left side of the embedding."""
l = dfs_data['FG']['l'] w, z = dfs_data['LF'][l] return __check_conflict_fronds(x, y, w, z, dfs_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __check_right_side_conflict(x, y, dfs_data): """Checks to see if the frond xy will conflict with a frond on the right side of the embedding."""
r = dfs_data['FG']['r'] w, z = dfs_data['RF'][r] return __check_conflict_fronds(x, y, w, z, dfs_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __check_conflict_fronds(x, y, w, z, dfs_data): """Checks a pair of fronds to see if they conflict. Returns True if a conflict was found, False otherwise."""
# Case 1: False frond and corresponding branch marker # --x and w should both be negative, and either xy or wz should be the same value uu if x < 0 and w < 0 and (x == y or w == z): # --Determine if the marker and frond correspond (have the same low-value) if x == w: return Tru...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __calculate_adjacency_lists(graph): """Builds an adjacency list representation for the graph, since we can't guarantee that the internal representation of th...
adj = {} for node in graph.get_all_node_ids(): neighbors = graph.neighbors(node) adj[node] = neighbors return adj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __get_all_lowpoints(dfs_data): """Calculates the lowpoints for each node in a graph."""
lowpoint_1_lookup = {} lowpoint_2_lookup = {} ordering = dfs_data['ordering'] for node in ordering: low_1, low_2 = __get_lowpoints(node, dfs_data) lowpoint_1_lookup[node] = low_1 lowpoint_2_lookup[node] = low_2 return lowpoint_1_lookup, lowpoint_2_lookup
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __get_lowpoints(node, dfs_data): """Calculates the lowpoints for a single node in a graph."""
ordering_lookup = dfs_data['ordering_lookup'] t_u = T(node, dfs_data) sorted_t_u = sorted(t_u, key=lambda a: ordering_lookup[a]) lowpoint_1 = sorted_t_u[0] lowpoint_2 = sorted_t_u[1] return lowpoint_1, lowpoint_2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __edge_weight(edge_id, dfs_data): """Calculates the edge weight used to sort edges."""
graph = dfs_data['graph'] edge_lookup = dfs_data['edge_lookup'] edge = graph.get_edge(edge_id) u, v = edge['vertices'] d_u = D(u, dfs_data) d_v = D(v, dfs_data) lp_1 = L1(v, dfs_data) d_lp_1 = D(lp_1, dfs_data) if edge_lookup[edge_id] == 'backedge' and d_v < d_u: return 2*...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_type_I_branch(u, v, dfs_data): """Determines whether a branch uv is a type I branch."""
if u != a(v, dfs_data): return False if u == L2(v, dfs_data): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_type_II_branch(u, v, dfs_data): """Determines whether a branch uv is a type II branch."""
if u != a(v, dfs_data): return False if u < L2(v, dfs_data): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __get_descendants(node, dfs_data): """Gets the descendants of a node."""
list_of_descendants = [] stack = deque() children_lookup = dfs_data['children_lookup'] current_node = node children = children_lookup[current_node] dfs_current_node = D(current_node, dfs_data) for n in children: dfs_child = D(n, dfs_data) # Validate that the child node is...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def S_star(u, dfs_data): """The set of all descendants of u, with u added."""
s_u = S(u, dfs_data) if u not in s_u: s_u.append(u) return s_u
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def classify_segmented_recording(recording, result_format=None): """Use this function if you are sure you have a single symbol. Parameters recording : string The...
global single_symbol_classifier if single_symbol_classifier is None: single_symbol_classifier = SingleClassificer() return single_symbol_classifier.predict(recording, result_format)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict(self, recording, result_format=None): """Predict the class of the given recording. Parameters recording : string Recording of a single handwritten da...
evaluate = utils.evaluate_model_single_recording_preloaded results = evaluate(self.preprocessing_queue, self.feature_list, self.model, self.output_semantics, recording) if result_format =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_symbol_ids(symbol_yml_file, metadata): """ Get a list of ids which describe which class they get mapped to. Parameters symbol_yml_file : string Path to a...
with open(symbol_yml_file, 'r') as stream: symbol_cfg = yaml.load(stream) symbol_ids = [] symbol_ids_set = set() for symbol in symbol_cfg: if 'latex' not in symbol: logging.error("Key 'latex' not found for a symbol in %s (%s)", symbol_yml_file, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_csv(filepath): """ Read a CSV into a list of dictionarys. The first line of the CSV determines the keys of the dictionary. Parameters filepath : string ...
symbols = [] with open(filepath, 'rb') as csvfile: spamreader = csv.DictReader(csvfile, delimiter=',', quotechar='"') for row in spamreader: symbols.append(row) return symbols
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_raw(raw_pickle_file): """ Load a pickle file of raw recordings. Parameters raw_pickle_file : str Path to a pickle file which contains raw recordings. Re...
with open(raw_pickle_file, 'rb') as f: raw = pickle.load(f) logging.info("Loaded %i recordings.", len(raw['handwriting_datasets'])) return raw
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_metrics(metrics_description): """Get metrics from a list of dictionaries. """
return utils.get_objectlist(metrics_description, config_key='data_analyzation_plugins', module=sys.modules[__name__])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_file(filename): """Truncate the file and return the filename."""
directory = os.path.join(utils.get_project_root(), "analyzation/") if not os.path.exists(directory): os.makedirs(directory) workfilename = os.path.join(directory, filename) open(workfilename, 'w').close() # Truncate the file return workfilename
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_by_formula_id(raw_datasets): """ Sort a list of formulas by `id`, where `id` represents the accepted formula id. Parameters raw_datasets : list of dicti...
by_formula_id = defaultdict(list) for el in raw_datasets: by_formula_id[el['handwriting'].formula_id].append(el['handwriting']) return by_formula_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_data(self, symbols, err_recs, nr_recordings, total_error_count, percentages, time_max_list): """Write all obtained data to a file. Parameters symbols ...
write_file = open(self.filename, "a") s = "" for symbol, count in sorted(symbols.items(), key=lambda n: n[0]): if symbol in ['a', '0', 'A']: s += "\n%s (%i), " % (symbol, count) elif symbol in ['z', '9', 'Z']: s += "%s (%i) \n" % (symbol, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_featurelist(feature_list): """ Print the feature_list in a human-readable form. Parameters feature_list : list feature objects """
input_features = sum(map(lambda n: n.get_dimension(), feature_list)) print("## Features (%i)" % input_features) print("```") for algorithm in feature_list: print("* %s" % str(algorithm)) print("```")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _stroke_simplification(self, pointlist): """The Douglas-Peucker line simplification takes a list of points as an argument. It tries to simplifiy this list by...
# Find the point with the biggest distance dmax = 0 index = 0 for i in range(1, len(pointlist)): d = geometry.perpendicular_distance(pointlist[i], pointlist[0], pointlist[-1]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_preprocessing_queue(preprocessing_list): """Get preprocessing queue from a list of dictionaries {'ScaleAndShift': [{'center': True}]} ] [RemoveDuplicateT...
return utils.get_objectlist(preprocessing_list, config_key='preprocessing', module=sys.modules[__name__])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_preprocessing_list(preprocessing_queue): """ Print the ``preproc_list`` in a human-readable form. Parameters preprocessing_queue : list of preprocessin...
print("## Preprocessing") print("```") for algorithm in preprocessing_queue: print("* " + str(algorithm)) print("```")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_parameters(self, hwr_obj): """ Take a list of points and calculate the factors for scaling and moving it so that it's in the unit square. Keept the aspe...
a = hwr_obj.get_bounding_box() width = a['maxx'] - a['minx'] + self.width_add height = a['maxy'] - a['miny'] + self.height_add factor_x, factor_y = 1, 1 if width != 0: factor_x = self.max_width / width if height != 0: factor_y = self.max_height...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calculate_pen_down_strokes(self, pointlist, times=None): """Calculate the intervall borders 'times' that contain the information when a stroke started, when...
if times is None: times = [] for stroke in pointlist: stroke_info = {"start": stroke[0]['time'], "end": stroke[-1]['time'], "pen_down": True} # set up variables for interpolation x, y, t = [], [], [] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calculate_pen_up_strokes(self, pointlist, times=None): """ 'Pen-up' strokes are virtual strokes that were not drawn. It models the time when the user moved ...
if times is None: times = [] for i in range(len(pointlist) - 1): stroke_info = {"start": pointlist[i][-1]['time'], "end": pointlist[i + 1][0]['time'], "pen_down": False} x, y, t = [], [], [] for point ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _space(self, hwr_obj, stroke, kind): """Do the interpolation of 'kind' for 'stroke'"""
new_stroke = [] stroke = sorted(stroke, key=lambda p: p['time']) x, y, t = [], [], [] for point in stroke: x.append(point['x']) y.append(point['y']) t.append(point['time']) x, y = numpy.array(x), numpy.array(y) failed = False ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calculate_average(self, points): """Calculate the arithmetic mean of the points x and y coordinates seperately. """
assert len(self.theta) == len(points), \ "points has length %i, but should have length %i" % \ (len(points), len(self.theta)) new_point = {'x': 0, 'y': 0, 'time': 0} for key in new_point: new_point[key] = self.theta[0] * points[0][key] + \ sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_model(model_folder, model_type, topology, override): """ Create a model if it doesn't exist already. Parameters model_folder : The path to the folder ...
latest_model = utils.get_latest_in_folder(model_folder, ".json") if (latest_model == "") or override: logging.info("Create a base model...") model_src = os.path.join(model_folder, "model-0.json") command = "%s make %s %s > %s" % (utils.get_nntoolkit(), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(model_folder, override=False): """Parse the info.yml from ``model_folder`` and create the model file."""
model_description_file = os.path.join(model_folder, "info.yml") # Read the model description file with open(model_description_file, 'r') as ymlfile: model_description = yaml.load(ymlfile) project_root = utils.get_project_root() # Read the feature description file feature_folder = os.pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interactive(): """Interactive classifier."""
global n if request.method == 'GET' and request.args.get('heartbeat', '') != "": return request.args.get('heartbeat', '') if request.method == 'POST': logging.warning('POST to /interactive is deprecated. ' 'Use /worker instead') else: # Page where the use...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_part(pointlist, strokes): """Get some strokes of pointlist Parameters pointlist : list of lists of dicts strokes : list of integers Returns ------- list...
result = [] strokes = sorted(strokes) for stroke_index in strokes: result.append(pointlist[stroke_index]) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_translate(): """ Get a dictionary which translates from a neural network output to semantics. """
translate = {} model_path = pkg_resources.resource_filename('hwrt', 'misc/') translation_csv = os.path.join(model_path, 'latex2writemathindex.csv') arguments = {'newline': '', 'encoding': 'utf8'} with open(translation_csv, 'rt', **arguments) as csvfile: contents = csvfile.read() lines =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(port=8000, n_output=10, use_segmenter=False): """Main function starting the webserver."""
global n global use_segmenter_flag n = n_output use_segmenter_flag = use_segmenter logging.info("Start webserver...") app.run(port=port)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_training_command(model_folder): """Generate a string that contains a command with all necessary parameters to train the model."""
update_if_outdated(model_folder) model_description_file = os.path.join(model_folder, "info.yml") # Read the model description file with open(model_description_file, 'r') as ymlfile: model_description = yaml.load(ymlfile) # Get the data paths (hdf5 files) project_root = utils.get_projec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def train_model(model_folder): """Train the model in ``model_folder``."""
os.chdir(model_folder) training = generate_training_command(model_folder) if training is None: return -1 logging.info(training) os.chdir(model_folder) os.system(training)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(model_folder): """Main part of the training script."""
model_description_file = os.path.join(model_folder, "info.yml") # Read the model description file with open(model_description_file, 'r') as ymlfile: model_description = yaml.load(ymlfile) # Analyze model logging.info(model_description['model']) data = {} data['training'] = os.path...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_bounding_box(points): """Get the bounding box of a list of points. Parameters points : list of points Returns ------- BoundingBox """
assert len(points) > 0, "At least one point has to be given." min_x, max_x = points[0]['x'], points[0]['x'] min_y, max_y = points[0]['y'], points[0]['y'] for point in points: min_x, max_x = min(min_x, point['x']), max(max_x, point['x']) min_y, max_y = min(min_y, point['y']), max(max_y, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_bb_intersect(a, b): """Check if BoundingBox a intersects with BoundingBox b."""
return a.p1.x <= b.p2.x \ and a.p2.x >= b.p1.x \ and a.p1.y <= b.p2.y \ and a.p2.y >= b.p1.y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def segments_distance(segment1, segment2): """Calculate the distance between two line segments in the plane. '1.41' '0.00' '0.00' """
assert isinstance(segment1, LineSegment), \ "segment1 is not a LineSegment, but a %s" % type(segment1) assert isinstance(segment2, LineSegment), \ "segment2 is not a LineSegment, but a %s" % type(segment2) if len(get_segments_intersections(segment1, segment2)) >= 1: return 0 # t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def perpendicular_distance(p3, p1, p2): """ Calculate the distance from p3 to the stroke defined by p1 and p2. The distance is the length of the perpendicular fr...
px = p2['x']-p1['x'] py = p2['y']-p1['y'] squared_distance = px*px + py*py if squared_distance == 0: # The line is in fact only a single dot. # In this case the distance of two points has to be # calculated line_point = Point(p1['x'], p1['y']) point = Point(p3['...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dist_to(self, p2): """Measure the distance to another point."""
return math.hypot(self.x - p2.x, self.y - p2.y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_slope(self): """Return the slope m of this line segment."""
# y1 = m*x1 + t # y2 = m*x2 + t => y1-y2 = m*(x1-x2) <=> m = (y1-y2)/(x1-x2) return ((self.p1.y-self.p2.y) / (self.p1.x-self.p2.x))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_offset(self): """Get the offset t of this line segment."""
return self.p1.y-self.get_slope()*self.p1.x
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count_selfintersections(self): """ Get the number of self-intersections of this polygonal chain."""
# This can be solved more efficiently with sweep line counter = 0 for i, j in itertools.combinations(range(len(self.lineSegments)), 2): inters = get_segments_intersections(self.lineSegments[i], self.lineSegments[j]) if abs(...