Beispiel #1
0
def create_root():
    myRoot = Node(storeCat(request.args.get("name")))
    roots.append(myRoot)
    print "There were " + str(len(Tree.query().fetch(None))) + " entries."
    Tree(tree=str(myRoot.convertTree())).put()
    print "Now there are " + str(len(Tree.query().fetch(None))) + " entries."
    return get_tree()
    def test_crud_node(self):
        """ It tests the basic CRUD operations of an Node class """

        # We verify the object is not in the db after creating it
        node = Node()
        node.name = "node1"
        node.information_retrieved = True
        self.assertIsNone(node.id)

        # We store the object in the db
        db.session.add(node)

        # We recover the node from the db
        node = db.session.query(Node).filter_by(name='node1').first()
        self.assertIsNotNone(node.id)
        self.assertEquals("node1", node.name)
        self.assertTrue(node.information_retrieved)

        # We update the node
        node.information_retrieved = False
        db.session.commit()
        node = db.session.query(Node).filter_by(name='node1').first()
        self.assertFalse(node.information_retrieved)

        # We check the deletion
        db.session.delete(node)
        count = db.session.query(Node).filter_by(name='node1').count()
        self.assertEquals(0, count)
Beispiel #3
0
 def post(self, urlname):
     node = Node.get(urlname=urlname)
     if not node:
         return self.redirect_next_url()
     user = self.current_user
     kwargs = self.request.arguments
     try:
         selected = kwargs.get('parent_name')
         print(selected)
     except:
         selected = [n.name for n in node.parent_nodes]
         kwargs = {
             'name': [node.name],
             'urlname': [node.urlname],
             'description': [node.description],
             'style': [node.style]
         }
     form = NodeEditForm.init(Node.get_node_choices(),
                              selected,
                              node=node,
                              **kwargs)
     if form.validate():
         node = form.save(user, node=node)
         result = {
             'status': 'success',
             'message': '节点修改成功',
             'node_url': node.url
         }
         if self.is_ajax:
             return self.write(result)
         self.flash_message(**result)
         return self.redirect(node.url)
     if self.is_ajax:
         return self.write(form.result)
     return self.render("node/edit.html", form=form, node=node)
Beispiel #4
0
def creatNet(G,net):

    # G = snap.LoadEdgeList(snap.PUNGraph,"d:\\networkdata\\show\\facebook.txt",0,1)
    # for NI in G.Nodes():
    #   print "node: %d, out-degree %d, in-degree %d" % ( NI.GetId(), NI.GetOutDeg(), NI.GetInDeg())
    nodeIDs = set()
    nodes = []
    edges = []
    for EI in G.Edges():

        # print "edge (%d, %d)" % (EI.GetSrcNId(), EI.GetDstNId())
        id = EI.GetDstNId()
        if id not in nodeIDs:
            nodeIDs.append(id)
        inNode = Node(nodeId=id,net=net)
        nodes.append(inNode)
        id = EI.GetSrcNId()
        if id not in nodeIDs:
            nodeIDs.append(id)
        outNode = Node(nodeId=id,net=net)
        nodes.append(outNode)
        edge = Edge(nodeIn=inNode,nodeOut=outNode)
        edges.append(edge)
 
        # edge.save()
    # for NI in G.Nodes():
    #   for Id in NI.GetOutEdges():
    #       print "edge (%d %d)" % (NI.GetId(), Id)
    Node.objects.bulk_create(nodes)
    Edge.objects.bulk_create(edges)
Beispiel #5
0
def page_path(slug, **kwargs):
    p = Node.all().filter('abs_path = ', slug).get()
    if p is None:
        p = Node.all().filter('slug = ', slug).get()
    if p is None:
        return u''
    return p.get_absolute_url(**kwargs)
Beispiel #6
0
def menu(abs_path=''):
    base = Node.all().filter('abs_path = ', abs_path).get()
    qs = Node.all().filter('active = ', True).filter('state = ', PUBLISHED)
    l = len(base.abs_path)
    nodes = dict([(n.get_key(), n) for n in qs if n.abs_path.startswith(base.abs_path)])
    node = simple_rec(base, nodes)
    return node
Beispiel #7
0
 def post(self,request,  *args, **kwargs):
     
     # check name is free
     
     if Node.objects.filter(parent=request.POST.get('parent'), name=request.POST.get('name')).count() > 0:
         return HttpResponse("This name already exists", status=400)
     
     node = Node(parent_id=request.POST.get('parent'), name=request.POST.get('name'))
     node.save()
     
     if use_cacheops:
         print 'invalidate'
         invalidate_model(Node)
         node = Node.objects.get(pk=node.pk)
         
     
     return HttpResponse(simplejson.dumps({
                 'name' : node.name,
                 'icon' : 'default',
                 'loaded' : True,
                 'pk' : node.pk,
                 'position' : list(node.parent.get_children()).index(node),
                 'children' : [],
                 'parent' : node.parent.pk if node.parent is not None else None
             }), content_type="application/json", status=201)
