Example #1
0
def add_relationship(request):
    if request.method != "POST":
        return HttpResponseForbidden("Method not allowed")
    next = "/"
    if request.GET.has_key("next"):
        next = request.GET["next"]

    form = RelationshipForm(request.POST)

    if not form.is_valid():
        # add error
        return redirect(next)

    username = form.cleaned_data["user"]

    followed = get_object_or_404(User, username=username).get_profile()

    user = request.user.get_profile()

    if user != followed:
        m1 = Relationship(origin=user, destination=followed, relationship_type=1)
        m1.save()
    else:
        pass
        # add error
    return redirect(next)
Example #2
0
 def compute_relationship(self, article):
     kw_list1 = article.keywords.split(",")
     for a in Article.objects.all():
         kw_list2 = a.keywords.split(",")
         score = self.calculate_relationship(kw_list1, kw_list2)
         r = Relationship(id1=article.id, id2=a.id, score=score)
         r.save()
Example #3
0
def add_relation(request):
    feature1 = request.GET.get("feature1", None)
    feature2 = request.GET.get("feature2", None)
    relation = request.GET.get("relation", None)
    if feature1 == None or feature2 == None or relation == None:
        return render_to_json_response({"error": "bad request"})

    if not request.user.is_staff:
        return render_to_json_response(
            {"error": "insufficient permissions error. try logging in again? are you staff / admin?"}
        )

    feature1 = get_object_or_404_json(Feature, pk=feature1)
    feature2 = get_object_or_404_json(Feature, pk=feature2)
    verb = rel_obj = None
    try:
        rel_obj = Relationship.objects.get(feature1=feature1, feature2=feature2)
        verb = "deleted"
    except ObjectDoesNotExist:
        rel_obj = Relationship(feature1=feature1, feature2=feature2, relationship_type=relation)
        verb = "created"
    if relation == "":
        if verb == "deleted":
            rel_obj.delete()
            if relation == "conflates":
                feature2.is_primary = True
                feature2.save()
        else:
            return render_to_json_response({"error": "relation is already deleted"})
    else:
        rel_obj.save()
        if relation == "conflates":
            feature2.is_primary = False
            feature2.save()
    return render_to_json_response({"success": "relation %s successfully." % verb})
Example #4
0
 def compute_relationship(self, article):
     kw_list1 = article.keywords.split(",")
     for a in Article.objects.all():
         kw_list2 = a.keywords.split(",")
         score = self.calculate_relationship(kw_list1, kw_list2)
         r = Relationship(id1=article.id, id2=a.id, score=score)
         r.save()
Example #5
0
def user_unfollow(username):
    user = get_object_or_404(User, User.username == username)
    Relationship.delete().where(
        Relationship.from_user == auth.get_logged_in_user(),
        Relationship.to_user == user,
    ).execute()
    flash('You are no longer following %s' % user.username)
    return redirect(url_for('user_detail', username=user.username))
Example #6
0
def user_follow(username):
    user = get_object_or_404(User, User.username==username)
    Relationship.get_or_create(
        from_user=auth.get_logged_in_user(),
        to_user=user,
    )
    flash('You are now following %s' % user.username)
    return redirect(url_for('user_detail', username=user.username))
Example #7
0
def user_unfollow(username):
    user = get_object_or_404(User, User.username==username)
    Relationship.delete().where(
        Relationship.from_user==auth.get_logged_in_user(),
        Relationship.to_user==user,
    ).execute()
    flash('You are no longer following %s' % user.username)
    return redirect(url_for('user_detail', username=user.username))
Example #8
0
def user_follow(username):
    user = get_object_or_404(User, User.username == username)
    Relationship.get_or_create(
        from_user=auth.get_logged_in_user(),
        to_user=user,
    )
    flash('You are now following %s' % user.username)
    return redirect(url_for('user_detail', username=user.username))
Example #9
0
def create_tables():
    from models import User, Message, Note, Relationship, City, Pinche

    # User.create_table()
    Relationship.create_table()
    Note.create_table()
    Message.create_table()
    City.create_table()
    Pinche.create_table()
