Пример #1
0
    ## write json file
    data_line = "{" + nodes + "," + links + "}"
    output_file = open("data.json", "w")
    output_file.write(data_line)
    output_file.close()


##------------##
## TEST SPACE ##
##------------##

grid = network.Network("test", 3)

node_list = []

a = node.Node("tardis", 5)
b = node.Node("picvert", 4)
c = node.Node("choucroute", 6)
d = node.Node("falcon", 1)
e = node.Node("machine", 2)
f = node.Node("cheesecake", 9)

node_list.append(a)
node_list.append(b)
node_list.append(c)
node_list.append(d)
node_list.append(e)
node_list.append(f)

truc = generate_random_nodes(20)
machin = order_nodes(truc, 4)
Пример #2
0
    def _readNodes(self):
        self.nodelist = {}
        config = ConfigParser.SafeConfigParser()
        if not config.read(self.nodecfg):
            util.error("cannot read '%s'" % self.nodecfg)

        manager = False
        proxy = False
        worker = False
        standalone = False

        file = self.nodecfg

        counts = {}
        for sec in config.sections():
            node = node_mod.Node(sec)
            self.nodelist[sec] = node

            for (key, val) in config.items(sec):

                key = key.replace(".", "_")

                if not key in node_mod.Node._keys:
                    util.warn("%s: unknown key '%s' in section '%s'" %
                              (file, key, sec))
                    continue

                if key == "type":
                    if val == "manager":
                        if manager:
                            util.error("only one manager can be defined")
                        manager = True

                    elif val == "proxy":
                        proxy = True

                    elif val == "worker":
                        worker = True

                    elif val == "standalone":
                        standalone = True

                    else:
                        util.error("%s: unknown type '%s' in section '%s'" %
                                   (file, val, sec))

                node.__dict__[key] = val

            try:
                addrinfo = socket.getaddrinfo(node.host, None, 0, 0,
                                              socket.SOL_TCP)
                if len(addrinfo) == 0:
                    util.error(
                        "%s: no addresses resolved in section '%s' for host %s"
                        % (file, sec, node.host))

                addr_str = addrinfo[0][4][0]
                # zone_id is handled manually, so strip it if it's there
                node.addr = addr_str.split('%')[0]
            except AttributeError:
                util.error("%s: no host given in section '%s'" % (file, sec))
            except socket.gaierror, e:
                util.error("%s: unknown host '%s' in section '%s' [%s]" %
                           (file, node.host, sec, e.args[1]))

            # Each node gets a number unique across its type.
            type = self.nodelist[sec].type
            try:
                counts[type] += 1
            except KeyError:
                counts[type] = 1

            node.count = counts[type]

            if node.lb_procs:
                try:
                    numprocs = int(node.lb_procs)
                    if numprocs < 1:
                        util.error(
                            "%s: value of lb_procs must be at least 1 in section '%s'"
                            % (file, sec))
                except ValueError:
                    util.error(
                        "%s: value of lb_procs must be an integer in section '%s'"
                        % (file, sec))

                if not node.lb_method:
                    util.error(
                        "%s: no load balancing method given in section '%s'" %
                        (file, sec))

                if node.lb_method not in ("pf_ring", "myricom", "interfaces"):
                    util.error(
                        "%s: unknown load balancing method given in section '%s'"
                        % (file, sec))

                if node.lb_method == "interfaces":
                    if not node.lb_interfaces:
                        util.error(
                            "%s: no list of interfaces given in section '%s'" %
                            (file, sec))

                    # get list of interfaces to use, and assign one to each node
                    netifs = node.lb_interfaces.split(",")

                    if len(netifs) != int(node.lb_procs):
                        util.error(
                            "%s: number of interfaces does not match value of lb_procs in section '%s'"
                            % (file, sec))

                    node.interface = netifs.pop().strip()

                # node names will have a numerical suffix
                node.name = "%s-1" % sec

                for num in xrange(2, int(node.lb_procs) + 1):
                    newnode = copy.deepcopy(node)
                    # only the node name and count need to be changed
                    newname = "%s-%d" % (sec, num)
                    newnode.name = newname
                    self.nodelist[newname] = newnode
                    counts[type] += 1
                    newnode.count = counts[type]

                    if newnode.lb_method == "interfaces":
                        newnode.interface = netifs.pop().strip()
Пример #3
0
 def __init__(self):
     self.head = node.Node()
     self.length = 0
