예제 #1
0
def branches(request, id=0):
    if request.method == 'GET':
        all_branches = Branch.objects.get(user=request.user)
        serializer = BranchSerializer(all_branches)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = BranchSerializer(data=request.DATA)
        if serializer.is_valid():
            serializer.data.user = request.user
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'PUT':
        branch = Branch(id=id)
        serializer = BranchSerializer(branch, data=request.DATA)
        if serializer.is_valid():
            serializer.data.user = request.user
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        branch = Branch(id=id)
        branch.delete()
        return Response("DELETED", status=status.HTTP_200_OK)
예제 #2
0
 def get(self):
     a =  Ari_types()
     a.ari = "Ad Hominem"
     a.description = "Against the person"
     a.put()
     a =  Ari_types()
     a.ari = "Ad Hominem Tu Quoque"
     a.description = "You Too Fallacy"
     a.put()
     b = Branch()
     b.branch = "Business"
     b.description ="Business"
     b.put()
     b = Branch()
     b.branch = "Entertainment"
     b.description = "Entertainment"
     b.put()
     b = Branch()
     b.branch = "Economics"
     b.description = "Economics"
     b.put()
     b = Branch()
     b.branch = "Politics"
     b.description = "Politics"
     b.put()
예제 #3
0
    def setUp(self):

        #the memcache will contain values that will break the tests
        #dont run this on production!
        memcache.flush_all()

        # First, create an instance of the Testbed class.
        self.testbed = testbed.Testbed()
        # Then activate the testbed, which prepares the service stubs for use.
        self.testbed.activate()
        # Create a consistency policy that will simulate the High Replication consistency model.
        self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(
            probability=0)
        # Initialize the datastore stub with this policy.
        self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)

        millis = int(round(time.time() * 1000))

        tree_name = 'test_tree' + str(millis)

        username = '******' + str(millis)

        self.parent_branch = Branch(id=tree_name)

        self.parent_branch.author_name = username
        self.parent_branch.link = ''
        self.parent_branch.content = ''
        self.parent_branch.put()

        self.child_branchs = []
예제 #4
0
    def testValidator(self):

        test_link_text = "a" * 24
        test_content_text = "b" * 24

        branch = Branch()
        branch.link = test_link_text
        branch.content = test_content_text
        branch.put()

        self.assertEqual(branch.link, test_link_text)
        self.assertEqual(branch.content, test_content_text)

        branch = Branch()
        branch.link = "<a>" + test_link_text + "</a>"
        branch.content = "<a>" + test_content_text + "</a>"
        branch.put()

        self.assertEqual(branch.link, test_link_text)
        self.assertEqual(branch.content, test_content_text)
예제 #5
0
def create_branch_entry(request):
    if request.method == 'POST':
        try:
            received_json_data = json.loads(request.body)
            id = received_json_data.get('id', '')
            name = received_json_data.get('name', '')
            store_id = received_json_data.get('store_id', '')
            user_id = received_json_data.get('user_id', 'unknown')

            query = session.query(Store).filter(Store.id == store_id)
            _row = query.first()

            if _row is None:
                return JsonResponse(
                    {
                        "success":
                        "false",
                        "error":
                        "Store entry with store_id of " + str(store_id) +
                        " not found"
                    },
                    status=500)

            row = Branch(name=name, id=id, store_id=store_id)
            session.add(row)
            session.commit()
            create_new_log(user_id, "create branch", "branches", "all",
                           str(id))
            return JsonResponse({"Success": "true"}, status=200)
        except SQLAlchemyError as e:
            print(e)
            session.rollback()
            return JsonResponse({
                "success": "false",
                "error": e.message
            },
                                status=500)
        except ValueError as e:
            session.rollback()
            return JsonResponse({
                "success": "false",
                "error": e.message
            },
                                status=500)

    else:
        return JsonResponse({
            "success": "false",
            "error": "Method is POST"
        },
                            status=500)

    return JsonResponse({"Success": "true"}, status=200)
예제 #6
0
 def create_branches(self):
     """
     Cadastra os Ramos
     """
     #print("CADASTRAR RAMOS:")
     for branch in BRANCHS:
         branch_new = Branch()
         branch_new.id = branch['id']
         branch_new.name = branch['name']
         branch_new.description = branch['description']
         branch_new.active = branch['active']
         if branch.get('group'):
             branch_new.group = Group.objects.get(pk=branch['group']['id'])
         branch_new.save()
예제 #7
0
    def testUpdateNoDuplicate(self):

        branch = Branch()
        branch.link = 'testIdenticalLink.some_link'
        branch.content = 'some_content'

        branch.revision = 0
        branch.parent_branch = self.parent_branch.key
        branch.parent_branch_authorname = self.parent_branch.authorname
        branch.put()

        self.parent_branch.append_child(branch)

        self.assertTrue(len(self.parent_branch.children()) == 1)

        self.child_branchs.append(branch)