Example #10
0
File: app.py Project: lite/pinche
def create_tables():
    from models import User, Message, Note, Relationship, City, Pinche
    
    # User.create_table()
    Relationship.create_table()
    Note.create_table()
    Message.create_table()
    City.create_table()
    Pinche.create_table()
 def setUp(self):
     
     #create the client to be used
     self.client = Client()
     
     #create users
     self.user1 = User.objects.create_user('user1',
                                           '*****@*****.**',
                                           'user1')
     self.user2 = User.objects.create_user('user2',
                                           '*****@*****.**',
                                           'user2')
     self.user3 = User.objects.create_user('user3',
                                           '*****@*****.**',
                                           'user3')    
     self.user4 = User.objects.create_user('user4',
                                           '*****@*****.**',
                                           'user4')
     self.user5 = User.objects.create_user('user5',
                                           '*****@*****.**',
                                           'user5')
     self.user6 = User.objects.create_user('user6',
                                           '*****@*****.**',
                                           'user6')
     self.user7 = User.objects.create_user('user7',
                                           '',
                                           'user7')
     
     #create a group
     self.group1 = Group(name='@family')
     self.group1.save()
     self.group2 = Group(name="data_view_permission")
     self.group2.save()
     permission = Permission.objects.get(codename="data_view")
     self.group2.permissions.add(permission)
     
     #create a relationship
     r = Relationship(initial_user = self.user5,
                      group = self.group1,
                      target_user = self.user6)
     r.save()
     r = Relationship(initial_user = self.user5,
                      group = self.group1,
                      target_user = self.user7)
     r.save()
     r = Relationship(initial_user = self.user6,
                      group = self.group1,
                      target_user = self.user7)
     r.save()
     
     
     #give users permissions
     self.user5.groups.add(self.group2)
     
     #create values for users profiles
     self.user1.first_name = "First1"
     self.user1.last_name = "Last1"
     self.user1.email = "*****@*****.**"
     self.user1.save()
Example #12
0
def bookmark_add():
    error = {}
    bookmark = {}
    user = auth.get_logged_in_user()
    if request.method == 'POST':
        if not request.form['url']:
            error['url'] = u'书签的网址不能为空'
        if not request.form['url'].startswith('http://') and not request.form['url'].startswith('https://'):
            request.form['url'] = ''.join(['http://', request.form['url']])
        if not error:
            try:
                bookmark = Bookmark.select().where(Bookmark.user == user,
                                        Bookmark.url == request.form['url']
                ).get()
            except Bookmark.DoesNotExist:
                try:
                    db.database.set_autocommit(False)
                    
                    bookmark = Bookmark.create(
                        user=user,
                        url=request.form['url'],
                        title=request.form['title']
                    )
                    bookmark.fetch_image()
                    bookmark.save()

                    tagnames = re.split('\s+', request.form['tags'].strip())
                    # marksure request.form['tags'] not a empty string
                    if tagnames[0]:
                        for tagname in tagnames:
                            if not Tag.select().where(Tag.user == user,
                                                      Tag.name == tagname
                                                     ).exists():
                                tag = Tag.create(user=user, name=tagname)
                                tag.save()

                                relationship = Relationship.create(
                                    user=user,
                                    tag=tag,
                                    bookmark=bookmark)
                                relationship.save()
                except Exception as e:
                    db.database.rollback()
                    flash(u'对不起,服务器太累了,刚罢工了一会儿', 'error')
                else:
                    try:
                        db.database.commit()
                    except Exception as e:
                        db.database.rollback()
                        flash(u'对不起,服务器太累了,刚罢工了一会儿', 'error')
                finally:
                    db.database.set_autocommit(True)

                if not get_flashed_messages():
                    flash(u'你已经成功添加一个书签', 'success')
                    return redirect(url_for('bookmark'))
            else:
                flash(Markup(u'书签已经存在,也许你想要<a href="' + url_for('bookmark_edit', id=bookmark.id) + u'">编辑</a>此书签'), 'info')
    
    return render_template('bookmark_add.html', error=error, form=request.form, user=user, bookmark=bookmark)