Beispiel #8
0
    def test_insert_nodes(self):
        nodes_args = [
            (1, -1.4513525, -48.4689927, 'Av. Alm. Barroso x São Brás'),
            (2, -1.4053284, -48.4330374, 'Av. Alm. Barroso x Entroncamento'),
            (3, -1.4049556, -48.4326765, 'Av. Alm. Barroso x Entroncamento'),
            (4, -1.4510252, -48.4690023, 'Av. Alm. Barroso x São Brás')
        ]

        for (id_, lat, lon, name) in nodes_args:
            self.session.add(Node(lat, lon, name))
        self.session.commit()

        self.assertEqual(self.session.query(Node).count(), len(nodes_args))

        for (id_, lat, lon, name) in nodes_args:
            self.assertEqual(self.session.query(
                Node).get(id_), Node(lat, lon, name))

        self.session.add(Node(lat=-1.4538671, lon=-48.4925673,
                              name='Av. Assis de Vasconcelos x Av. Nazaré'))
        self.session.add(Node(-1.4606754, -48.4826942,
                              'Av. Assis de Vasconcelos x Av. Mal. Hermes'))
        self.session.commit()

        self.assertEqual(self.session.query(Node).count(), len(nodes_args)+2)
        self.assertIsNotNone(self.session.query(Node).get(5))
        self.assertIsNotNone(self.session.query(Node).get(6))

        for index in range(7, 10):
            self.assertIsNone(self.session.query(Node).get(index))
        self.session.commit()
Beispiel #9
0
def p_identifier_or_brackets_br(p):
    '''
    identifier_or_brackets : LEFT_BRACKET RIGHT_BRACKET IDENTIFIER
    '''
    dim_node = Node('dim', children=[1])
    id_node = Node('identifier', children=[p[3]])
    p[0] = [dim_node, id_node]
Beispiel #10
0
	def delete(self, node_id = None):
		node = Node.query.filter_by(id = node_id).first()
		if node: 
			Node.delete(id = node.id)
			return jsonify(ApiObjects(node.json()))
		else:
			jsonify(ApiObjects())
Beispiel #11
0
def p_int_statement(p):
    '''
    statement : INT identifier_or_brackets SEMICOLON
    '''
    type_node = Node('type', children=[p[2][0], p[1]])
    var_node = Node('variable', children=[type_node, p[2][1]])
    p[0] = Node('statement', children=[var_node])
Beispiel #12
0
def p_identifier_or_brackets_id(p):
    '''
    identifier_or_brackets : IDENTIFIER
    '''
    dim_node = Node('dim', children=[0])
    id_node = Node('identifier', children=[p[1]])
    p[0] = [dim_node, id_node]
Beispiel #13
0
def node_add(request):
    form = NodeForm(request.POST or None)
    if form.is_valid():
        data = {
            'nid': uuid.uuid4().hex,
            'title': str(form.cleaned_data['title']),
            'body': str(form.cleaned_data['body']),
            'author': str(form.cleaned_data['author']),
            'node_timestamp': int(time.time()),
            'revision_log': str(form.cleaned_data['revision_log']),
            'is_front_page': form.cleaned_data['is_front_page'],
            'is_sticky': form.cleaned_data['is_sticky'],
            'is_published': form.cleaned_data['is_published'],
            'can_comment': form.cleaned_data['can_comment'],
            # 'tags': str(form.cleaned_data['tags']),
            'node_type': str(form.cleaned_data['node_type'])
        }
        query = Node().insert(data)
        node = query.execute()

        #Increase the views count
        # count = {'views' : 'views+1'
        # }
        # count_query = NodeCount().update().where('nid', data['nid'], '=', True)
        # nodecount = count_query.execute()

        return HttpResponseRedirect(reverse('node_index'))
    context = {
        'form': form,
    }
    return render_to_response('addNode.html',
                              context,
                              context_instance=RequestContext(request))
    def test_node_gpu_relation(self):
        """
        Unit test that verifies that the correct relation between
        the GPU class and the node class is built
        """

        # We create a node
        node = Node()
        node.name = "node1"
        node.information_retrieved = True

        # We add several CPUs to it
        node.gpus = [
            GPU("Nvidia", "GeForce"),
            GPU("AMD", "Raedon")
        ]

        # We save everything to the db
        db.session.add(node)
        db.session.commit()

        # We retrived and verify that the gpus are there
        node = db.session.query(Node).filter_by(name='node1').first()

        self.assertEquals(2, len(node.gpus))
        self.assertEquals("Nvidia", node.gpus[0].vendor_id)
        self.assertEquals("AMD", node.gpus[1].vendor_id)

        # Lets delete a gpu directly from the session
        db.session.delete(node.gpus[1])
        db.session.commit()
        node = db.session.query(Node).filter_by(name='node1').first()
        self.assertEquals(1, len(node.gpus))
        self.assertEquals("Nvidia", node.gpus[0].vendor_id)
    def test_node_memory_relation(self):
        """
        Unit test that verifies that the correct relation between
        the Memory class and the node class is built
        """

        # We create a node
        node = Node()
        node.name = "node1"
        node.information_retrieved = True

        # We add several CPUs to it
        node.memories = [
            Memory(11111, "bytes"),
            Memory(11211, "bytes")
        ]

        # We save everything to the db
        db.session.add(node)
        db.session.commit()

        # We retrived and verify that the gpus are there
        node = db.session.query(Node).filter_by(name='node1').first()

        self.assertEquals(2, len(node.memories))
        self.assertEquals(11111, node.memories[0].size)
        self.assertEquals(11211, node.memories[1].size)

        # Lets delete a gpu directly from the session
        db.session.delete(node.memories[1])
        db.session.commit()
        node = db.session.query(Node).filter_by(name='node1').first()
        self.assertEquals(1, len(node.memories))
        self.assertEquals(11111, node.memories[0].size)