Пример #4
0
def rrt(start_coords, goal_coords, radius, clearance):

    x_start, y_start = start_coords
    x_goal, y_goal = goal_coords

    start_node = node.Node(current_coords=start_coords,
                           parent_coords=None,
                           distance=None)
    goal_node = node.Node(current_coords=goal_coords,
                          parent_coords=None,
                          distance=None)

    print(start_node.printNode())
    print(goal_node.printNode())

    tree = []
    path = []

    # tree.append(start_node)
    tree.append([0, start_node.current_coords, (0, 0)])

    N = 0
    while (N < MAX_ITER):
        print("N:", N)
        x_random = (np.random.uniform(X_LIM[0], X_LIM[1]),
                    np.random.uniform(Y_LIM[0], Y_LIM[1]))
        # print("x_random", x_random)
        ##########################################
        #put a check if x_random is repeated
        ##########################################
        # print("<<<<<<<<<<<<Before updating the distance<<<<")
        # print("tree", tree)

        # print("<<<<<<<<<<<<After updating the distance<<<<<")
        for i in tree:
            # while True:
            distance = utils.euclideanDistance(point_1=i[1], point_2=x_random)
            i[0] = distance
            # print("tree", i)

        heapq.heapify(tree)

        # Finding the node in the tree which is the nearest to the x_random
        min_node = heapq.heappop(tree)

        # print("len(tree)", len(tree))
        heapq.heappush(tree, [min_node[0], min_node[1], min_node[2]])
        # sys.exit(0)

        # print("min node", min_node)
        # print("next_node", next_node)
        # print("distance", distance)
        # path.append(add_node)
        # tree.append([min_node[0], x_random, min_node[1]])
        # print("<<<<<<<<<<<After apending the latest x random<<<<<")
        # print("tree", tree)

        # if the random node is within the step size
        if min_node[0] <= STEP_SIZE:

            # create a node with this value and add it to the path
            obstacle_status = obstacles.withinObstacleSpace(
                point=min_node[1], radius=radius, clearance=clearance)
            if (obstacle_status == False):
                add_node = node.Node(current_coords=x_random,
                                     parent_coords=min_node[1],
                                     distance=min_node[0])
                path.append(add_node)
                # print("<<<<<<<<<<<<<_before<<<<<<<<<,")
                # print("len(tree)", len(tree))
                heapq.heappush(tree, [
                    add_node.distance, add_node.current_coords,
                    add_node.parent_coords
                ])
                # print("<<<<<<<<<<<<after<<<<<<<<<<,")
                # print("len(tree)", len(tree))
                # tree.append([add_node.distance, add_node.current_coords, add_node.parent_coords])

        else:
            # Find an intermediate point in between a and b
            x1, y1 = min_node[1]
            x2, y2 = x_random

            slope = (y2 - y1) / (x2 - x1)
            theta = math.atan(slope)

            x_near = (x1 + (STEP_SIZE * math.cos(theta)),
                      y1 + (STEP_SIZE * math.sin(theta)))

            obstacle_status = obstacles.withinObstacleSpace(
                point=min_node[1], radius=radius, clearance=clearance)
            if (obstacle_status == False):
                add_node = node.Node(current_coords=x_near,
                                     parent_coords=min_node[1],
                                     distance=STEP_SIZE)
                # print("<<<<<<<<<<<<<_before<<<<<<<<<,")
                # print("len(tree)", len(tree))
                path.append(add_node)
                heapq.heappush(tree, [
                    add_node.distance, add_node.current_coords,
                    add_node.parent_coords
                ])
                # print("<<<<<<<<<<<<<_before<<<<<<<<<,")
                # print("len(tree)", len(tree))

                # tree.append([add_node.distance, add_node.current_coords, add_node.parent_coords])

        goal_status = utils.goal_reached(
            current_node=add_node,
            goal_node=goal_node,
            goal_reach_threshold=GOAL_REACH_THRESH)
        if (goal_status):
            print("Reached Goal!")
            return path, goal_node
            # break

        N += 1
        # print("-------------------")
        # print(path)
    return path, goal_node
Пример #5
0
    c.configPath = args.c or "/etc/fail2ban-p2p"
    c.privkey = os.path.join(c.configPath, 'private.pem')
    c.pubkey = os.path.join(c.configPath, 'public.pem')

    if c.loadConfig() == False:
        raise OSError  #, 'Config error, check log.'

    logger = log.initialize_logging("fail2ban-p2p")

    if args.K:
        crypto.create_keys()
        exit()
    # make sure the keys exist
    if not os.path.isfile(c.privkey) or not os.path.isfile(c.pubkey):
        logger.warning('Private or public key not found, creating them')
        crypto.create_keys()

    n = None
    try:
        n = node.Node()
        n.loadConfig()
        n.getFriends()
        n.requestBanlist()
        n.cleanBanlist()
        n.openSocket()
    except (KeyboardInterrupt):
        logger.info("Keyboard Interrupt received, going down")
        n.cleanBanlistStop()
        n.closeSocket()
        logger.info("kthxbai!")
Пример #6
0
def solve8PuzzleProblem(input_data_matrix):
    input_data = node.Node(data_matrix=input_data_matrix,
                           current_idx=0,
                           parent_idx=-1)

    if not input_data.isSolvable():
        print(
            "Sorry but this configuration is not solvable! Try some other configuration."
        )
        sys.exit(0)

    is_visited = []

    Q = []
    Q.append(input_data)
    Q_idx = 0
    curr_idx = 1

    while (Q_idx < len(Q)):
        is_visited.append(input_data)

        if Q[Q_idx].reachedGoalState():
            utils.printSolutionPath(Q, Q_idx)
            utils.writeNodeIdxInformation(node_list=Q,
                                          node_info_filename="./NodesInfo.txt")
            utils.writeNodeStates(node_list=Q,
                                  node_state_filename="./Nodes.txt")
            return (utils.getSolutionPath(Q, Q_idx))

        new_state = actions.actionMoveLeft(Q[Q_idx])
        if (new_state is not None) and (new_state not in is_visited):
            new_state.current_idx = curr_idx
            curr_idx += 1
            new_state.parent_idx = Q_idx
            Q.append(new_state)

        new_state = actions.actionMoveRight(Q[Q_idx])
        if (new_state is not None) and (new_state not in is_visited):
            new_state.current_idx = curr_idx
            curr_idx += 1
            new_state.parent_idx = Q_idx
            Q.append(new_state)

        new_state = actions.actionMoveUp(Q[Q_idx])
        if (new_state is not None) and (new_state not in is_visited):
            new_state.current_idx = curr_idx
            curr_idx += 1
            new_state.parent_idx = Q_idx
            Q.append(new_state)

        new_state = actions.actionMoveDown(Q[Q_idx])
        if (new_state is not None) and (new_state not in is_visited):
            new_state.current_idx = curr_idx
            curr_idx += 1
            new_state.parent_idx = Q_idx
            Q.append(new_state)

        Q_idx += 1

    print(
        "I am really sorry but I could not find a solution. This is weird because as per my logic the solution exists."
    )
    return None
Пример #7
0
_STRUCTURE = 0

# 0 -> black
# 1 -> white
# 2 -> blue
# 3 -> green
# 4 -> red
_COLOR = WHITE


###############################################
##
##  Geometric Types - INIT
#####################################################
#Nodes Example
nodeA_ForLine = node.Node(5, 5)
nodeB_ForLine = node.Node(10, 10)

#Dots Example
_nodes = list()

#Lines example
_lines = list()

#Circle Example
_circles = list()

#Polygon Example
_polygons = list()