Example #13
0
def ParseGraphLocal(data, image, verbose=False):
    global count_skips
    objects = []
    object_map = {}
    relationships = []
    attributes = []

    for obj in data['objects']:
        object_map, o_ = MapObject(object_map, obj)
        objects.append(o_)
    for rel in data['relationships']:
        if rel['subject_id'] in object_map and rel['object_id'] in object_map:
            object_map, s = MapObject(object_map,
                                      {'object_id': rel['subject_id']})
            v = rel['predicate']
            object_map, o = MapObject(object_map,
                                      {'object_id': rel['object_id']})
            rid = rel['relationship_id']
            relationships.append(Relationship(rid, s, v, o, rel['synsets']))
        else:
            # Skip this relationship if we don't have the subject and object in
            #   the object_map for this scene graph. Some data is missing in this way.
            count_skips[0] += 1
    if 'attributes' in data:
        for attr in data['attributes']:
            a = attr['attribute']
            if a['object_id'] in object_map:
                attributes.append(
                    Attribute(attr['attribute_id'], a['object_id'], a['names'],
                              a['synsets']))
            else:
                count_skips[1] += 1
    if verbose:
        print 'Skipped {} rels, {} attrs total'.format(*count_skips)
    return Graph(image, objects, relationships, attributes)
Example #14
0
def ParseGraph(data, image):
    objects = []
    object_map = {}
    relationships = []
    attributes = []
    # Create the Objects
    for obj in data['bounding_boxes']:
        names = []
        synsets = []
        for s in obj['boxed_objects']:
            names.append(s['name'])
            synsets.append(ParseSynset(s['object_canon']))
            object_ = Object(obj['id'], obj['x'], obj['y'], obj['width'],
                             obj['height'], names, synsets)
            object_map[obj['id']] = object_
        objects.append(object_)
    # Create the Relationships
    for rel in data['relationships']:
        relationships.append(Relationship(rel['id'], object_map[rel['subject']], \
            rel['predicate'], object_map[rel['object']], ParseSynset(rel['relationship_canon'])))
    # Create the Attributes
    for atr in data['attributes']:
        attributes.append(Attribute(atr['id'], object_map[atr['subject']], \
            atr['attribute'], ParseSynset(atr['attribute_canon'])))
    return Graph(image, objects, relationships, attributes)
Example #15
0
def follow(username):
    try:
        user = User.get(User.username**username)
    except DoesNotExist:
        abort(406)
    else:
        try:
            Relationship.get(Relationship.from_user == g.user,
                             Relationship.to_user == user)
        except DoesNotExist:
            Relationship.create(from_user=g.user, to_user=user)
            flash('Followed {}!'.format(user.username))
            return redirect(url_for('user_view', username=user.username))
        else:
            flash('You already followed {}.'.format(user.username))
            return redirect(url_for('user_view', username=user.username))
Example #16
0
def ParseGraphVRD(d):
    image = Image(d['photo_id'], d['filename'], d['width'], d['height'], '',
                  '')

    id2obj = {}
    objs = []
    rels = []
    atrs = []

    for i, o in enumerate(d['objects']):
        b = o['bbox']
        obj = Object(i, b['x'], b['y'], b['w'], b['h'], o['names'], [])
        id2obj[i] = obj
        objs.append(obj)

        for j, a in enumerate(o['attributes']):
            atrs.append(Attribute(j, obj, a['attribute'], []))

    for i, r in enumerate(d['relationships']):
        s = id2obj[r['objects'][0]]
        o = id2obj[r['objects'][1]]
        v = r['relationship']
        rels.append(Relationship(i, s, v, o, []))

    return Graph(image, objs, rels, atrs)