Beispiel #16
0
 def post(self, urlname):
     if not self.has_permission:
         return
     if not self.current_user.is_admin:
         return self.redirect_next_url()
     node = Node.get(urlname=urlname)
     if not node:
         return self.redirect_next_url()
     user = self.current_user
     args = self.request.arguments
     try:
         selected = args.get('parent_name')
         print(selected)
     except:
         selected = [n.name for n in node.parent_nodes]
         args = {'name': [node.name], 'urlname': [node.urlname],
                 'description': [node.description], 'style': [node.style]}
     form = NodeEditForm.init(Node.get_node_choices(), selected, args=args,
             node=node)
     if form.validate():
         node = form.save(user, node=node)
         result = {'status': 'success', 'message': '节点修改成功',
                 'node_url': node.url}
         if self.is_ajax:
             return self.write(result)
         self.flash_message(result)
         return self.redirect(node.url)
     if self.is_ajax:
         return self.write(form.result)
     return self.render("node/edit.html", form=form, node=node)
Beispiel #17
0
def p_identifier_or_assignment_array_element_assign(p):
    '''
    identifier_or_assignment : LEFT_BRACKET expression RIGHT_BRACKET ASSIGNMENT expression
    '''
    index_node = Node('index', children=[p[2]])
    right_part_node = Node('rignt_part', children=[p[5]])
    p[0] = ('assign', index_node, right_part_node)
Beispiel #18
0
def node_register(caller_identity):
    payload = request.get_json(force=True)

    proposal = payload.get('service_proposal', None)
    if proposal is None:
        return jsonify(error='missing service_proposal'), 400

    node_key = proposal.get('provider_id', None)
    if node_key is None:
        return jsonify(error='missing provider_id'), 400

    if node_key.lower() != caller_identity:
        message = 'provider_id does not match current identity'
        return jsonify(error=message), 403

    node = Node.query.get(node_key)
    if not node:
        node = Node(node_key)

    node.ip = request.remote_addr
    node.proposal = json.dumps(proposal)
    node.updated_at = datetime.utcnow()
    db.session.add(node)
    db.session.commit()

    return jsonify({})