#Polyline Example
Пример #8
0
import sys
import tree_reader2
import tree_utils
import node

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print "python " + sys.argv[0] + " infile.trees outfile.tre"
        sys.exit(0)

    trees = []
    maintree = node.Node()
    for i in tree_reader2.read_tree_file_iter(sys.argv[1]):
        trees.append(i)

    lvsnms = set()
    for i in trees:
        for l in i.lvsnms():
            lvsnms.add(l)

    for i in lvsnms:
        nd = node.Node()
        nd.label = i
        maintree.add_child(nd)

    for i in trees:
        mr = tree_utils.get_mrca_wnms(i.lvsnms(), maintree)
        mvnds = set()
        for j in mr.children:
            if len(set(j.lvsnms()).intersection(set(i.lvsnms()))) > 0:
                mvnds.add(j)
        x_lon = np.zeros((len(shape.points), 1))
        y_lat = np.zeros((len(shape.points), 1))
        for ip in range(len(shape.points)):
            x_lon[ip] = shape.points[ip][0]
            y_lat[ip] = shape.points[ip][1]

x_min = x_lon.min()
x_max = x_lon.max()
y_min = y_lat.min()
y_max = y_lat.max()

bitmap = []
row = []
x_range = np.arange(x_min, x_max, 0.0001)
y_range = np.arange(y_min, y_max, 0.0001)
for i in range(0, len(x_range)):
    row.clear()
    for j in range(0, len(y_range)):
        point = None
        if polygon.contains(Point(x_range[i], y_range[j])):
            plt.scatter(x_range[i], y_range[j], s=.5, c='b')
            point = node.Node(x_range[i], y_range[j], True)
        else:
            plt.scatter(x_range[i], y_range[j], s=.5, c='r')
            point = node.Node(x_range[i], y_range[j], False)
        row.append(point)
    bitmap.append(row)
plt.show()

data = np.array(bitmap)
print(data.shape)
# @app.route('/forceminetrigger', methods = ['GET'])
# def force_mine():
#     force_result = _node.force_mine()
#     if force_result == 0:
#         return jsonify(status="did something")
#     else:
#         return jsonify(status="all work done")


@app.route('/chain', methods=['GET'])
def chain_send():
    chain = _node.chain
    return jsonify(chain=chain)


if __name__ == '__main__':
    from argparse import ArgumentParser
    parser = ArgumentParser()
    parser.add_argument('-p', default=5000, help='port to listen on')
    parser.add_argument('-diff', default=4, help='set difficulty of POW')
    parser.add_argument('-ip', help='ip to listen on')
    parser.add_argument('-bip', help='bootstrap ip, -1 if bootstrap')
    parser.add_argument('-bport', help='bootstrap port, -1 if bootstrap')
    args = parser.parse_args()
    config.difficulty = int(args.diff)
    port = args.p
    _node = node.Node(args.ip, args.p, args.bip, args.bport)

    app.run(host='0.0.0.0', port=port, threaded=True)
Пример #11
0
    def __init__(self, num_i_elem, num_j_elem, p, mesh_properties):
        """Constructor for the Quadrilateral Mesh
		
		Will generate a quadrilateral mesh (rectangular) of certain order
		elements. The mesh will initially be "structured" however it will
		be stored in memory as an unstructured mesh. Then, we will work
		with the unstructured mesh to do all solving and adaptation.
		
		Args:
		    num_i_elem (int): Number of elements to initialize along the i direction
		    num_j_elem (int): Number of elements to initialize along the j direction
		    p (int): The order of the basis functions
		    mesh_properties (dict): Dictionary holding the following parameters
		    	"x_range": List with the lower and upper x limits of the mesh (for rectangular case)
		    	"y_range": List with the lower and upper y limits of the mesh (for rectangular case)
		    	"dirichlet_bc_flag": The function for setting the dirichlet bc
		"""

        # ===========================
        #            Setup
        # ===========================

        # x and y limits of the rectangular mesh
        self.x_range = mesh_properties.get("x_range")
        self.y_range = mesh_properties.get("y_range")

        # Order of the mesh
        self.p = p

        # Generate the initial mesh by creating equal dimension elements on a
        # num_i_elem x num_j_elem grid.

        # Spacing of the elements
        dx_elem, dy_elem =  float(self.x_range[1] - self.x_range[0])/num_i_elem, \
             float(self.y_range[1] - self.y_range[0])/num_j_elem

        # ===========================
        #      Vertices Generation
        # ===========================

        # Generate the grid of vertex points
        vertex_points_grid = []

        for i in range(num_i_elem + 1):
            col = []
            for j in range(num_j_elem + 1):

                x_pt, y_pt = i * dx_elem, j * dy_elem
                vertex_pt = vertex.Vertex(x_pt, y_pt)

                col.append(vertex_pt)

            vertex_points_grid.append(col)

        # ===========================
        #   Element/DOF Generation
        # ===========================

        # As we are initially creating a structured mesh, exploit this fact
        # to be able to quickly determine the connectivity between the elements
        element_matrix = []

        for i in range(num_i_elem):
            col = []
            for j in range(num_j_elem):

                # Get the range of the element on the physical domain
                elem_x_range = [
                    i * dx_elem + self.x_range[0],
                    (i + 1) * dx_elem + self.x_range[0]
                ]
                elem_y_range = [
                    j * dy_elem + self.y_range[0],
                    (j + 1) * dy_elem + self.y_range[0]
                ]

                # The matrix of points for the vertices for this element
                vertex_pt_matrix = [[None, None], [None, None]]
                for i_vertex in range(2):
                    for j_vertex in range(2):
                        vertex_pt_matrix[i_vertex][
                            j_vertex] = vertex_points_grid[i +
                                                           i_vertex][j +
                                                                     j_vertex]

                # Create the element with these vertices
                col.append(
                    quad_finite_element.QuadFiniteElement(
                        self.p, elem_x_range, elem_y_range, vertex_pt_matrix,
                        0))

            element_matrix.append(col)

        # Set the neigbors of the elements
        for i in range(num_i_elem):
            for j in range(num_j_elem):

                elem_ij = element_matrix[i][j]

                if i == 0:
                    elem_ij.set_neighbor([element_matrix[i + 1][j]], 1, [3])
                elif i == num_i_elem - 1:
                    elem_ij.set_neighbor([element_matrix[i - 1][j]], 3, [1])
                else:
                    elem_ij.set_neighbor([element_matrix[i + 1][j]], 1, [3])
                    elem_ij.set_neighbor([element_matrix[i - 1][j]], 3, [1])

                if j == 0:
                    elem_ij.set_neighbor([element_matrix[i][j + 1]], 2, [0])
                elif j == num_j_elem - 1:
                    elem_ij.set_neighbor([element_matrix[i][j - 1]], 0, [2])
                else:
                    elem_ij.set_neighbor([element_matrix[i][j + 1]], 2, [0])
                    elem_ij.set_neighbor([element_matrix[i][j - 1]], 0, [2])

        # Now, with all the neighbors set, we place all the elements in a list
        self.element_list = []
        for i in range(num_i_elem):
            for j in range(num_j_elem):
                self.element_list.append(element_matrix[i][j])

        # Set the dofs for the elements. Exploit the structured data for now to
        # create the shared dofs
        node_points_grid = []
        for i in range(num_i_elem + 1):
            col = []

            for j in range(num_j_elem + 1):
                x_pt, y_pt = i * dx_elem, j * dy_elem
                node_pt = node.Node("dof", x_pt, y_pt)
                col.append(node_pt)

            node_points_grid.append(col)

        for i in range(num_i_elem):
            for j in range(num_j_elem):

                elem_ij = element_matrix[i][j]

                i_dof_min = i
                j_dof_min = j

                for i_node_elem in range(2):
                    for j_node_elem in range(2):

                        elem_ij.node_matrix[i_node_elem][j_node_elem] = \
                         node_points_grid[i_dof_min + i_node_elem][j_dof_min + j_node_elem]

        self.set_node_to_element_connectivity()

        # Summary:
        # - At this point in the mesh generation, we now have a list of
        # 	elements. This list makes it such that we can effectively handle
        # 	an unstructured mesh of elements.
        # - All nodes have been generated

        # ===========================
        #      Dirichlet BC Setup
        # ===========================

        # Set the Dirichlet BC on the mesh and its nodes
        self.dirichlet_bc_flag_function = mesh_properties["dirichlet_bc_flag"]
        self.set_dirichlet_boundary_condition()

        # ===========================
        #      Global DOF List
        # ===========================

        # Set the list of dofs for this mesh. This will be used for the system solve
        self.dof_list = []
        self.set_dof_list()

        self.dirichlet_bc_list = []
        self.set_dirichlet_bc_list()

        # Set the list of hanging nodes for this mesh. Will be needed during h-refinement
        self.hanging_node_list = []
        self.set_hanging_node_list()