Example #17
0
def find_users_who_took_bribes():
    users_who_took_bribes = set()

    for user in User.select():
        if user.job in ["سازمان بنادر", "گمرک"]:

            if is_user_has_any_deed(user):
                users_who_took_bribes.add(user)

            else:
                for relation in Relationship.select().where(
                    (Relationship.person_1 == user) or (Relationship.person_2 == user)
                ):
                    is_person_1_has_any_deed = is_user_has_any_deed(relation.person_1)
                    is_person_2_has_any_deed = is_user_has_any_deed(relation.person_2)

                    if is_person_1_has_any_deed or is_person_2_has_any_deed:
                        users_who_took_bribes.add(user)
                        break

    for user in users_who_took_bribes:
        print(
            user.first_name,
            user.last_name,
            "with national_id",
            user.national_id,
            "working in",
            user.job,
            "has been took some bribes.",
        )
    print(f"⭕️ Totally {len(users_who_took_bribes)} users has been took bribes.\n")

    return users_who_took_bribes
Example #18
0
def follow(username):
    """Follow user function. Login required.

    :param username:
    :return: redirect()
    """
    try:
        to_user = User.get(User.username**username)
    except User.DoesNotExist:
        abort(404)
    else:
        try:
            Relationship.create(from_user=g.user._get_current_object(),
                                to_user=to_user)
        except Relationship.IntegrityError:
            to_user = User.get(User.username**username)
        else:
            flash("Following {}".format(to_user.username), "success")
    return redirect(url_for('feed', username=to_user.username))
Example #19
0
def unfollow(username):
    """User unfollow function. Login required.

    :param username:
    :return: redirect()
    """
    try:
        to_user = User.get(User.username**username)
    except User.DoesNotExist:
        abort(404)
    else:
        try:
            Relationship.get(from_user=g.user._get_current_object(),
                             to_user=to_user).delete_instance()
        except Relationship.IntegrityError:
            pass
        else:
            flash("Unfollowed {}".format(to_user.username), "success")
    return redirect(url_for('feed', username=to_user.username))
Example #20
0
def add_relation(request):
    feature1 = request.GET.get("feature1", None)
    feature2 = request.GET.get("feature2", None)
    relation = request.GET.get("relation", None)
    if feature1 == None or feature2 == None or relation == None:
        return render_to_json_response({'error': 'bad request'})

    if not request.user.is_staff:
        return render_to_json_response({'error': 'insufficient permissions error. try logging in again? are you staff / admin?'})

    feature1 = get_object_or_404_json(Feature, pk=feature1)
    feature2 = get_object_or_404_json(Feature, pk=feature2)
    verb = rel_obj = None
    try:
        rel_obj = Relationship.objects.get(feature1=feature1, feature2=feature2)
        verb = "deleted"
    except ObjectDoesNotExist:
        rel_obj = Relationship(feature1=feature1, feature2=feature2, relationship_type=relation)
        verb = "created"
    if relation == "":
        if verb == "deleted":
            rel_obj.delete()
            if relation == "conflates":
                feature2.is_primary = True
                feature2.save()
        else:
             return render_to_json_response({'error': 'relation is already deleted'})
    else:
        rel_obj.save()
        if relation == "conflates":
            feature2.is_primary = False
            feature2.save()
    return render_to_json_response({'success': 'relation %s successfully.' % verb})
Example #21
0
def ParseGraphLocal(data, image_id):
    global count_skips
    objects = []
    object_map = {}
    relationships = []
    attributes = []

    for rel in data['relationships']:
        object_map, objects, s = MapObject(object_map, objects, rel['subject'])
        v = rel['predicate']
        object_map, objects, o = MapObject(object_map, objects, rel['object'])
        rid = rel['relationship_id']
        relationships.append(Relationship(rid, s, v, o, rel['synsets']))
    return Graph(image_id, objects, relationships, attributes)
Example #22
0
    def create(self, request, mfileid):

        mfileid_left = mfileid
        mfileid_right = request.POST.get("mfileid", None)
        relationship_name = request.POST.get("name", None)

        if mfileid_right == None:
            response = rc.BAD_REQUEST
            logging.info("Bad Request to relationship create handler %s", request.POST)
            response.write("Invalid Request! No mfileid in POST fields")
            return response
        elif relationship_name == None:
            response = rc.BAD_REQUEST
            logging.info("Bad Request to relationship create handler %s", request.POST)
            response.write("Invalid Request! No name in POST fields")
            return response
        else:
            mfile_left = MFile.objects.get(id=mfileid_left)
            mfile_right = MFile.objects.get(id=mfileid_right)
            relationship = Relationship(entity1=mfile_left,
                                entity2=mfile_right,
                                name=relationship_name)
            relationship.save()
            return relationship