예제 #8
0
    def fill_branch_table(self, xml_info_list):
        """
        This method unpacks the tuples in the xml_info_list and creates a list of Branch items
        :param xml_info_list: a list of tuples containing all relevant information
        :return: a list of Branch objects
        """
        branch_list = []

        for branch_id, branch_name, address, sub_chain_id, city in xml_info_list:
            # if not in db then add it
            if (int(branch_id), self.current_super['chain_id']) not in \
                    self.branch_unique_constraint_set:
                branch_list.append(
                    Branch(id=branch_id,
                           name=branch_name,
                           address=address,
                           sub_chain_id=sub_chain_id,
                           city=city,
                           chain_id=self.current_super['chain_id']))
                self.branch_unique_constraint_set.add(
                    (int(branch_id), self.current_super['chain_id']))

        return branch_list
예제 #9
0
파일: views.py 프로젝트: qualisign/treeli
def index(request):
    if request.method != 'POST':
        return render(request, 'index.html')
    else:
        if request.is_ajax():
            if request.POST.get('userName'):
                user_name = request.POST.get('userName')
                user = User.objects.get(user_name=user_name)
            else:
                user = None

            if request.POST.get("mode") == "grow":

                parent = request.POST.get('parent')
                child = request.POST.get('child')

                # case 1: parent already trunk -- create branch from child
                try:
                    trunk = Trunk.objects.get(text=parent)
                    drawing = trunk.drawing
                    if trunk:
                        try:
                            branch = Branch.objects.get(text=child)
                            data = {
                                "already": True,
                                "parent": parent,
                                "child": child
                            }
                            return JsonResponse(data)
                        except Branch.DoesNotExist:
                            branch = Branch(text=child, trunk=trunk)
                            branch.save()
                            branch.get_tips()
                            data = drawing.get_data()
                            if trunk.branch_set.count() > 1:
                                data["tree?"] = trunk.text
                                branch.stage = "filled"
                                branch.save()
                            return JsonResponse(data)
                        # display message saying that this combo already exists.

                except Trunk.DoesNotExist:
                    # case 2: parent already branch -- create twig from child
                    print("trying case 2")
                    try:
                        branch = Branch.objects.get(text=parent)
                        drawing = branch.trunk.drawing
                        if branch:
                            try:
                                twig = Twig.objects.get(text=child)
                                data = {
                                    "already": True,
                                    "parent": parent,
                                    "child": child
                                }
                                return JsonResponse(data)
                            except Twig.DoesNotExist:
                                twig = Twig(text=child, branch=branch)
                                twig.save()
                                twig.get_tips()
                                data = drawing.get_data()
                                if branch.trunk.branch_set.count() > 1:
                                    data["tree?"] = branch.trunk.text
                                    twig.stage = "filled"
                                    twig.save()
                                return JsonResponse(data)

                    except Branch.DoesNotExist:
                        # case 3: parent already twig -- create leaf from child
                        print("trying case 3")
                        try:
                            twig = Twig.objects.get(text=parent)
                            drawing = twig.branch.trunk.drawing
                            if twig:
                                try:
                                    leaf = Leaf.objects.get(text=child)
                                    leaf.twigs.add(twig)
                                    leaf.save()
                                    leaf.get_tips(parent)
                                    data = drawing.get_data()
                                    return JsonResponse(data)
                                except Leaf.DoesNotExist:
                                    leaf = Leaf(text=child)
                                    leaf.save()
                                    leaf.twigs.add(twig)
                                    leaf.save()
                                    leaf.get_tips(parent)
                                    data = drawing.get_data()
                                    if twig.branch.trunk.branch_set.count(
                                    ) > 1:
                                        data["tree?"] = twig.branch.trunk.text
                                        leaf.stage = "filled"
                                        leaf.save()
                                    return JsonResponse(data)

                        except Twig.DoesNotExist:
                            # case 4: neither child nor parent saved to tree --
                            # create branch from child and trunk from parent
                            print("trying case 4")
                            trunk = Trunk.objects.create(text=parent)
                            branch = Branch.objects.create(text=child)
                            branch.get_tips()
                            branch.trunk = trunk
                            branch.save()
                            drawing = Drawing.objects.create(text=parent,
                                                             trunk=trunk)
                            data = drawing.get_data()
                            trunk.stage = "filled"
                            trunk.save()
                            branch.stage = "filled"
                            branch.save()
                            return JsonResponse(data)

            elif request.POST.get("mode") == "prompt":
                trunk_name = request.POST.get("trunkName")
                trunk = Trunk.objects.get(text=trunk_name)
                try:
                    tree = Tree.objects.get(name=trunk_name)
                    tree.rank_twigs()
                    tree.save()
                    sorted_twigs = Twig.objects.order_by('-rank').filter(
                        tree=tree)
                    current_twig = sorted_twigs[tree.twigs_learned]
                    print("current twig is " + current_twig.text)
                    data = {"twig": current_twig.text}
                    return JsonResponse(data)
                except Tree.DoesNotExist:
                    tree = Tree(name=trunk_name, trunk=trunk)
                    tree.rank_twigs()
                    tree.save()
                    sorted_twigs = Twig.objects.order_by('-rank').filter(
                        tree=tree)
                    current_twig = sorted_twigs[tree.twigs_learned]
                    data = {"twig": current_twig.text}
                    return JsonResponse(data)

            elif request.POST.get("mode") == "remind":
                trunk_name = request.POST.get("trunkName")
                tree = Tree.objects.get(name=trunk_name)
                sorted_twigs = Twig.objects.order_by('-rank').filter(tree=tree)
                current_twig = sorted_twigs[tree.twigs_learned]
                tries = request.POST.get("tries").strip(',')
                for leaf in current_twig.leaf_set.all():
                    if leaf.text in tries:
                        leaf.learned = True
                        leaf.save()
                total_count = current_twig.leaf_set.count()
                learned_count = current_twig.leaf_set.all().filter(
                    learned=True).count()
                if total_count == learned_count:
                    tree.twigs_learned += 1
                    tree.save()
                    current_twig = sorted_twigs[tree.twigs_learned]
                    data = {"twig": current_twig.text}
                    return JsonResponse(data)
                else:
                    missed_leaf = current_twig.leaf_set.all().filter(
                        learned=False)[0]
                    print("missed leaf is: " + missed_leaf.text)
                    next_twigs_list = [
                        i.text for i in missed_leaf.twigs.all()
                        [1:missed_leaf.reminders + 1]
                    ]
                    print(next_twigs_list)

                    next_twigs = map(lambda x: " AND " + x, next_twigs_list)
                    data = {
                        "miss": current_twig.text,
                        "next_twigs": next_twigs
                    }
                    missed_leaf.reminders += 1
                    missed_leaf.save()
                    return JsonResponse(data)

            elif request.POST.get("mode") == "check":
                to_check = request.POST.get("toCheck")
                try:
                    matching_leaf = current_twig.leaf_set.get(text=to_check)
                    next_leaf = current_twig.misses[indexofmissedleaf + 1]
                    other_twigs = request.POST.get(nextTwigs)
                    next_leaf_next_twigs = [
                        i.text
                        for i in next_leaf.twigs[0:missed_leaf.reminders]
                    ]
                    if other_twigs in [twig.text for i in matching_leaf.twigs]:
                        # user successfully remembered missed leaf she was reminded of. go on
                        # to next leaf...
                        matching_leaf.learned = True
                        matching_leaf.save()
                        current_twig.misses.remove(matching_leaf)
                        data = {
                            "miss": next_leaf.text,
                            "next_twigs": next_leaf_next_twigs
                        }
                        return JsonResponse(data)
                except matching_leaf.DoesNotExist:
                    # user failed to remember missed leaf she was reminded of.
                    # give another reminder, unless she has exhausted them all...
                    missed_leaf = current_twig.misses[0]
                    next_twigs = [
                        i.text
                        for i in missed_leaf.twigs[0:missed_leaf.reminders]
                    ]
                    data = {"miss": current_twig, "next_twigs": [i.text]}
                    return JsonResponse(data)

        else:
            print("request wasn't ajax")
            return render(request, 'index.html')