Пример #12
0
 def create_server_node(server_node_ip_enum):
     return node.Node(server_node_ip_enum)
Пример #13
0
 def criarServidor():
     self.master.intr.no = node.Node("", int(self.porta.get()))
     self.master.intr.no.servidor(self.master.intr)
Пример #14
0
    def a_star(self, heuristic):
        start_node = node.Node(self.position[0],
                               self.position[1],
                               None,
                               heuristic,
                               "START",
                               g=1,
                               direction='north')  # creates start node

        options_per_node = ["FORWARD", "LEFT", "RIGHT",
                            "BASHING"]  # choices per node
        VISITED = list()
        OPEN = list()
        OPEN.append(start_node)
        while len(OPEN) > 0:
            # print(len(OPEN))
            curr = min(OPEN, key=lambda x: x.f)  # get lowest f-score
            # print(f"{curr} : {curr.parent}")
            if self.board.get_cost(
                    curr.row, curr.col
            ) == -1:  # check if goal reached. if reached print path
                len_of_path = -1
                # print("GOAL REACHED\n\n\n")
                goal_info = self._get_path(curr)
                path = goal_info[0]
                actions = goal_info[1]
                nodes_expanded = 0
                score = 0
                for step in path[::-1]:
                    len_of_path += 1
                    nodes_expanded = len(VISITED)
                    score = 100 - (curr.f + 1)
                    # print(step)
                return score, len_of_path, nodes_expanded, actions
            OPEN.remove(curr)
            VISITED.append(curr)
            for option in options_per_node:
                # print(f"{option} from {curr.row}, {curr.col}")
                if option == "FORWARD":
                    forward = self._move(curr_pos=[curr.row, curr.col],
                                         curr_dir=curr.direction)
                    new_pos = forward[0]
                    cost_of_move = forward[1]
                    if cost_of_move == 0:
                        continue
                    new_heuristic = self.calc_heuristic(heuristic, new_pos)
                    curr.add_edge(
                        node.Node(new_pos[0],
                                  new_pos[1],
                                  curr,
                                  new_heuristic,
                                  "FORWARD",
                                  g=curr.g + cost_of_move,
                                  direction=curr.direction))
                    continue
                elif option == "LEFT":
                    if curr.how_we_got_here == "BASH" or curr.how_we_got_here == "RIGHT":
                        continue
                    left = self._turn([curr.row, curr.col], "LEFT",
                                      curr.direction)
                    if left:
                        new_pos = left[0]
                        cost_of_move = left[1]
                        new_heuristic = self.calc_heuristic(heuristic, new_pos)
                        curr.add_edge(
                            node.Node(new_pos[0],
                                      new_pos[1],
                                      curr,
                                      new_heuristic,
                                      "LEFT",
                                      g=curr.g + cost_of_move,
                                      direction=left[2]))
                        continue
                elif option == "RIGHT":
                    if curr.how_we_got_here == "BASH" or curr.how_we_got_here == "LEFT":
                        continue
                    right = self._turn([curr.row, curr.col], "RIGHT",
                                       curr.direction)
                    if right:
                        new_pos = right[0]
                        cost_of_move = right[1]
                        new_heuristic = self.calc_heuristic(heuristic, new_pos)
                        curr.add_edge(
                            node.Node(new_pos[0],
                                      new_pos[1],
                                      curr,
                                      new_heuristic,
                                      "RIGHT",
                                      g=curr.g + cost_of_move,
                                      direction=right[2]))
                        continue
                elif option == "BASHING":
                    if curr.how_we_got_here == "BASH":
                        continue
                    bash = self._bash(curr_pos=[curr.row, curr.col],
                                      curr_dir=curr.direction)
                    new_pos = bash[0]
                    cost_of_move = bash[1]
                    if cost_of_move == 0:
                        continue
                    new_heuristic = self.calc_heuristic(heuristic, new_pos)
                    curr.add_edge(
                        node.Node(new_pos[0],
                                  new_pos[1],
                                  curr,
                                  new_heuristic,
                                  "BASH",
                                  g=curr.g + cost_of_move,
                                  direction=curr.direction))
                    continue
            for e in curr.edges:
                if (e not in VISITED and e not in OPEN) or e.f > curr.f:
                    OPEN.append(e)