Beispiel #19
0
def get_next_moves(current):
    moves = []
    zeroY, zeroX = position(current.grid, 0)
    gridsize = len(current.grid[0])
    if zeroY + 1 < gridsize:
        a = copy.deepcopy(current.grid)
        a[zeroY + 1][zeroX], a[zeroY][zeroX] = a[zeroY][zeroX], a[zeroY +
                                                                  1][zeroX]
        if a != current.grid:
            moves.append(Node(a))
    if zeroY - 1 > -1:
        b = copy.deepcopy(current.grid)
        b[zeroY - 1][zeroX], b[zeroY][zeroX] = b[zeroY][zeroX], b[zeroY -
                                                                  1][zeroX]
        if b != current.grid:
            moves.append(Node(b))
    if zeroX + 1 < gridsize:
        c = copy.deepcopy(current.grid)
        c[zeroY][zeroX +
                 1], c[zeroY][zeroX] = c[zeroY][zeroX], c[zeroY][zeroX + 1]
        if c != current.grid:
            moves.append(Node(c))
    if zeroX - 1 > -1:
        d = copy.deepcopy(current.grid)
        d[zeroY][zeroX -
                 1], d[zeroY][zeroX] = d[zeroY][zeroX], d[zeroY][zeroX - 1]
        if d != current.grid:
            moves.append(Node(d))
    for node in moves:
        node.parent = current
    return (moves)
    def test_node_cpu_relation(self):
        """
        Unit test that verifies that the correct relation between
        the testbed class and the node class is built
        """

        # We create a node
        node = Node()
        node.name = "node1"
        node.information_retrieved = True

        # We add several CPUs to it
        node.cpus = [
            CPU("Intel", "Xeon", "x86_64", "e6333", "2600Mhz", True, 2, "cache", "111"),
            CPU("AMD", "Zen", "x86_64", "xxxxx", "2600Mhz", True, 2, "cache", "111")
        ]

        # We save everything to the db
        db.session.add(node)
        db.session.commit()

        # We retrived and verify that the cpus are there
        node = db.session.query(Node).filter_by(name='node1').first()

        self.assertEquals(2, len(node.cpus))
        self.assertEquals("Intel", node.cpus[0].vendor_id)
        self.assertEquals("AMD", node.cpus[1].vendor_id)

        # Lets delete a cpu directly from the session
        db.session.delete(node.cpus[1])
        db.session.commit()
        node = db.session.query(Node).filter_by(name='node1').first()
        self.assertEquals(1, len(node.cpus))
        self.assertEquals("Intel", node.cpus[0].vendor_id)
Beispiel #21
0
def bbs_add_node():
    form = NodeForm(request.form)
    form.section.query_factory = Section.query.all

    if request.method == 'POST' and form.validate():
        section = form.data["section"]
        print section, type(section)
        if not section:
            form.section.errors.append(u"Section不存在!")
            return render_template("add_node.html", form=form)

        node = Node(section=section,
                    name=form.data["node_name"].strip(),
                    title=form.data["node_title"],
                    descp=form.data["descp"],
                    item_per_page=form.data["item_per_page"],
                    header=form.data["header"],
                    footer=form.data["footer"],
                    sidebar=form.data["sidebar"],
                    sidebar_ads=form.data["sidebar_ads"],
                    avatar_url=form.data["avatar_url"])
        node.created = datetime.now()

        section.node_count += 1
        db.session.add_all([node, section])
        db.session.commit()
        return redirect(url_for(".bbs_node",
                                node_name=urllib.quote(node.name)))

    return render_template("add_node.html", form=form)
Beispiel #22
0
def calculate_connected_component(index, graph, top_artists, talky=False):
    """
	Takes the given graph and computes the following measures:
		- size (number of nodes)
		[- diameter]
		- density
		- degree
		- closeness_centrality
		[- betweenness_centrality]
		[- eccentricity]

	The first three measures are computed for each connected component.
	The remaining ones are computed for each node.

	The result is written to a database (see tricorder.models).
	"""
    is_real_graph = graph.number_of_edges() > 0
    num_artists = 0
    num_top_artists = 0

    # calculate measures (only if we have edges!)
    density = nx.density(graph) if is_real_graph else 0
    # print "diameter..."
    # diameter = nx.diameter(graph) if is_real_graph else 0
    degree = sc.degree_centrality(graph) if is_real_graph else {}
    closeness = sc.closeness_centrality(graph) if is_real_graph else {}
    # betweenness = sc.betweenness_centrality(graph) if is_real_graph else {}
    # print "eccentricity..."
    # eccentricity = sc.eccentricity(graph) if is_real_graph else {}

    # create Node DB entries
    for id, attrs in graph.node.items():
        if attrs["type"] == "artist":
            num_artists += 1
            if attrs["name"] in top_artists:
                num_top_artists += 1
                # ecc = 1/eccentricity[id] if id in eccentricity else 0 # need an extra variable here since division by zero is evil
        Node.create(
            nid=int(id),
            pid=graph.graph["pid"],
            node_type=attrs["type"],
            name=attrs["name"],
            degree=degree.get(id, 0),
            closeness=closeness.get(id, 0),
        )
        # eccentricity=ecc)#, betweenness=betweenness.get(id, 0))

        # create Partition DB entry
    Partition.create(
        pid=graph.graph["pid"],  # diameter=diameter,
        num_nodes=graph.number_of_nodes(),
        num_edges=graph.number_of_edges(),
        num_artists=num_artists,
        num_top_artists=num_top_artists,
        density=density,
    )

    if talky and index % 500 == 0:
        print index
Beispiel #23
0
 def _create_node(self, node_key):
     node = Node(node_key)
     node.proposal = json.dumps({
         "id": 1,
         "format": "service-proposal/v1",
         "provider_id": node_key,
     })
     db.session.add(node)