def create_relationship(request, initial_user, relationship_type):
    """ This function creates a realtionship from intial_user with
    relation_type to target user that is in the request.POST payload """
    
    #the user is only allowed to create relationships for him/herself            
    if initial_user != '@me' and request.user.username != initial_user:
        return HttpResponseForbidden("You are not allowed to create this relationship")

    iuser = request.user #should always be @me or the username of @me
    
    gtype = relationship_type
    
    tuser = None
    try:
        if request.META['CONTENT_TYPE'] == 'application/json':
            post_dict = json.loads(request.raw_post_data)
            tuser = User.objects.get(username = post_dict.get('id', None))
        else:
            tuser = User.objects.get(username = request.POST.get('id', None))
            
    except User.DoesNotExist:
        return HttpResponseNotFound("The target user of the relationship was not found")
    
    relationship = Relationship(initial_user = iuser,
                                group = gtype,
                                target_user = tuser)
    
    sid = transaction.savepoint()
    try:
        relationship.save()
        return HttpResponseCreated("The relationship was created")
    except Relationship.DoesNotExist:
        return HttpResponseNotFound("The relationship could not be created")
    except IntegrityError:
        transaction.savepoint_rollback(sid)
        return HttpResponseConflict("This relationship already exists")
Example #24
0
def unfollow(username):
    try:
        user = User.get(User.username**username)
    except DoesNotExist:
        abort(406)
    else:
        try:
            relation = Relationship.get(Relationship.from_user == g.user,
                                        Relationship.to_user == user)
        except DoesNotExist:
            flash('You haven\'t followed {} yet.'.format(user.username))
            return redirect(url_for('user_view', username=user.username))
        else:
            relation.delete_instance()
            flash('Unfollowed {}.'.format(user.username))
            return redirect(url_for('user_view', username=user.username))
Example #25
0
def UpdateRelation(id1, id2, status, action_by):

    try:
        exisit_relation =GetRelation(id1,id2)
        if exisit_relation:
            exisit_relation.status = status
            db.session.commit()
        else:
            relation = Relationship()
            if id1 < id2:
                relation.user1_Id = id1
                relation.user2_Id = id2
            else:
                relation.user1_Id = id2
                relation.user2_Id = id1
            relation.status = status
            relation.action_by = action_by
            db.session.add(relation)
            db.session.commit()
        
        return "relation updated successfully!!"

    except Exception as error:
        return errors.internal_error(error)
Example #26
0
def parse_graph(data, image):
    """
    Helper to parse a Graph object from API data.
    """
    objects = []
    object_map = {}
    relationships = []
    attributes = []

    # Create the Objects
    for obj in data['bounding_boxes']:
        names = []
        synsets = []
        for bbx_obj in obj['boxed_objects']:
            names.append(bbx_obj['name'])
            synsets.append(parse_synset(bbx_obj['object_canon']))
            object_ = Object(obj['id'], obj['x'], obj['y'], obj['width'],
                             obj['height'], names, synsets)
            object_map[obj['id']] = object_
        objects.append(object_)
        pass

    # Create the Relationships
    for rel in data['relationships']:
        relationships.append(
            Relationship(rel['id'], object_map[rel['subject']],
                         rel['predicate'], object_map[rel['object']],
                         parse_synset(rel['relationship_canon'])))
        pass

    # Create the Attributes
    for atr in data['attributes']:
        attributes.append(
            Attribute(atr['id'], object_map[atr['subject']], atr['attribute'],
                      parse_synset(atr['attribute_canon'])))
        pass

    return Graph(image, objects, relationships, attributes)