Пример #15
0
def GenerateNode(filepath, nodeID = 0):
    # Create a new node
    Node = node.Node(id = nodeID)
    try:
        # Parse file and extract dictionary of EDS entry
        eds_dict = ParseEDSFile(filepath)
        # Extract Profile Number from Device Type entry
        ProfileNb = eds_dict[0x1000].get("DEFAULTVALUE", 0) & 0x0000ffff
        # If profile is not DS-301 or DS-302
        if ProfileNb not in [0, 301, 302]:
            # Compile Profile name and path to .prf file
            ProfileName = "DS-%d"%ProfileNb
            ProfilePath = os.path.join(os.path.split(__file__)[0], "config/%s.prf"%ProfileName)
            # Verify that profile is available
            if os.path.isfile(ProfilePath):
                try:
                    # Load Profile
                    execfile(ProfilePath)
                    Node.SetProfileName(ProfileName)
                    Node.SetProfile(Mapping)
                    Node.SetSpecificMenu(AddMenuEntries)
                except:
                    pass
        # Read all entries in the EDS dictionary 
        for entry, values in eds_dict.iteritems():
            # All sections with a name in keynames are escaped
            if entry in SECTION_KEYNAMES:
                pass
            else:
                # Extract informations for the entry
                entry_infos = Node.GetEntryInfos(entry)
                
                # If no informations are available, then we write them
                if not entry_infos:
                    # First case, entry is a DOMAIN or VAR
                    if values["OBJECTTYPE"] in [2, 7]:
                        if values["OBJECTTYPE"] == 2:
                            values["DATATYPE"] = values.get("DATATYPE", 0xF)
                            if values["DATATYPE"] != 0xF:
                                raise SyntaxError, _("Domain entry 0x%4.4X DataType must be 0xF(DOMAIN) if defined")%entry
                        # Add mapping for entry
                        Node.AddMappingEntry(entry, name = values["PARAMETERNAME"], struct = 1)
                        # Add mapping for first subindex
                        Node.AddMappingEntry(entry, 0, values = {"name" : values["PARAMETERNAME"], 
                                                                 "type" : values["DATATYPE"], 
                                                                 "access" : ACCESS_TRANSLATE[values["ACCESSTYPE"].upper()], 
                                                                 "pdo" : values.get("PDOMAPPING", 0) == 1})
                    # Second case, entry is an ARRAY or RECORD
                    elif values["OBJECTTYPE"] in [8, 9]:
                        # Extract maximum subindex number defined
                        max_subindex = max(values["subindexes"].keys())
                        # Add mapping for entry
                        Node.AddMappingEntry(entry, name = values["PARAMETERNAME"], struct = 3)
                        # Add mapping for first subindex
                        Node.AddMappingEntry(entry, 0, values = {"name" : "Number of Entries", "type" : 0x05, "access" : "ro", "pdo" : False})
                        # Add mapping for other subindexes
                        for subindex in xrange(1, int(max_subindex) + 1):
                            # if subindex is defined
                            if subindex in values["subindexes"]:
                                Node.AddMappingEntry(entry, subindex, values = {"name" : values["subindexes"][subindex]["PARAMETERNAME"], 
                                                                                "type" : values["subindexes"][subindex]["DATATYPE"], 
                                                                                "access" : ACCESS_TRANSLATE[values["subindexes"][subindex]["ACCESSTYPE"].upper()], 
                                                                                "pdo" : values["subindexes"][subindex].get("PDOMAPPING", 0) == 1})
                            # if not, we add a mapping for compatibility 
                            else:
                                Node.AddMappingEntry(entry, subindex, values = {"name" : "Compatibility Entry", "type" : 0x05, "access" : "rw", "pdo" : False})
##                    # Third case, entry is an RECORD
##                    elif values["OBJECTTYPE"] == 9:
##                        # Verify that the first subindex is defined
##                        if 0 not in values["subindexes"]:
##                            raise SyntaxError, "Error on entry 0x%4.4X:\nSubindex 0 must be defined for a RECORD entry"%entry
##                        # Add mapping for entry
##                        Node.AddMappingEntry(entry, name = values["PARAMETERNAME"], struct = 7)
##                        # Add mapping for first subindex
##                        Node.AddMappingEntry(entry, 0, values = {"name" : "Number of Entries", "type" : 0x05, "access" : "ro", "pdo" : False})
##                        # Verify that second subindex is defined
##                        if 1 in values["subindexes"]:
##                            Node.AddMappingEntry(entry, 1, values = {"name" : values["PARAMETERNAME"] + " %d[(sub)]", 
##                                                                     "type" : values["subindexes"][1]["DATATYPE"], 
##                                                                     "access" : ACCESS_TRANSLATE[values["subindexes"][1]["ACCESSTYPE"].upper()], 
##                                                                     "pdo" : values["subindexes"][1].get("PDOMAPPING", 0) == 1,
##                                                                     "nbmax" : 0xFE})
##                        else:
##                            raise SyntaxError, "Error on entry 0x%4.4X:\nA RECORD entry must have at least 2 subindexes"%entry
                
                # Define entry for the new node
                
                # First case, entry is a DOMAIN or VAR
                if values["OBJECTTYPE"] in [2, 7]:
                    # Take default value if it is defined
                    if "PARAMETERVALUE" in values:
                        value = values["PARAMETERVALUE"]
                    elif "DEFAULTVALUE" in values:
                        value = values["DEFAULTVALUE"]
                    # Find default value for value type of the entry
                    else:
                        value = GetDefaultValue(Node, entry)
                    Node.AddEntry(entry, 0, value)
                # Second case, entry is an ARRAY or a RECORD
                elif values["OBJECTTYPE"] in [8, 9]:
                    # Verify that "Subnumber" attribute is defined and has a valid value
                    if "SUBNUMBER" in values and values["SUBNUMBER"] > 0:
                        # Extract maximum subindex number defined
                        max_subindex = max(values["subindexes"].keys())
                        Node.AddEntry(entry, value = [])
                        # Define value for all subindexes except the first 
                        for subindex in xrange(1, int(max_subindex) + 1):
                            # Take default value if it is defined and entry is defined
                            if subindex in values["subindexes"] and "PARAMETERVALUE" in values["subindexes"][subindex]:
                                value = values["subindexes"][subindex]["PARAMETERVALUE"]
                            elif subindex in values["subindexes"] and "DEFAULTVALUE" in values["subindexes"][subindex]:
                                value = values["subindexes"][subindex]["DEFAULTVALUE"]
                            # Find default value for value type of the subindex
                            else:
                                value = GetDefaultValue(Node, entry, subindex)
                            Node.AddEntry(entry, subindex, value)
                    else:
                        raise SyntaxError, _("Array or Record entry 0x%4.4X must have a \"SubNumber\" attribute")%entry
        return Node
    except SyntaxError, message:
        return _("Unable to import EDS file\n%s")%message