예제 #10
0
    def save_branch(self,authorname,parent_urlsafe_key,link,content):
        
        userinfo = UserInfo.get_by_username(authorname)    
        if userinfo is None or not self.is_user_info_current(userinfo):
            
            return False, [ 'unauthenticated' ]
        
        branch = Branch()
        branch.authorname = authorname
        
        parent_key = ndb.Key(urlsafe=parent_urlsafe_key)
        parent_branch = parent_key.get()
        
        if parent_branch is None:
            return False, ['parent_branch_not_found']
        
        branch.tree_name = parent_branch.tree_name
        
        tree = Tree.get_by_name(parent_branch.tree_name)
        
        if tree is None:
            return False, ['tree_not_found']

        if tree.moderatorname == authorname or not tree.link_moderator_only:
            branch.link = link
        else:
            branch.link = ""
        
        if tree.moderatorname == authorname or not tree.content_moderator_only:
            branch.content = content
        else:
            branch.content = ""
        
        errors = self.validate_branch(tree, branch,authorname)
                    
#currently there is a db lock on unique links
#eventually we should have a memcache lcok
        
        authored_branch_count = 0
                
        branchs = parent_branch.children()
        
        if tree.single_thread and parent_branch.authorname == authorname:
            errors.append('has_single_thread_parent_branch')
        
        if tree.single_thread and len(branchs) > 0:
            errors.append('has_single_thread_branch')
        
        for branch_branch in branchs:
            if branch_branch.link == branch.link:
                errors.append('has_identical_link')
            if branch_branch.authorname == authorname:
                authored_branch_count += 1
        
        if tree.branch_max > 0 and tree.branch_max <= authored_branch_count:
            errors.append('has_branches')
        
        if len(errors) == 0:
            branch.revision = 0
            branch.parent_branch = parent_key
            branch.parent_branch_authorname = parent_branch.authorname
            branch.put()
            self.create_branch_version(branch)
            
            parent_branch.append_child(branch)
            
            notification = Notification()
            notification.from_username = branch.authorname
            if branch.authorname != parent_branch.authorname:
                notification.to_username = parent_branch.authorname
            notification.notification_type = 'new_branch'
            notification.branch = branch.key
            notification.branch_link = branch.link
            notification.tree_name = branch.tree_name
            notification.put()
            
            return True, branch
        else:
            return False, errors