Beispiel #24
0
    def test_automata_without_final_states(self):
        initial = Node()
        final = Node()
        initial.add_transition('a', final)
        automata = Automata([initial, final], ['a'], initial, [])

        #assert para que haya alguno, la idea es que si no tendría que tirar excepción.
        self.assertTrue(automata.initial == initial)
Beispiel #25
0
def p_unary_expression(p):
    '''
    unary_expression : MINUS expression %prec UMINUS
                               | NOT expression
    '''
    operation_node = Node('operation', children=[p[1]])
    operand_node = Node('operand', children=[p[2]])
    p[0] = Node('unary_expression', children=[operation_node, operand_node])
Beispiel #26
0
def p_boolean_single_or_array_var(p):
    '''
    single_or_array_var : BOOLEAN IDENTIFIER
    '''
    dim_node = Node('dim', children=[0])
    type_node = Node('type', children=[dim_node, p[1]])
    id_node = Node('identifier', children=[p[2]])
    p[0] = Node('variable', children=[type_node, id_node])
Beispiel #27
0
def p_boolean_return_type_and_name(p):
    '''
    return_type_and_name : BOOLEAN IDENTIFIER
    '''
    dim_node = Node('dim', children=[0])
    type_node = Node('type', children=[dim_node, p[1]])
    id_node = Node('identifier', children=[p[2]])
    p[0] = [type_node, id_node]
Beispiel #28
0
def p_method(p):
    """
    method : PUBLIC return_type_and_name LEFT_PARENTHESIS params_list RIGHT_PARENTHESIS LEFT_BRACE statements_list RETURN expression SEMICOLON RIGHT_BRACE
    """
    return_node = Node('return', children=[p[9]])
    children = [p[4], p[7], return_node]
    children.extend(p[2])
    p[0] = Node('method', children=children)
Beispiel #29
0
 def get(self):
     node_id = int(self.get_argument('node_id', 0))
     node = Node.get(id=node_id)
     if node:
         selected = [node.name]
     else:
         selected = []
     form = NodeForm.init(Node.get_node_choices(), selected)
     return self.render("node/create.html", form=form)
Beispiel #30
0
def setNode(stub, raddr):
	fChar = stub[:1]
	if fChar.isalpha():
		fChar = fChar.lower()
	else:
		fChar = "else"

	a = Node(stub = stub, remoteaddrs = raddr, f = fChar)
	a.put()
Beispiel #31
0
 def get(self):
     node_id = int(self.get_argument('node_id', 0))
     node = Node.get(id=node_id)
     if node:
         selected = [node.name]
     else:
         selected = []
     form = NodeForm.init(Node.get_node_choices(), selected)
     return self.render("node/create.html", form=form)
Beispiel #32
0
def create_structureNode(long_title, text="", authors=()):
    structure = Node(node_type=Node.STRUCTURE_NODE, title=long_title)
    structure.save()
    text_obj = Text(node=structure, text=text)
    text_obj.save()
    for author in authors:
        text_obj.authors.add(author)
    text_obj.save()
    return structure
Beispiel #33
0
def test_node_get_dict():
    copy_list = copy.deepcopy(EXAMPLE_INPUT)
    new_node = Node(copy_list, True)
    node_dict = new_node._get_dict()
    assert node_dict.get("number of children") == EXAMPLE_INPUT[0]
    assert node_dict.get("metadata") == EXAMPLE_INPUT[-3:]
    assert node_dict.get("amount of metadata") == EXAMPLE_INPUT[1]
    assert node_dict.get("total") == 138
    assert len(node_dict.get("childrens")) == EXAMPLE_INPUT[0]
Beispiel #34
0
def p_main_method(p):
    '''
    main_method : PUBLIC STATIC VOID MAIN LEFT_PARENTHESIS STRING LEFT_BRACKET RIGHT_BRACKET IDENTIFIER RIGHT_PARENTHESIS LEFT_BRACE statements_list RIGHT_BRACE
    '''
    dim_node = Node('dim', children=[1])
    type_node = Node('type', children=[dim_node, p[6]])
    id_node = Node('identifier', children=[p[9]])
    arg_node = Node('arg', children=[type_node, id_node])
    p[0] = Node('main_method', children=[arg_node, p[12]])
Beispiel #35
0
def p_single_or_array_var_ref(p):
    '''
    single_or_array_var : IDENTIFIER IDENTIFIER
    '''
    dim_node = Node('dim', children=[0])
    type_id_node = Node('identifier', children=[p[1]])
    type_node = Node('type', children=[dim_node, type_id_node])
    id_node = Node('identifier', children=[p[2]])
    p[0] = Node('variable', children=[type_node, id_node])
