def add_ind_to_col(request, username): global message if request.method == 'POST': if request.user.is_authenticated(): u1 = User.objects.get(username=username) u = User.objects.get(id=u1.id) json_data = json.loads(request.body) col = json_data['userCollection'] ind = json_data['id'] c = Collection.objects.get(id=col) collection_name = c.name #print collection_name itc = Collection_Individual(collection=c, individual_id=ind, added_from=c, from_user=u, date_added=datetime.datetime.now()) itc.save() #Agregar activity stream activity_stream = Activity_stream() usr = request.user.username activity_stream.activity("person", "save", "individual to collection", usr) #Agregar relacion entre individuo y coleccion en la red de grafos collection = GraphCollection() collection_result = collection.get_collection(collection_name) individual = Graph_Individual() individual_result = individual.get_node(ind) nodo1 = node(collection_result[0][0]) nodo2 = node(individual_result[0][0]) relation = Relations() relation.has(nodo1, nodo2) message = "Individual is now added to this collection!" else: message = "No username in evoart!" print "YYYYYYYYYYYYYYY" print col print ind print message data = ({'collection': col, 'individual': ind, 'message': message}) datar = json.dumps(data) return HttpResponse(datar, content_type='application/json')
def get_collection(request, username, collection=None): if request.user.is_authenticated(): print "mememememememememmememememem" print username #REFACTOR GET_FRIENDS face = FacebookSession.objects.get(uid=request.user.username) friends = face.query("me", connection_type="friends", fields='name,installed') # Mejor con FQL app_friends = [f for f in friends['data'] if f.has_key('installed')] face_owner = FacebookSession.objects.get(uid=username) url = 'https://graph.facebook.com/%s?fields=name' % username owner = face_owner.query("me", fields='name') #owner = json.load(urllib.urlopen(url)) print username, owner #r = redis.Redis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB) #r = redis.StrictRedis(host='localhost', port=6379, db=0) from lib.store import redis r = redis if collection: inds_psql = Collection.objects.get(user_collection__user__username=username, id=collection).individuals.all() collection_obj = Collection.objects.get(id=collection) else: collections = Collection.objects.filter(user_collection__user__username=username, visibility='PU') lists_of_inds = [ind for ind in [col.individuals.all() for col in collections]] inds_psql = list(itertools.chain.from_iterable(lists_of_inds)) collection_obj = None inds = [{"id": r["id"], "chromosome": r["chromosome"]} for r in [ast.literal_eval(i) for i in [r.get(ind_.individual_id) for ind_ in inds_psql] if i ] ] #Agreagar activity stream activity_stream = Activity_stream() usr = request.user.username activity_stream.activity("person", "open", "open a collection", usr) #inds = [ (i["id"], i["chromosome"]) for i in [ r.get(ind_.individual_id) for ind_ in inds_psql ] if i ] j = json.dumps(inds) return render_to_response('collection.html', {'static_server': 'http://evospace.org/prototype/', 'api_server': 'http://app.evospace.org', 'individualsjs': j, 'individuals': inds, 'collection_obj': collection_obj, "friends": app_friends, 'owner': owner }, context_instance=RequestContext(request)) else: return HttpResponse('noup')
def get_user_collections(request, username): if User.objects.get(username=username): u1 = User.objects.get(username=username) u_id = u1.id uc = Collection.objects.all().filter(user_collection__user_id__exact=u_id) jd = {'collections': [{'id': col.id, 'name': col.name} for col in uc]} j = json.dumps(jd) #Agreagar activity stream activity_stream = Activity_stream() usr = request.user.username activity_stream.activity("person", "open", "open a collection", usr) return HttpResponse(j, mimetype='application/json')
def get_user_collections(request, username): if User.objects.get(username=username): u1 = User.objects.get(username=username) u_id = u1.id uc = Collection.objects.all().filter( user_collection__user_id__exact=u_id) jd = {'collections': [{'id': col.id, 'name': col.name} for col in uc]} j = json.dumps(jd) #Agreagar activity stream activity_stream = Activity_stream() usr = request.user.username activity_stream.activity("person", "open", "open a collection", usr) return HttpResponse(j, content_type='application/json')
def evospace(request): if request.method == 'POST': population = Population(popName) #print 'Raw Data___: "%s"' % request.body #print type(request.body) json_data = json.loads(request.body) method = json_data["method"] params = json_data["params"] id = json_data["id"] if method == "initialize": result = population.initialize() data = json.dumps({"result": result, "error": None, "id": id}) print data return HttpResponse(data, mimetype='application/javascript') elif method == "getSample": #Auto ReInsert if population.read_sample_queue_len() >= REINSERT_THRESHOLD: population.respawn(5) result = population.get_sample(params[0]) if result: data = json.dumps({"result": result, "error": None, "id": id}) else: data = json.dumps({"result": None, "error": {"code": -32601, "message": "EvoSpace empty"}, "id": id}) return HttpResponse(data, mimetype='application/json') elif method == "read_pop_keys": result = population.read_pop_keys() if result: data = json.dumps({"result": result, "error": None, "id": id}) else: data = json.dumps({"result": None, "error": {"code": -32601, "message": "EvoSpace empty"}, "id": id}) return HttpResponse(data, mimetype='application/json') elif method == "read_sample_queue": result = population.read_sample_queue() if result: data = json.dumps({"result": result, "error": None, "id": id}) else: data = json.dumps({"result": None, "error": {"code": -32601, "message": "EvoSpace empty"}, "id": id}) return HttpResponse(data, mimetype='application/json') elif method == "putSample": #Cada EVOLUTION_INTERVAL evoluciona print "##################" if not population.get_returned_counter() % EVOLUTION_INTERVAL: try: print "Evolucionando" evolve_Tournament() except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() print e.message traceback.print_tb(exc_traceback, limit=20, file=sys.stdout) pass population.put_sample(params[0]) #Aqui se construye el grafo con el individuo if request.user.is_authenticated(): usr = request.user.username first_name = request.user.first_name #last_name = request.user.last_name name = first_name nodo = Nodo() person = Person() person_result = person.get_person(name) activity_stream = Activity_stream() #print u print "=========Parametros===========" print params[0] usrLastDate=str(usr_last_date(params[0]['sample'][0]['fitness'])) print usrLastDate usr_date_key = usr + ":" + usrLastDate print usr_date_key print params[0]['sample'][0]['fitness'][usr_date_key] rate = params[0]['sample'][0]['fitness'][usr_date_key] if params[0]["individuals_with_like"]: for item in params[0]["individuals_with_like"]: id = item print id individual_node = Graph_Individual() print "prueba ", params[0]["individuals_with_like"] # Verificar si el nodo individual existe con status last individual_node_exist = individual_node.get_node(id) if person_result: nodo1 = node(person_result[0][0]) if individual_node_exist: # si la lista esta vacia quiere decir que no existe nodo2 = node(individual_node_exist[0][0]) relation = Relations() relation.likes(nodo1,nodo2,rate) #request.user.username in k #Agreagando Activity stream para el verbo like activity_stream.activity("person", "like", "evaluate", usr) print "=========Parametros===========" else: print "Usuario anonimo" return HttpResponse(json.dumps("Success"), mimetype='application/json') elif method == "init_pop": data = init_pop(populationSize=params[0]) return HttpResponse(json.dumps("Success"), mimetype='application/javascript') elif method == "respawn": data = population.respawn(n=params[0]) return HttpResponse(json.dumps("Success"), mimetype='application/javascript') elif method == "put_individual": print "params", params[0] population.put_individual(**params[0]) data = json.dumps({"result": None, "error": None, "id": id}) return HttpResponse(data, mimetype='application/json') else: return HttpResponse("ajax & post please", mimetype='text')
def add_collection(request, username): global message errors = [] if request.method == 'POST': #print "Estas en add collections" #users=User.objects.all(); #u1=User.objects.get(username=username) #u=users[0] #print request.POST json_data = json.loads(request.body) n = json_data["name"] d = json_data["description"] v = json_data["option"] #print n c = Collection(name=n, description=d, creation_date=datetime.datetime.now(), visibility=v) c.save() #Agregar nodo Coleccion a la red de grafos nodo_collection = Nodo() nodo_collection.create_nodo(element_type="Collection", name=n, description=d, visibility=v) print "Salvaste colleccion" #c_id=Collection.objects.latest('id') #c_id=c_id.id #u_id=u1.id #if User.objects.get(id=u_id) and Collection.objects.get(id=c_id): #u=User.objects.get(id=u_id) #c=Collection.objects.get(id=c_id) u=request.user.last_name #print u uc = User_Collection(user=request.user, collection=c, role="O", status="PU") uc.save() #Activity stream activity_stream = Activity_stream() usr = request.user.username activity_stream.activity("person", "save", "new collection", usr) #Relacionar coleccion con el usuario firstName = request.user.first_name #lastName = request.user.last_name name = firstName person = Person() person_result = person.get_person(name) collection = GraphCollection() collection_result = collection.get_collection(n) nodo1 = node(person_result[0][0]) nodo2 = node(collection_result[0][0]) relation = Relations() relation.has(nodo1, nodo2) message = "You are now linked to this collection!" #else: # message= "Sorry there is no collection or user" #add_user_collection(id,c_id) #col= Collection.objects.all() data = ({'name': n, 'description': d, 'visibility': v, 'message': message}) datar = json.dumps(data) print datar return HttpResponse(datar, mimetype='application/json')
def get_collection(request, username, collection=None): if request.user.is_authenticated(): #REFACTOR GET_FRIENDS face = FacebookSession.objects.get(uid=request.user.username) friends = face.query("me", connection_type="friends", fields='name,installed') # Mejor con FQL app_friends = [f for f in friends['data'] if f.has_key('installed')] face_owner = FacebookSession.objects.get(uid=username) url = 'https://graph.facebook.com/%s?fields=name' % username owner = face_owner.query("me", fields='name') #owner = json.load(urllib.urlopen(url)) print username, owner #r = redis.Redis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB) #r = redis.StrictRedis(host='localhost', port=6379, db=0) r = redis if collection: inds_psql = Collection.objects.get( user_collection__user__username=username, id=collection).individuals.all() collection_obj = Collection.objects.get(id=collection) else: collections = Collection.objects.filter( user_collection__user__username=username, visibility='PU') lists_of_inds = [ ind for ind in [col.individuals.all() for col in collections] ] inds_psql = list(itertools.chain.from_iterable(lists_of_inds)) collection_obj = None inds = [{ "id": r["id"], "chromosome": r["chromosome"] } for r in [ ast.literal_eval(i) for i in [r.get(ind_.individual_id) for ind_ in inds_psql] if i ]] #Agreagar activity stream activity_stream = Activity_stream() usr = request.user.username activity_stream.activity("person", "open", "open a collection", usr) #inds = [ (i["id"], i["chromosome"]) for i in [ r.get(ind_.individual_id) for ind_ in inds_psql ] if i ] j = json.dumps(inds) return render_to_response('collection.html', { 'static_server': 'http://evospace.org/prototype/', 'api_server': 'http://app.evospace.org', 'individualsjs': j, 'individuals': inds, 'collection_obj': collection_obj, "friends": app_friends, 'owner': owner }, context_instance=RequestContext(request)) else: return HttpResponse('noup')
def add_collection(request, username): global message errors = [] if request.method == 'POST': #print "Estas en add collections" #users=User.objects.all(); #u1=User.objects.get(username=username) #u=users[0] #print request.POST json_data = json.loads(request.body) n = json_data["name"] d = json_data["description"] v = json_data["option"] print n c = Collection(name=n, description=d, creation_date=datetime.datetime.now(), visibility=v) c.save() #Agregar nodo Coleccion a la red de grafos nodo_collection = Nodo() nodo_collection.create_nodo(element_type="Collection", name=n, description=d, visibility=v) print "Salvaste colleccion" #c_id=Collection.objects.latest('id') #c_id=c_id.id #u_id=u1.id #if User.objects.get(id=u_id) and Collection.objects.get(id=c_id): #u=User.objects.get(id=u_id) #c=Collection.objects.get(id=c_id) u = request.user.last_name #print u uc = User_Collection(user=request.user, collection=c, role="O", status="PU") uc.save() #Activity stream activity_stream = Activity_stream() usr = request.user.username activity_stream.activity("person", "save", "new collection", usr) #Relacionar coleccion con el usuario firstName = request.user.first_name lastName = request.user.last_name name = firstName + " " + lastName person = Person() person_result = person.get_person(name) collection = GraphCollection() collection_result = collection.get_collection(n) nodo1 = node(person_result[0][0]) nodo2 = node(collection_result[0][0]) relation = Relations() relation.has(nodo1, nodo2) message = "You are now linked to this collection!" #else: # message= "Sorry there is no collection or user" #add_user_collection(id,c_id) #col= Collection.objects.all() data = ({ 'name': n, 'description': d, 'visibility': v, 'message': message }) datar = json.dumps(data) print datar return HttpResponse(datar, content_type='application/json')
def evospace(request): if request.method == 'POST': population = Population(popName) #print 'Raw Data___: "%s"' % request.body #print type(request.body) json_data = json.loads(request.body) method = json_data["method"] params = json_data["params"] id = json_data["id"] if method == "initialize": result = population.initialize() data = json.dumps({"result": result, "error": None, "id": id}) print data return HttpResponse(data, mimetype='application/javascript') elif method == "getSample": #Auto ReInsert if population.read_sample_queue_len() >= REINSERT_THRESHOLD: population.respawn(5) result = population.get_sample(params[0]) if result: data = json.dumps({"result": result, "error": None, "id": id}) else: data = json.dumps({ "result": None, "error": { "code": -32601, "message": "EvoSpace empty" }, "id": id }) return HttpResponse(data, mimetype='application/json') elif method == "read_pop_keys": result = population.read_pop_keys() if result: data = json.dumps({"result": result, "error": None, "id": id}) else: data = json.dumps({ "result": None, "error": { "code": -32601, "message": "EvoSpace empty" }, "id": id }) return HttpResponse(data, mimetype='application/json') elif method == "read_sample_queue": result = population.read_sample_queue() if result: data = json.dumps({"result": result, "error": None, "id": id}) else: data = json.dumps({ "result": None, "error": { "code": -32601, "message": "EvoSpace empty" }, "id": id }) return HttpResponse(data, mimetype='application/json') elif method == "putSample": #Cada EVOLUTION_INTERVAL evoluciona print "##################" if not population.get_returned_counter() % EVOLUTION_INTERVAL: try: print "Evolucionando" evolve_Tournament() except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() print e.message traceback.print_tb(exc_traceback, limit=20, file=sys.stdout) pass population.put_sample(params[0]) #Aqui se va armar la machaca del individuo if request.user.is_authenticated(): usr = request.user.username first_name = request.user.first_name last_name = request.user.last_name name = first_name + " " + last_name nodo = Nodo() person = Person() person_result = person.get_person(name) activity_stream = Activity_stream() #print u print "=========Parametros===========" print params[0] if params[0]["individuals_with_like"]: for item in params[0]["individuals_with_like"]: id = item print id individual_node = Graph_Individual() print "prueba ", params[0]["individuals_with_like"] # Verificar si el nodo individual existe con status last individual_node_exist = individual_node.get_node(id) if person_result: nodo1 = node(person_result[0][0]) if individual_node_exist: # si la lista esta vacia quiere decir que no existe nodo2 = node(individual_node_exist[0][0]) relation = Relations() relation.likes(nodo1, nodo2) #request.user.username in k #Agreagando Activity stream para el verbo like activity_stream.activity("person", "like", "evaluate", usr) #Curret experience calculation current_experience(request) print "=========Parametros===========" else: print "Usuario anonimo" return HttpResponse(json.dumps("Success"), mimetype='application/json') elif method == "init_pop": data = init_pop(populationSize=params[0]) return HttpResponse(json.dumps("Success"), mimetype='application/javascript') elif method == "respawn": data = population.respawn(n=params[0]) return HttpResponse(json.dumps("Success"), mimetype='application/javascript') elif method == "put_individual": print "params", params[0] population.put_individual(**params[0]) data = json.dumps({"result": None, "error": None, "id": id}) return HttpResponse(data, mimetype='application/json') else: return HttpResponse("ajax & post please", mimetype='text')
class FacebookBackend: def authenticate(self, token=None): print token facebook_session = models.FacebookSession.objects.get( access_token=token, ) profile = facebook_session.query('me') print "^^^^^^^^^PROFILE^^^^^^^^^^^^" try: user = auth_models.User.objects.get(username=profile['id']) except auth_models.User.DoesNotExist, e: user = auth_models.User(username=profile['id']) user.set_unusable_password() if 'username' in profile: user.email = profile['username'] else: user.email = profile['id'] user.first_name = profile['first_name'] user.last_name = profile['last_name'] user.save() #Agregando Activity_stream #activity_stream = Activity_stream() #Agregando nodo usuario, creado por Christian "Nuevo" usr = profile['id'] email = profile['name'] first_name = profile['first_name'] last_name = profile['last_name'] full_name = first_name + " " + last_name print '****************' nodo = Nodo() person = Person() person_result = person.get_person(full_name) print usr, email, full_name print "if person_result es vacio, entonce hay que crearlo" print person_result if not person_result: print "creando nodo" nodo.create_nodo(element_type="person", id=usr, email=email, name=full_name) print "creo nodo" #Agregando Activity_stream activity_stream = Activity_stream() activity_stream.activity("person", "join", "log in", usr) try: models.FacebookSession.objects.get(uid=profile['id']).delete() except models.FacebookSession.DoesNotExist, e: pass