예제 #11
0
    def save_tree(self,tree_dict):
        
        try:
            tree_dict = self.merged_tree(tree_dict)
        except:
            return False, ['invalid_parameters']
            
        #tree_name,moderatorname,conventions,root_branch_link,root_branch_content
        
        if tree_dict['moderatorname'] is None:
            return False, ['unauthenticated','no_moderator']
        
        if tree_dict['tree_name'] is None:
            return False, ['empty_name']
        
        author_info = UserInfo.get_by_username(tree_dict['moderatorname'])
        
        if author_info is None:
            return False, ['unauthenticated','moderator_not_found']
        
        if not self.is_user_info_current(author_info):
            return False, ['unauthenticated','moderator_not_current']
        
        if author_info.username is None:
            return False, ['invalid_user']
        
        errors = []
        
        if tree_dict['content_max'] < 16:
            errors.append('min_content_max')
            
        if tree_dict['link_max'] < 16:
            errors.append('min_link_max')
            
        if len(tree_dict['link_prompt']) > tree_dict['link_max']:
            errors.append('link_prompt_too_large')
            
        if len(tree_dict['content_prompt']) > tree_dict['content_max']:
            errors.append('content_prompt_too_large')
        
        tree_key = Tree.create_key(tree_dict['tree_name'])
        
        empty_name = tree_dict['tree_name'] is None or len(tree_dict['tree_name']) == 0
        
        if empty_name:
            errors.append('empty_name')
        else:
            match = re.search(r'^[\d\w_\-]+$', tree_dict['tree_name'])
            isvalid = match and 4 <= len(tree_dict['tree_name']) and len(tree_dict['tree_name']) <= 20;
            if not isvalid:
                errors.append('invalid_name')
        
        branch = Branch(id=tree_dict['tree_name'])
        branch.authorname = tree_dict['moderatorname']
        branch.link = tree_dict['root_branch_link']
        branch.content = tree_dict['root_branch_content']
        branch.tree_name = tree_dict['tree_name']
        
        if branch.link == None or len(branch.link) == 0:
            errors.append('empty_root_branch_link')
        
        if branch.content == None or len(branch.content) == 0:
            errors.append('empty_root_branch_content')
        
#let the user complete the other validation before trying to create the tree        
        if len(errors) != 0:
            return False, errors
        
        
        tree = tree_key.get();
        
        if tree:
            errors.append('tree_exists')
        
        if len(errors) == 0:
            #if two users enter identical information at the same time, then
            #whoever gets it second is the winner
            tree = Tree(id=tree_dict['tree_name'].lower(),name=tree_dict['tree_name'])
            tree.moderatorname = tree_dict['moderatorname']
            tree.conventions = tree_dict['conventions']
            
            tree.link_moderator_only = tree_dict['link_moderator_only']
            tree.link_max = tree_dict['link_max']
            tree.link_prompt = tree_dict['link_prompt']
            
            tree.content_moderator_only = tree_dict['content_moderator_only']
            tree.content_max = tree_dict['content_max']
            tree.content_prompt = tree_dict['content_prompt']
            
            tree.single_thread = tree_dict['single_thread']
            
            tree.branch_max = tree_dict['branch_max']
            
            branch.put()
            tree.put()
        
            notification = Notification()
            notification.from_username = tree.moderatorname
            #only set the to_username when a different user is performing the action
            notification.notification_type = 'new_tree'
            notification.tree_name = tree_dict['tree_name']
            notification.put()

        
        if len(errors) == 0:
            return True, tree
        else:
            return False, errors
예제 #12
0
 def execute(id):
     return Branch(id=id, name='some branch', key_name='some-branch').put()