Beispiel #36
0
def add(request, key):
    """ add a new page
        to the set"""
    to = key # lame but it does the trick for now
    blocks = []
    form = PageForm(request.form)
    add  = BlockAddForm(request.form, prefix='_add')

    form.layout.choices =  Layout.get_key_to_path()
    if request.method == 'POST':
        # some logic to find __block elements.
        for key in request.form:
            if key.startswith('__block:'):
                name = key.split('__',2)[1][6:]
                blocks.append((name, BlockForm(request.form, prefix='__block:%s__' % name)))
        if add.validate() and add.add.data is True:
            blocks.append((add.name.data, BlockForm(prefix='__block:%s__' % add.name.data)))
            add = BlockAddForm(prefix='_add')
        elif form.validate() and all([block.validate() for _, block in blocks]):
            name = form.name.data
            slug = form.slug.data
            breadcrumb = form.breadcrumb.data
            state = form.state.data
            active = form.active.data
            if len(slug) < 1:
                slug = slugify(name)
            author = users.get_current_user()
            updated = datetime.now()

            description = form.description.data
            keywords = form.keywords.data
            body = form.body.data
            content_type = form.content_type.data
            if form.layout.data == 'Layout:None':
                layout = None
            else:
                layout = Layout.get(form.layout.data.split(':',1)[1])
            page = Node.add(to=to, name=name, slug=slug, breadcrumb=breadcrumb,
                            updated=updated, author=author, body=body,
                            description=description, keywords=keywords, layout=layout,
                            content_type=content_type,
                            state=state, active=active, type=PAGE)
            done = []
            try:
                for name, block in blocks:
                    b = Block(node=page, name=name, body=block.body.data)
                    b.put()
                    done.append(b)
            except:
                db.delete(done)
                Node.drop(page.get_key())
            if form.save.data is True:
                return redirect(url_for('nut:pages/list_pages'), 301)
            if form.cont.data is True:
                return redirect(url_for('nut:pages/edit', key=page.get_key()), 301)

    return render_template('app:pages/form.html', form=form, add=add, blocks=blocks)
Beispiel #37
0
def p_id_return_type_and_name(p):
    '''
    return_type_and_name : IDENTIFIER IDENTIFIER
    '''
    dim_node = Node('dim', children=[0])
    type_id_node = Node('identifier', children=[p[1]])
    type_node = Node('type', children=[dim_node, type_id_node])
    id_node = Node('identifier', children=[p[2]])
    p[0] = [type_node, id_node]
Beispiel #38
0
def p_bool_statement(p):
    '''
    statement : BOOLEAN IDENTIFIER SEMICOLON
    '''
    dim_node = Node('dim', children=[0])
    type_node = Node('type', children=[dim_node, p[1]])
    id_node = Node('identifier', children=[p[2]])
    var_node = Node('variable', children=[type_node, id_node])
    p[0] = Node('statement', children=[var_node])
Beispiel #39
0
    def test_is_deterministic_automata__det(self):
        initial = Node()
        final = Node()
        other_node = Node()
        initial.add_transition('a', final)
        automata = Automata([initial, final, other_node], ['a'], initial, [final])

        self.assertTrue(automata.is_deterministic())
        self.assertFalse(automata.has_lambda())
Beispiel #40
0
 def get(self):
     node_id = force_int(self.get_argument('node_id', 0), 0)
     node = Node.get(id=node_id)
     if node:
         selected = node.name
     else:
         selected = None
     choices = Node.get_node_choices()
     form = TopicForm.init(choices=choices, selected=selected)
     return self.render("topic/create.html", form=form, node=node)
Beispiel #41
0
    def test_build_child_tree_path(self):
        node = Node.objects.get(pk=6)
        child_node = Node(parent=node)
        self.assert_empty_tree_path(child_node)
        child_node.save()

        self.assertEquals(
            node.tree_path+PATH_SEPARATOR+child_node.zerro_filled_pk,
            child_node.tree_path
        )
Beispiel #42
0
def node_index(request):
    query = Node().select('nid', 'title')
    query.compare('is_published', True, '=',
                  True).compare('node_timestamp', int(time.time()), '<=',
                                True).allowFiltering()
    node_list = query.execute()
    context = {
        'node_list': node_list,
    }
    return render_to_response('nodes.html', context)
Beispiel #43
0
    def test_is_deterministic_node__not_det(self):
        tested = Node()
        target1 = Node()
        target3 = Node()
        s = 'a'

        tested.add_transition(s, target1)
        tested.add_transition(s, target3)

        self.assertFalse(tested.is_deterministic())
Beispiel #44
0
    def test_add_transition__existing_symbol(self):
        tested = Node()
        target1 = Node()
        target2 = Node()
        s = 'a'

        tested.add_transition(s, target1)
        tested.add_transition(s, target2)

        self.assertEqual(set([target1, target2]), set(tested.transitions[s]))
