def test_compare(self): obj1 = Node("foo") obj2 = Node("foo") obj3 = Node("bar") obj4 = Node("bar") obj4.addAttribute(BoolAttribute("testAttr", True)) self.assertEqual(obj1, obj2) self.assertNotEqual(obj1, obj3) self.assertNotEqual(obj3, obj4)
def draw_outer_walls(self, color): assert type(color) == int assert 0 <= color < 64 for i in range(self.grid.width): self.draw_bottom_wall(Node(i, 0), color) self.draw_top_wall(Node(i, self.grid.height - 1), color) for i in range(self.grid.height): self.draw_left_wall(Node(0, i), color) self.draw_right_wall(Node(self.grid.width - 1, i), color)
def adduseropts(user): ret = [] field = Node("upload.type_image", "metafield") field.set("label", "image_schema") field.set("type", "text") ret.append(field) field = Node("upload.type_text", "metafield") field.set("label", "text_schema") field.set("type", "text") ret.append(field) db.session.commit() return ret
def test_parse_find_node_response(): nodes = [Node(addr='localhost', port=i, nodeid=ID(i)) for i in range(5)] find_node_response = msg.FindNodeResponse(b'', nodes[0:]).finalize(nodes[0]) parsed_nodes = msg.Message.parse_protobuf(find_node_response) assert parsed_nodes.nodes == nodes[0:]
def create_nodes_from_list(node_list, edges_list=()): """Given a list tuples (name, coords, destinations, links, generate the Nodes and edges Parameters ---------- node_list: list edges_list: list Returns ------- dict """ nodes = {} count = 0 for node_tuple in node_list: node = Node(node_tuple[0], destinations=node_tuple[2], coords=node_tuple[1]) nodes[node.name] = node count += 1 connection_dict = dict( zip([i[0] for i in node_list], [i[3] for i in node_list])) for name, node in nodes.items(): connections = connection_dict[name] for conn_name in connections: node.connect_to(nodes[conn_name], xy=get_edge_xy(node.name, conn_name, edges_list)) return nodes
def generateMask(node): mask = getMask(node) maintype = getMainContentType(node) if not maintype: return # clean up for field in mask.children: mask.children.remove(field) #todo this also needs to be fixed allfields_parent = maintype allfields = maintype.metafields.all() allfieldnames = [mf.name for mf in allfields] for metafield in maintype.getMetaFields("s"): d = metafield.get("label") if not d: d = metafield.getName() new_maskitem = Node(d, type="searchmaskitem") mask.children.append(new_maskitem) if metafield.get("type") == "union": for t in metafield.get("valuelist").split(";"): if t and t in allfieldnames: new_maskitem.children.append( allfields_parent.children.filter_by(name=t).one()) else: new_maskitem.children.append(metafield) db.session.commit() return mask
def test_serialize(self): obj1 = Node("foo") obj1.addAttribute(BoolAttribute("testAttr", True)) obj1.addAttribute(StringAttribute("foo", "bar")) json1 = obj1.serialize() obj2 = Node.deserialize(json1) for attribute in obj1.attributes: self.assertEqual(obj1[attribute], obj2[attribute]) self.assertEqual(obj1, obj2)
def fill_holes(self, visited, color): assert type(color) == int assert 0 <= color < 64 for i in range(self.grid.width): for j in range(self.grid.height): node = Node(i, j) if node not in visited: self.fill(node, color)
def newMask(node): searchmask_root = q(Searchmasks).one() while True: maskname = unicode(hashlib.md5(ustr(random.random())).hexdigest()[0:8]) if maskname in searchmask_root.children.all(): continue else: break mask = Node(name=maskname, type=u"searchmask") searchmask_root.children.append(mask) node.set("searchmaskname", maskname) return mask
def main(): """ create a window, add scene objects, then run rendering loop """ viewer = Viewer() shader = Shader("phong.vert", "phong.frag") node = Node(transform=rotate((0, 0, 1), 45)) viewer.add(node) light_dir = (0, -1, 0) node.add(*[ mesh for file in sys.argv[1:] for mesh in load_phong_mesh(file, shader, light_dir) ]) if len(sys.argv) != 2: print('Usage:\n\t%s [3dfile]*\n\n3dfile\t\t the filename of a model in' ' format supported by assimp.' % (sys.argv[0], )) # start rendering loop viewer.run()
def main(): """ create a window, add scene objects, then run rendering loop """ viewer = Viewer() # default color shader shader = Shader("color.vert", "color.frag") # think about it: we can re-use the same cylinder instance! cylinder = Cylinder(shader) # make a flat cylinder base_shape = Node(transform=scale(1, 0.7, 1)) base_shape.add(cylinder) # shape of robot base # make a thin cylinder arm_shape = Node(transform=translate(0, 3, 0) @ scale(0.1, 2.4, 0.1)) arm_shape.add(cylinder) # shape of arm # make a thin cylinder forearm_shape = Node(transform=translate(0, 7, 0) @ scale(0.1, 1.8, 0.1)) forearm_shape.add(cylinder) # shape of forearm theta = 45.0 # base horizontal rotation angle phi1 = 45.0 # arm angle phi2 = 20.0 # forearm angle transform_forearm = Node(transform=rotate((0.6, 0.5, 1), phi2)) transform_forearm.add(forearm_shape) transform_arm = Node(transform=rotate((0.3, 0.1, 0.9), phi1)) transform_arm.add(arm_shape, transform_forearm) transform_base = Node(transform=rotate((0.9, 0.1, 0.2), theta)) transform_base.add(base_shape, transform_arm) viewer.add(transform_base) # place instances of our basic objects # viewer.add(*[mesh for file in sys.argv[1:] for mesh in load(file, shader)]) # if len(sys.argv) < 2: # print('Usage:\n\t%s [3dfile]*\n\n3dfile\t\t the filename of a model in' # ' format supported by assimp.' % (sys.argv[0],)) # start rendering loop viewer.run()
from core import Blockchain, Node from flask import Flask, jsonify, request api = Flask(__name__) blockchain = Blockchain() node = Node() @api.route('/register', methods=['GET']) def register(): node = request.form.get('node') if node is None: return 'Requires `node`', 400 # TO-DO: blockchain.register(node) res = {'message': 'Added node'} return jsonify(res) @api.route('/chain', methods=['GET']) def chain(): chain = [b.serialize() for b in blockchain.chain] res = {'blockchain': chain, 'length': len(blockchain.chain)} return jsonify(res) @api.route('/mine', methods=['GET']) def mine(): prev_block = blockchain.peek() proof = blockchain.mine(prev_block.key)
def __init__(self, fi, verbose=True): self.root = None self.nodes = [] self.attributename = None self.id2node = {} self.verbose = verbose self.node_already_seen = False handler = HandlerTarget() handler.start = lambda name, attrs: self.xml_start_element(name, attrs) handler.end = lambda name: self.xml_end_element(name) handler.data = lambda d: self.xml_char_data(d) parser = etree.XMLParser(target=handler) if type(fi) in [unicode, str]: xml = fi elif type(fi) in [file]: xml = fi.read() fi.close() else: raise NotImplementedError() try: result = etree.XML(xml, parser) except Exception as e: logg.exception("\tfile not well-formed. %s", e) return mappings = q(Mappings).scalar() if mappings is None: mappings = q(Root).one().children.append( Node(name="mappings", type="mappings")) logg.info("no mappings root found: added mappings root") for node in self.nodes: if node.type == "mapping": if node.name not in [ n.name for n in mappings.children if n.type == "mapping" ]: mappings.children.append(node) if self.verbose: logg.info( "xml import: added mapping id=%s, type='%s', name='%s'", node.id, node.type, node.name) if self.verbose: logg.info("linking children to parents") for node in self.nodes: d = {} for id in node.tmpchilds: child = self.id2node[id] node.children.append(child) d[child.id] = child if self.verbose and node.tmpchilds: added = [(cid, d[cid].type, d[cid].name) for cid in d.keys()] logg.info( "added %d children to node id='%s', type='%s', name='%s': %s", len(node.tmpchilds), node.id, node.type, node.name, added) for node in self.nodes: if node.type == "maskitem": attr = node.get("attribute") if attr and attr in self.id2node: attr_new = self.id2node[attr].id node.set("attribute", attr_new) if self.verbose: logg.info( "adjusting node attribute for maskitem '%s', name='attribute', value: old='%s' -> new='%s'", node.id, attr, attr_new) mappingfield = node.get("mappingfield") if mappingfield and mappingfield in self.id2node: mappingfield_new = self.id2node[mappingfield].id node.set("mappingfield", ustr(mappingfield_new)) if self.verbose: logg.info( "adjusting node attribute for maskitem '%s', name='mappingfield', value old='%s' -> new='%s'", node.id, mappingfield, mappingfield_new) elif node.type == "mask": exportmapping = node.get("exportmapping") if exportmapping and exportmapping in self.id2node: exportmapping_new = self.id2node[exportmapping].id node.set("exportmapping", ustr(exportmapping_new)) if self.verbose: logg.info( "adjusting node attribute for mask '%s', name='exportmapping':, value old='%s' -> new='%s'", node.id, exportmapping, exportmapping_new) logg.info("xml import done") db.session.commit()
def test_parsing(): node = Node('localhost', 3000, ID(10)) message = msg.FindNode(ID(10)).finalize(node) parsed = msg.Message.parse_protobuf(message) assert parsed.key == ID(10)
# deliver schemes for given contenttype if req.params.get('action') == 'getschemes': ret = [] for scheme in get_permitted_schemas_for_datatype( req.params.get('contenttype')): ret.append({'id': scheme.name, 'name': scheme.getLongName()}) req.write(json.dumps({'schemes': ret}, ensure_ascii=False)) return None # create node with given type/schema if req.params.get('action') == "createobject": schema = req.params.get('schema') ctype = req.params.get('contenttype') node = Node(name=u"", type=ctype, schema=schema) basenode = q(Node).get(req.params.get('id')) basenode.children.append(node) node.set("creator", user.login_name) node.set( "creationtime", ustr( time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(time.time())))) db.session.commit() res = {'newid': node.id, 'id': req.params.get('id')} req.write(json.dumps(res, ensure_ascii=False)) return None # create node using given identifier (doi, ...) if req.params.get('action') == "obj_from_identifier":
def test_session(session): """Tests if the session rolls back correctly and leaves no traces. Assert is in the fixture.""" from core import Node session.add(Node(u"name"))
def test_session_rollback(session): """Tests if the session fixture works even after a rollback and commit...""" from core import Node session.add(Node(u"name")) session.rollback() session.commit()
def test_session_commit2(session): """Tests if the session rolls back correctly and leaves no traces, even after two commits...""" from core import Node session.add(Node(u"name")) session.commit() session.commit()
from core import Node def change_parameter(master: Node, node_name: str, param_name: str, new_value: str): """ Change a parameter in the parameter server :param master: A node object for the ROS master node :param node_name: The name to give the node to request information :param param_name: The name of the parameter you want to change :param new_value: The new value of the parameter :return: """ master.server.setParam(node_name, param_name, new_value) if __name__ == "__main__": target_master = Node(ip_addr='localhost', port="11311", notes="Master Node") new_value = "pwnd" node_name = "/rosploit" (_, _, param_list) = Node.server.getParamNames(node_name) for param_name in param_list: change_parameter(target_master, node_name, param_name, new_value)
def add_object(object, transform=identity()): obj = Node(transform=transform) obj.add(object) return obj
def getContent(req, ids): user = current_user node = q(Node).get(ids[0]) if not node.has_write_access( ) or "searchmask" in user.hidden_edit_functions: req.setStatus(httpstatus.HTTP_FORBIDDEN) return req.getTAL("web/edit/edit.html", {}, macro="access_error") p2 = {} for k, v in req.params.items(): if k.endswith(".x") or k.endswith(".y"): p2[k[:-2]] = v else: p2[k] = v req.params = p2 openfield = None delfield = None delsubfield = None for k, v in req.params.items(): if k.startswith("open_"): openfield = k[5:] if k.startswith("del_"): delfield = k[4:] if k.startswith("delsub_"): delsubfield = k[7:] searchtype = req.params.get("searchtype", None) if not searchtype: searchtype = node.get("searchtype") if not searchtype: searchtype = "none" # if a parent has a search mask, use 'inherit' n = node while len(n.parents): n = n.parents[0] if n.get("searchtype") == "own": searchtype = "parent" node.set("searchtype", searchtype) schema = req.params.get("schema", None) schemafield = req.params.get("schemafield", None) selectedfieldid = req.params.get("selectedfield", None) if schema: if schema.endswith(";"): schema = schema[:-1] schema = q(Node).get(schema) if not isinstance(schema, Node): schema = None if schemafield: if schemafield.endswith(";"): schemafield = schemafield[:-1] schemafield = q(Node).get(schemafield) if not isinstance(schemafield, Node): schemafield = None if schema and schemafield and schemafield not in schema.children: schemafield = None if schemafield and schemafield.type != "metafield": schemafield = None fields = None selectedfield = None isnewfield = False createsub = False closefield = False if searchtype == "own": maskname = node.get("searchmaskname") mask = q(Searchmasks).one().children.filter_by(name=maskname).scalar() if not maskname or mask is None: mask = searchmask.generateMask(node) if selectedfieldid: # edit selectedfield = q(Node).get(selectedfieldid) assert selectedfield in mask.children selectedfield.name = req.params["fieldname"] if "createsub" in req.params and schemafield: createsub = True selectedfield.children.append(schemafield) if delsubfield: selectedfield.children.remove(q(Node).get(delsubfield)) if req.params.get("isnewfield", "") == "yes": # create a new field isnewfield = True l = mask.children.count() mask.children.append(Node("Suchfeld %s" % l, "searchmaskitem")) elif delfield: # del a field delfield = q(Node).get(delfield) assert delfield in mask.children mask.children.remove(delfield) elif openfield: # unfold a new field selectedfieldid = openfield elif "close" in req.params: # fold a field closefield = True selectedfieldid = None if selectedfieldid: selectedfield = q(Node).get(selectedfieldid) if selectedfield not in mask.children: # this usually happens if the field was just deleted selectedfield = None else: selectedfield = None fields = mask.children.all() db.session.commit() data = { "idstr": ",".join(ids), "node": node, "searchtype": searchtype, "schemas": q(Metadatatypes).one().children.sort_by_name().all(), "searchfields": fields, "selectedfield": selectedfield, "newfieldlink": "edit_content?id=%s&tab=searchmask" % node.id, "defaultschemaid": None, "defaultfieldid": None, "id": req.params.get("id") } if schema: data["defaultschemaid"] = schema.id if schemafield: data["defaultfieldid"] = schemafield.id data["schema"] = schema def display(schemafield): if not schemafield or schemafield.type != 'metafield': return 0 if not schemafield.Searchfield(): return 0 if schemafield.get('type') == 'union': return 0 return 1 data["display"] = display searchtypechanged = False if req.params.get("searchtypechanged", "") == "true": searchtypechanged = True if any([ openfield, isnewfield, delfield, delsubfield, createsub, schema, searchtypechanged, closefield ]): content = req.getTAL("web/edit/modules/searchmask.html", data, macro="edit_search") s = json.dumps({'content': content}, ensure_ascii=False) req.write(s) return None return req.getTAL("web/edit/modules/searchmask.html", data, macro="edit_search")
'Try --colors to see all the available colors.') else: color = random.choice(list(Colors)) # Prevent method 2 with start_at if args.method == 2 and args.start_at is not None: parser.error('Method 2 can\'t be used with --start-at') # Prevents too high of a tolerance (that would result in an empty map) if args.method == 1 and (1.0 - args.tolerance) * args.width * args.height < 1: parser.error('Tolerance is too high. An empty map would be generated.') # Configure start position if args.start_at is None: start_options = { 'bottom_left': Node(0, 0), 'bottom_right': Node(args.width - 1, 0), 'top_left': Node(0, args.height - 1), 'top_right': Node(args.width - 1, args.height - 1), } start_position = start_options[args.start] else: x, y = args.start_at[0], args.start_at[1] if not 0 <= x < args.width or not 0 <= y < args.height: parser.error('Start position values for X and Y must be within ' 'boundaries: 0 <= X < WIDTH and 0 <= Y < HEIGHT') start_position = Node(x, y) # Configure random seed if args.seed is None: seed = random.randrange(sys.maxsize)
''' start.py This is the starting point for the pibs_client. To run: $ pip install -r requirements.txt (1st time only) $ python start.py - Scott Null, 08/23/18 ''' from definitions import * # update the package map from tools import updateDirInit updateDirInit('./sensors', iterative=True) updateDirInit('./tasks', iterative=True) from core import Node import json with open(LOCAL_CONFIG_FILE, 'rb') as f: sys_json = f.read() system_dict = json.loads(sys_json) node = Node(system=system_dict) node.loop_start()