Example #27
0
def ParseGraphLocal(data, image):
  global count_hit
  global count_miss

  objects = []
  object_map = {}
  relationships = []
  for obj in data['objects']:
    object_map, o_ = MapObject(object_map, obj)
    objects.append(o_)
  for rel in data['relationships']:
    if rel['subject_id'] in object_map and rel['object_id'] in object_map:
      object_map, s = MapObject(object_map, {'object_id': rel['subject_id']})
      v = rel['predicate']
      object_map, o = MapObject(object_map, {'object_id': rel['object_id']})
      rid = rel['relationship_id']
      relationships.append(Relationship(rid, s, v, o, rel['synsets']))
    else:
      count_miss += 1
    if count_miss % 10000 == 1:
      print 'Misses: ', count_miss
      # print 'SKIPPING   s: {}, v: {}, o: {}'.format(rel['subject_id'], rel['relationship_id'], rel['object_id'])
  return Graph(image, objects, relationships, [])
Example #28
0
def bookmark_edit(id):
    user = auth.get_logged_in_user()
    bookmark = {}
    try:
        bookmark = Bookmark.get(Bookmark.id == id)
        bookmark.tags = ' '.join([Tag.get(Tag.id == tagID).name for tagID in [tag.tag for tag in bookmark.Tags]])
    except Bookmark.DoesNotExist:
        flash(u'你要编辑的书签不存在', 'error')
        return redirect(url_for('page_404'))
    
    error = {}
    if request.method == 'POST':
        try:
            bookmark = Bookmark.get(Bookmark.id == request.form['id'])
        except Bookmark.DoesNotExist:
            flash(u'你要编辑的书签不存在', 'error')
            return redirect(url_for('page_404'))
        if not request.form['url']:
            error['url'] = u'书签的网址不能为空'
        if not error:
            try:
                db.database.set_autocommit(False)
                
                # before update image, should remove old version
                if bookmark.url != request.form['url']:
                    bookmark.destory_image()
                    bookmark.url = request.form['url']
                    bookmark.fetch_image()
                
                bookmark.title = request.form['title']
                bookmark.save()
                
                tagnames = re.split('\s+', request.form['tags'].strip())
                # marksure request.form['tags'] not a empty string
                if tagnames[0]:
                    for tagname in tagnames:
                        if not Tag.select().where(Tag.user == user,
                                                      Tag.name == tagname
                                                     ).exists():
                                tag = Tag.create(user=user, name=tagname)
                                tag.save()

                                relationship = Relationship.create(
                                    user=user,
                                    tag=tag,
                                    bookmark=bookmark)
                                relationship.save()
            except Exception as e:
                db.database.rollback()
                flash(u'对不起,服务器太累了,刚罢工了一会儿', 'error')
            else:
                try:
                    db.database.commit()
                except Exception as e:
                    db.database.rollback()
                    flash(u'对不起,服务器太累了,刚罢工了一会儿', 'error')
            finally:
                db.database.set_autocommit(True)

            if not get_flashed_messages():
                flash(u'你刚刚完成一个书签的编辑', 'success')
                return redirect(url_for('bookmark'))

    return render_template('bookmark_edit.html', error=error, form=request.form, bookmark=bookmark, user=user)
Example #29
0
 def get_relationships(self):
     rows = self.database.get_relationships()
     result = []
     for row in rows:
         result.append(Relationship(row))
     return result
Example #30
0
from flask_login import *
from models import User, Question, Relationship
import yaml

db = yaml.load(open("config/db.yaml"))

main_app = Flask(__name__)
main_app.register_blueprint(app)
main_app.secret_key = db['secret']
main_app.config['MONGO_DBNAME'] = "venn_development"
main_app.config['MONGO_URI'] = db["uri"]

mongo = PyMongo(main_app)

login_manager = LoginManager()

login_manager.setup_app(main_app)
login_manager.login_view = "/login"


@login_manager.user_loader
def load_user(userid):
    return User.find_one({'_id':ObjectId(userid)})

with main_app.app_context():
    User.initialize_db(mongo.db)
    Question.initialize_db(mongo.db)
    Relationship.initialize_db(mongo.db)

if __name__ == '__main__':
    main_app.run(debug=True)