Beispiel #45
0
    def test_add_transition__new_symbol(self):
        tested = Node()
        target = Node()
        s = 'a'

        self.assertFalse(s in tested.transitions)
        tested.add_transition(s, target)

        self.assertTrue(s in tested.transitions)
        self.assertEqual([target], tested.transitions[s])
Beispiel #46
0
    def test_filter_active_nodes(self):
        node1 = Node("node1")
        node1.mark_activity()
        db.session.add(node1)

        node2 = Node("node2")
        db.session.add(node2)

        nodes = filter_active_nodes().all()
        self.assertEqual([node1], nodes)
Beispiel #47
0
    def test_construction_automata__extra_final(self):
        initial = Node()
        final = Node()
        initial.add_transition('a', final)

        states = [initial, final]
        symbols = ['a']

        with self.assertRaises(FinalsNotInStatesException):
            Automata(states, symbols, initial, [final, Node()])
Beispiel #48
0
 def get(self):
     node_id = force_int(self.get_argument('node_id', 0), 0)
     node = Node.get(id=node_id)
     if node:
         selected = node.name
     else:
         selected = None
     choices = Node.get_node_choices()
     form = TopicForm.init(choices=choices, selected=selected)
     return self.render("topic/create.html", form=form, node=node)
Beispiel #49
0
 def get(self, urlname):
     node = Node.get(urlname=urlname)
     if node:
         selected = [n.name for n in node.parent_nodes]
     else:
         return self.redirect_next_url()
     kwargs = {'name': [node.name], 'urlname': [node.urlname],
               'description': [node.description], 'style': [node.style]}
     form = NodeEditForm.init(Node.get_node_choices(), selected, node=node, **kwargs)
     return self.render("node/edit.html", form=form, node=node)
Beispiel #50
0
    def test_add_terminal_node__ejemplo_simple(self):
        q0 = Node('q0')
        q1 = Node('q1')
        q2 = Node('q2')

        q0.add_transition('a', q1)
        q1.add_transition('b', q2)
        q2.add_transition('a', q2)
        q2.add_transition('b', q2)

        symbols = ['a', 'b']
        automata = Automata([q0, q1, q2], symbols, q0, [q2])

        with_terminal_node = add_terminal_node(automata)

        self.assertEqual(automata.symbols, with_terminal_node.symbols)
        self.assertEqual(len(automata.states) + 1, len(with_terminal_node.states))

        q0T = with_terminal_node.state_by_name("q0")
        q1T = with_terminal_node.state_by_name("q1")
        q2T = with_terminal_node.state_by_name("q2")
        qT = with_terminal_node.state_by_name("qT")

        self.assertEqual(symbols, q0T.transitions.keys())
        self.assertEqual([q1T], q0T.transitions['a'])
        self.assertEqual([qT], q0T.transitions['b'])
        self.assertEqual(symbols, q1T.transitions.keys())
        self.assertEqual([qT], q1T.transitions['a'])
        self.assertEqual([q2T], q1T.transitions['b'])
        self.assertEqual(symbols, q2T.transitions.keys())
        self.assertEqual([q2T], q2T.transitions['a'])
        self.assertEqual([q2T], q2T.transitions['b'])
        self.assertEqual(symbols, qT.transitions.keys())
        self.assertEqual([qT], qT.transitions['a'])
        self.assertEqual([qT], qT.transitions['b'])
Beispiel #51
0
    def test_accept__ejemplo_enunciado(self):
        q0 = Node('q0')
        q1 = Node('q1')
        q2 = Node('q2')
        symbols = ['a', 'b', 'c', 'd', 'e', 'f']

        q0.add_transition('a', q1)
        q1.add_transition('b', q2)
        q1.add_transition('c', q1)
        q2.add_transition('f', q2)

        tested = Automata([q0, q1, q2], symbols, q0, [q1, q2])

        self.assertTrue(tested.accepts("a"))
        self.assertTrue(tested.accepts("ac"))
        self.assertTrue(tested.accepts("accc"))
        self.assertTrue(tested.accepts("ab"))
        self.assertTrue(tested.accepts("acccb"))
        self.assertTrue(tested.accepts("acccbf"))
        self.assertTrue(tested.accepts("acccbfff"))
        self.assertFalse(tested.accepts(""))
        self.assertFalse(tested.accepts("b"))
        self.assertFalse(tested.accepts("c"))
        self.assertFalse(tested.accepts("d"))
        self.assertFalse(tested.accepts("e"))
        self.assertFalse(tested.accepts("f"))
        self.assertFalse(tested.accepts("Z"))
        self.assertFalse(tested.accepts("abb"))
        self.assertFalse(tested.accepts("af"))
        self.assertFalse(tested.accepts("acca"))