Пример #16
0
 def get_node(self,name):
     if name not in self.nodes:
         self.nodes[name] = node.Node(name)
     return self.nodes[name]
Пример #17
0
def sew_it2(ML_val, branches, bip_hash, test, gene_count_hash):

    maintree = node.Node()
    names = []

    #get the names
    names = tree_stuff.get_tips(bip_hash.itervalues().next())
    lvs = set(names)

    trees = []
    trees_r = []
    temp = []
    temp_r = []

    #put trees into an array
    for i in branches:

        if test == "2_con" or test == "2_con_gene" or test == "con_b":
            nd = node.Node()
            nd = tree_stuff.build(bip_hash[i])
            temp, temp_r = get_left(nd, lvs)
        else:
            nd = node.Node()
            nd = tree_stuff.build(bip_hash[branches[i]])
            temp, temp_r = get_left(nd, lvs)

        if test == "tree_dist":
            diffval = ML_val - float(i)
        elif test == "constraint_label":
            diffval = branches[i]
        elif test == "2_con" or test == "2_con_gene" or test == "con_b":
            diffval = branches[i]
        elif test == "blank":
            diffval = ""
        elif test == "conflict":
            diffval = gene_count_hash[branches[i]]
        temp = "(" + ",".join(temp) + ")" + str(diffval) + ";"
        temp_r = "(" + ",".join(temp_r) + ")" + str(diffval) + ";"
        x = tree_stuff.build(temp)
        trees.append(x)
        x = tree_stuff.build(temp_r)
        trees_r.append(x)

    #print trees
    #print trees_r

    #get the tip names as an tree structures
    lvsnms = set()
    for i in trees:
        #print i
        for l in i.lvsnms():

            lvsnms.add(l)
    for i in trees_r:

        for l in i.lvsnms():

            lvsnms.add(l)

    #Create a star tree with all tips being tree structures
    for i in lvsnms:

        nd = node.Node()
        nd.label = i
        maintree.add_child(nd)

    for i in range(0, len(trees)):

        ilvs = trees[i].lvsnms()
        bp1 = tree_stuff.get_mrca_wnms(trees[i].lvsnms(), maintree)
        bp2 = tree_stuff.get_mrca_wnms(trees_r[i].lvsnms(), maintree)

        if bp1 == maintree and bp2 != maintree:
            bp = bp2
            ilvs = trees_r[i].lvsnms()
            #bp.label = trees_r[i].label
        else:
            bp = bp1
            #bp.label = trees[i].label
        mvnds = set()
        for j in bp.children:

            if len(set(j.lvsnms()).intersection(set(ilvs))) > 0:
                mvnds.add(j)

        nd = node.Node()

        lab = trees_r[i].label
        for j in mvnds:
            #print "Here is j:" + str(j)
            bp.remove_child(j)
            nd.add_child(j)
        if nd.label == "":
            nd.label = lab
        bp.add_child(nd)

    print maintree.get_newick_repr(False) + ";"
Пример #18
0
import node

print(node.Node('../samples/Physics.cfg').variables)
print()
print(node.Node('../samples/mvp.craft').variables)
Пример #19
0
    def test_basics(self):
        empty_b = Bucket(MAX_RNODES)

        # Get empty superbucket
        log_distance = self.my_node.log_distance(tc.SERVER_NODE)
        sbucket = self.rt.get_sbucket(log_distance)
        m_bucket = sbucket.main
        r_bucket = sbucket.replacement
        eq_(m_bucket, empty_b)
        eq_(r_bucket, empty_b)
        ok_(r_bucket.there_is_room())
        eq_(m_bucket.get_rnode(tc.SERVER_NODE), None)
        ok_(m_bucket.there_is_room(MAX_RNODES))
        ok_(not m_bucket.there_is_room(MAX_RNODES + 1))
        eq_(self.rt.num_rnodes, 0)  # empty
        eq_(self.rt.get_main_rnodes(), [])

        # Add server_node to main bucket
        m_bucket.add(tc.SERVER_NODE)
        self.rt.update_lowest_index(log_distance)
        self.rt.num_rnodes += 1
        ok_(m_bucket.there_is_room())
        ok_(not m_bucket.there_is_room(MAX_RNODES))
        eq_(m_bucket.rnodes, [tc.SERVER_NODE])
        eq_(m_bucket.get_rnode(tc.SERVER_NODE), tc.SERVER_NODE)

        # Check updated table
        eq_(self.rt.num_rnodes, 1)
        eq_(self.rt.get_main_rnodes(), [tc.SERVER_NODE])
        sbucket = self.rt.get_sbucket(log_distance)
        m_bucket = sbucket.main
        r_bucket = sbucket.replacement

        # Let's add a node to the same bucket
        new_node = node.Node(tc.SERVER_NODE.addr,
                             tc.SERVER_NODE.id.generate_close_id(1))
        m_bucket.add(new_node)
        self.rt.update_lowest_index(log_distance)
        self.rt.num_rnodes += 1
        # full bucket
        ok_(not m_bucket.there_is_room())
        eq_(m_bucket.rnodes, [tc.SERVER_NODE, new_node])
        eq_(m_bucket.get_rnode(new_node), new_node)
        # Trying to add to the bucket will raise exception
        assert_raises(AssertionError, sbucket.main.add, tc.NODES[0])
        eq_(self.rt.num_rnodes, 2)
        eq_(self.rt.get_main_rnodes(), [tc.SERVER_NODE, new_node])

        ld_to_server = tc.SERVER_ID.log_distance(tc.CLIENT_ID)
        eq_(self.rt.get_closest_rnodes(ld_to_server, 1, True),
            [tc.SERVER_NODE])
        eq_(self.rt.get_closest_rnodes(ld_to_server, 8, False),
            [tc.SERVER_NODE, new_node, tc.CLIENT_NODE])
        eq_(self.rt.get_closest_rnodes(ld_to_server, 8, False),
            [tc.SERVER_NODE, new_node, tc.CLIENT_NODE])
        eq_(self.rt.get_closest_rnodes(ld_to_server, 8, True),
            [tc.SERVER_NODE, new_node])

        sbucket = self.rt.get_sbucket(log_distance)
        m_bucket = sbucket.main

        m_bucket.remove(new_node)
        self.rt.update_lowest_index(log_distance)
        print '>>>'
        print self.rt.get_main_rnodes()
        print '>>>'
        self.rt.num_rnodes -= 1
        # there is one slot in the bucket
        ok_(m_bucket.there_is_room())
        ok_(m_bucket.get_rnode(new_node) is None)
        eq_(m_bucket.rnodes, [tc.SERVER_NODE])
        eq_(m_bucket.get_rnode(tc.SERVER_NODE), tc.SERVER_NODE)

        eq_(self.rt.num_rnodes, 1)
        eq_(self.rt.get_main_rnodes(), [tc.SERVER_NODE])

        eq_(self.rt.get_closest_rnodes(ld_to_server, 8, True),
            [tc.SERVER_NODE])