Beispiel #52
0
    def to_automata(self):
        content_automata = self.content.to_automata()
        q0 = Node()
        qf = Node()
        states = [q0, qf] + content_automata.states

        q0.add_transition(LAMBDA, qf)
        q0.add_transition(LAMBDA, content_automata.initial)
        for q in content_automata.finals:
            q.add_transition(LAMBDA, qf)

        return Automata(states, content_automata.symbols, q0, [qf])
Beispiel #53
0
 def post(self):
     if not (session and session.get('uid')):
         return jsonify({'error': 'Not logged in'})
     node = Node(title=request.form['title'])
     node.url = request.form['url']
     node.score = 1
     node.save()
     space = Space.objects(id=ObjectId(request.form['sid']))[0]
     space.nodes.append(node)
     space.save(cascade=True)
     
 	return jsonify({'success':1})
Beispiel #54
0
    def test_reachable_nodes(self):
        q0 = Node("q0")
        q1 = Node("q1")
        q2 = Node("q2")

        q0.add_transition(0, q1)
        q0.add_transition(1, q2)
        q2.add_transition(1, q1)

        self.assertEqual(set([q1, q2]), q0.reachable_nodes())
        self.assertEqual(set([]), q1.reachable_nodes())
        self.assertEqual(set([q1]), q2.reachable_nodes())
Beispiel #55
0
 def get(self):
     if not self.has_permission:
         return
     if not self.current_user.is_admin:
         return self.redirect_next_url()
     node_id = int(self.get_argument('node_id', 0))
     node = Node.get(id=node_id)
     if node:
         selected = [node.name]
     else:
         selected = []
     form = NodeForm.init(Node.get_node_choices(), selected)
     return self.render("node/create.html", form=form)
Beispiel #56
0
def create_structureNode(long_title, text="", authors=()):
    structure = Node()
    structure.node_type = 'structureNode'
    structure.title = long_title
    structure.save()
    text_obj = Text()
    text_obj.node = structure
    text_obj.text = text
    text_obj.save()
    for author in authors:
        text_obj.authors.add(author)
    text_obj.save()
    return structure
Beispiel #57
0
def create_textNode(long_title, text="", authors=()):
    text_node = Node()
    text_node.node_type = Node.STRUCTURE_NODE
    text_node.title = long_title
    text_node.save()
    text_obj = Text()
    text_obj.node = text_node
    text_obj.text = text
    text_obj.save()
    for author in authors:
        text_obj.authors.add(author)
    text_obj.save()
    return text_node
Beispiel #58
0
            def transaction():
                q = Node.all()
                q.ancestor(project)
                q.filter('title =', title)
                node = q.get()

                if node is None:
                    node = Node(
                        parent=project,
                        title=title,
                    )
                    node.put()

                return node
Beispiel #59
0
 def get(self, urlname):
     if not self.has_permission:
         return
     if not self.current_user.is_admin:
         return self.redirect_next_url()
     node = Node.get(urlname=urlname)
     if node:
         selected = [n.name for n in node.parent_nodes]
     else:
         return self.redirect_next_url()
     args = {'name': [node.name], 'urlname': [node.urlname],
             'description': [node.description], 'style': [node.style]}
     form = NodeEditForm.init(Node.get_node_choices(), selected, args=args,
             node=node)
     return self.render("node/edit.html", form=form, node=node)
Beispiel #60
0
def activate_node(payload = None):
    """
        Activate Node
        Called by node to activate itself on the hub
        ---
        tags:
          - nodes
        responses:
          200:
            description: Returns a list of sensors
        """

    global nodes
    id   = int(request.args.get("id"))
    ip   = str(request.args.get("ip"))
    port = int(request.args.get("port", 80))
    log = hub.log
    listener = hub.node_listeners

    node = Node.get_by_id(id)
    if node:
        node.update(ip=ip)
        if not listener.is_alive(id):
            t = NodeCollector(id, hub.Webapi, hub.log)
            t.start()
            listener.add_thread(id, t)
            log.log("Node " + str(id) + " is now online.")
            return json.jsonify({'message': "Node " + str(id)
                                            + " is now online."}),201
        if listener.is_alive(id):
            log.log("Node " + str(id)
                    + " is already online but tried"
                    + " to activate again, Updated it's data")
            return json.jsonify({'message': "Node " + str(id)
                                            + " was already online"}),201
    else:
        node = Node(id, ip)
        t = NodeCollector(id, hub.Webapi, hub.log)
        t.start()
        listener.add_thread(id, t)
        updates = {"nodes": []}
        node_updates = updates.get("nodes")
        for node in Node.get_all(fresh=True):
            if node.printer_id == None:
                node_updates.append(node.id)
        t = threading.Thread(target=hub.Webapi.update_nodes,args=updates)
        t.start()
        return json.jsonify({"message": str(id) + " has been activated."}),201