def a_star(start_rc,
           goal_rc,
           orientation,
           rpm1=10,
           rpm2=20,
           clearance=0.2,
           viz_please=False):
    """
	A-star algorithm given the start and the goal nodes.

	:param      start_rc:     The start position
	:type       start_rc:     tuple
	:param      goal_rc:      The goal position
	:type       goal_rc:      tuple
	:param      orientation:  The orientation
	:type       orientation:  number
	:param      rpm1:         The rpm 1
	:type       rpm1:         number
	:param      rpm2:         The rpm 2
	:type       rpm2:         number
	:param      clearance:    The clearance
	:type       clearance:    number
	:param      viz_please:   Whether to visualize or not
	:type       viz_please:   boolean

	:returns:   Returns path nodes and the list of visited nodes.
	:rtype:     tuple
	"""
    """
	Inputs
	"""
    start_node = node.Node(current_coords=start_rc,
                           parent_coords=None,
                           orientation=0,
                           parent_orientation=None,
                           action=None,
                           movement_cost=0,
                           goal_cost=utils.euclideanDistance(
                               start_rc, goal_rc))
    print("-----------------------")
    print("Start Node:")
    start_node.printNode()
    print("-----------------------")
    goal_node = node.Node(current_coords=goal_rc,
                          parent_coords=None,
                          orientation=None,
                          parent_orientation=None,
                          action=None,
                          movement_cost=None,
                          goal_cost=0)
    """
	Initializations
	"""
    action_set = [(0, rpm1), (rpm1, 0), (0, rpm2), (rpm2, 0), (rpm1, rpm2),
                  (rpm2, rpm1), (rpm1, rpm1), (rpm2, rpm2)]

    min_heap = [((start_node.movement_cost + start_node.goal_cost), start_node)
                ]
    heapq.heapify(min_heap)

    visited = {}
    visited.update({
        (utils.getKey(start_rc[0], start_rc[1], start_node.orientation)):
        start_node
    })

    visited_viz_nodes = [start_node]
    """
	Initialize the plot figures if the visualization flag is true.
	Also mark the start and the goal nodes.
	"""
    if viz_please:
        fig, ax = plt.subplots()
        ax.set(xlim=(an.MIN_COORDS[0], an.MAX_COORDS[0]),
               ylim=(an.MIN_COORDS[1], an.MAX_COORDS[1]))
        # ax.set(xlim=(-5, 5), ylim=(-5, 5))
        ax.set_aspect('equal')

        obstacles.generateMap(plotter=ax)

        viz.markNode(start_node, plotter=ax, color='#00FF00', marker='o')
        viz.markNode(goal_node, plotter=ax, color='#FF0000', marker='^')

        plt.ion()
    """
	Run the loop for A-star algorithm till the min_heap queue contains no nodes.
	"""
    while (len(min_heap) > 0):
        _, curr_node = heapq.heappop(min_heap)

        # Consider all the action moves for all the selected nodes.
        for action in action_set:
            new_node = an.actionMove(current_node=curr_node,
                                     next_action=action,
                                     goal_position=goal_rc,
                                     clearance=clearance)

            # Check if all the nodes are valid or not.
            if (new_node is not None):
                """
				Check if the current node is a goal node.
				"""
                if new_node.goal_cost < GOAL_REACH_THRESH:
                    print("Reached Goal!")
                    print("Final Node:")
                    new_node.printNode()
                    visited_viz_nodes.append(new_node)

                    path = an.backtrack(new_node, visited)
                    print("------------------------")
                    if viz_please:
                        viz.plot_curve(new_node, plotter=ax, color="red")
                        viz.plotPath(path,
                                     rev=True,
                                     pause_time=0.5,
                                     plotter=ax,
                                     color="lime",
                                     linewidth=4)

                        plt.ioff()
                        plt.show()
                    return (path, visited_viz_nodes)
                """
				Mark node as visited,
				Append to min_heap queue,
				Update if already visited.
				"""
                node_key = (utils.getKey(new_node.current_coords[0],
                                         new_node.current_coords[1],
                                         new_node.orientation))

                if node_key in visited:
                    if new_node < visited[node_key]:
                        visited[node_key] = new_node
                        min_heap.append(
                            ((new_node.movement_cost + new_node.goal_cost),
                             new_node))

                else:
                    if viz_please:
                        viz.plot_curve(new_node, plotter=ax, color="red")
                        plt.show()
                        plt.pause(0.001)

                    visited.update({node_key: new_node})
                    min_heap.append(
                        ((new_node.movement_cost + new_node.goal_cost),
                         new_node))

                    visited_viz_nodes.append(new_node)

        # Heapify the min heap to update the minimum node in the list.
        heapq.heapify(min_heap)
Пример #21
0
def extractInfo():
    with open('app//app.info', "r") as fp:
        contents = fp.readlines()
        for content in contents:
            [a, b] = content.rstrip('\n').split(':')
            nd.Node()
Пример #22
0
 def setUp(self):
     self.nodes = {}
     for i in range(1, 4):
         self.nodes[i] = node.Node(i)
Пример #23
0
def print_dict(data):
    for index, values in data.items():
        print(f'    --{hex(index)}')
        if type(values) == list:
            for val in values:
                print(f'      > {val}')
        else:
            print(f'      > {values}')


parser = argparse.ArgumentParser(description='Print object')
parser.add_argument('-f', '--file', action='store', dest='file')

args = parser.parse_args()

node = node.Node()

node.load_from_file(args.file)

print(f'OD File for {node.Name}')
print(f'  Type:          {node.Type}')
print(f'  ID:            {node.ID}')
print(f'  Description:   {node.Description}')
print(f'  Profile Name:  {node.ProfileName}')
print(f'  Profile:       {node.Profile}')
print(f'  Dictionary:')

print_dict(node.Dictionary)

print(f'  ParamsDictionary:')
Пример #24
0
 def __init__(self, rootval):
     if rootval == None:
         self.root = None
     else:
         self.root = node.Node(rootval)
     self.traversecount = 0
Пример #25
0
        current_node.add_transaction_to_block(transaction)
        return "Transaction OK" , 200
    else:
        return "Transaction is Not Valid", 400
        
 
@app.route('/node/sendChain', methods=['GET'])
def Chain():
    return {'chain': jsonpickle.encode(current_node.chain.blockchain)}

    
@app.route('/chain/print', methods=['GET'])
def print_blockchain():    
    current_node.chain.print_chain()
    return jsonify({}),200
        
if __name__ == '__main__':
    from argparse import ArgumentParser

    parser = ArgumentParser()
    parser.add_argument('-p', '--port' ,type=int, help='port to listen on')
    parser.add_argument('-ip', '--ipaddress' ,type=str, help='port to listen on')
    parser.add_argument('-cap', '--capacity' ,type=int, help='the capacity of the block')
    parser.add_argument('-diff', '--difficulty' ,type=int, help='the block difficulty, number of "0" the hash starts with')
    args = parser.parse_args()
    port = args.port
    ip = args.ipaddress
    block_capacity = args.capacity
    block_difficulty = args.difficulty
    current_node = node.Node(ip,port,5000,'127.0.0.1',block_capacity, block_difficulty)
    app.run(host = '127.0.0.1', port = port)
Пример #26
0
 def test_rootIsNodeOnly(self):
     root = node.Node(1)
     self.assertEqual(1, node.lowestCommonAncestor(root, 1, 1))
Пример #27
0
 def addToFront(self, val):
     n = node.Node()
     n.sett(val)
     n.next = self.head.next
     self.head.next = n
Пример #28
0
# Print network graph
def printNetwork():
    plt.figure(1)
    nx.draw_networkx_nodes(graph, pos)
    nx.draw_networkx_labels(graph, pos, labels)
    nx.draw_networkx_edges(graph,
                           pos,
                           arrows=True,
                           connectionstyle='arc3,rad=0.2')
    plt.show()


# Generate nodes with id appropriate to their position
for row in range(1, rows + 1):
    for column in range(1, columns + 1):
        node_list.append(node.Node("{}:{}".format(row, column), buffer_size))

# Generate adequate horizontal links with alternating directions
for row in range(1, rows + 1):
    for column in range(1, columns):
        if row % 2 == 1:
            link_list.append(
                link.Link(uuid.uuid1(),
                          getNode(row, column).id,
                          getNode(row, column + 1).id))
        else:
            link_list.append(
                link.Link(uuid.uuid1(),
                          getNode(row, column + 1).id,
                          getNode(row, column).id))
    if row % 2 == 1:
Пример #29
0
    arguments = p.parse_args(sys.argv[1:])

    nickname = arguments.nickname
    lost = arguments.lost
    port = arguments.port
    if lost < 0 or lost > 100:
        print("Значение процента потерь должно быть от 0 до 100!!!")
        exit(1)
    if len(nickname) > 20:
        print("Никнейм должен быть не длиннее 20 символов")
        exit(1)

    parent_address = None
    parent_port = None
    if arguments.parent_address or arguments.parent_port:
        parent_address = arguments.parent_address
        parent_port = arguments.parent_port
        ROOT = False
        if not (parent_address or parent_port):
            print(
                "Если передавать адрес родителя, то нужно передавать и адрес, и порт,"
                " либо вообще ничего не передавать!!!")
            exit(1)

    print(nickname, lost, port, parent_address, parent_port)

    if ROOT:
        node = node.Node(nickname, port, lost)
    else:
        node = node.Node(nickname, port, lost, (parent_address, parent_port))
Пример #30
0
            y_lat[ip] = shape.points[ip][1]
        #plt.plot(x_lon, y_lat)

x_min, y_min, x_max, y_max = polygon.bounds

bitmap = []
row = []
x_range = np.arange(x_min, x_max, 0.0001)
y_range = np.arange(y_min, y_max, 0.0001)
for j in range(0, len(y_range)):
    row = []
    for i in range(0, len(x_range)):
        point = None
        if polygon.contains(Point(x_range[i], y_range[j])):
            plt.scatter(x_range[i], y_range[j], s=.5, c='blue')
            point = node.Node(x_range[i], y_range[j], "In")
        else:
            plt.scatter(x_range[i], y_range[j], s=.5, c='yellow')
            point = node.Node(x_range[i], y_range[j], "Out")
        row.append(point)
    bitmap.append(row)

shape = np.array(bitmap).shape

# for x in range(0, shape[0]):
#     for y in range(0, shape[1]):
#         if bitmap[x][y].get_state() == "Out":
#             try:
#                 if bitmap[x+1][y].get_state() == "In":
#                     if (bitmap[x+1][y-1].get_state() == "In" and bitmap[x][y-1].get_state() == "In") or (bitmap[x+1][y+1].get_state() == "In" and bitmap[x][y+1].get_state() == "In"):
#                         bitmap[x][y].set_state("Partial")