예제 #1
0
def main(config_file,mode,distributed):
    config = check_params(config_file)
    if mode in ["Train","train"]:
        train_dataset = Dataset(config["train_params"]["input_path"],config["train_params"]["imsize"])
        if distributed:
            import horovod as hvd
            hvd.init()
            if hvd.rank()==0:
                writer = setup_tensorboard(get_params(config["train_params"],"tensorboard_location","./summary/"))
            train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset, num_replicas=hvd.size(),
                                                                            rank=hvd.rank())

            train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=config["train_params"]["batch_size"],
                                                       sampler=train_sampler, shuffle=True)
            model = ConvLSTM(**config["model_params"])
            optimizer = hvd.DistributedOptimizer(model.optimizer, named_parameters=model.named_parameters())
            hvd.broadcast_parameters(model.state_dict(), root_rank=0)
            train_distributed(model,train_loader,optimizer,config,writer)
        else:
            writer = setup_tensorboard(get_params(config["train_params"], "tensorboard_location", "./summary/"))
            train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=config["train_params"]["batch_size"],
                                                     shuffle = True)
            model = ConvLSTM(**config["model_params"])
            train(model,train_loader,model.optimizer,config,writer)
    elif mode in ["infer","Infer"]:
        model = ConvLSTM(**config["model_params"])
        model.load_state_dict(config["infer_params"]["model_save_path"])
        output_file = open(config["infer_params"]["output_path"])
예제 #2
0
 def get_weights(self):
     """
     Collect the parameters from user embedding, item embedding, and recommendation modules
     """
     # User embedding parameters
     u_emb_params = get_params(self.user_embedding.parameters())
     # Item embedding parameters
     i_emb_params = get_params(self.item_embedding.parameters())
     # Recommendation model parameters
     rec_params = get_params(self.rec_model.parameters())
     return u_emb_params, i_emb_params, rec_params
예제 #3
0
    def post(self, request):
        """
        POST
        Confirma y crea los tfgs devolviendo los errores
        :param request:
        :return :

        """
        try:
            params = utils.get_params(request)
            self.logger.info('INICIO WS - UPLOADFILECONFIRMVIEW POST del usuario: %s con parametros: %s' % (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
            if request.user.has_perm('tfgs.tfg.masivos') or request.user.is_admin:
                model = get_model(params.get('model'))
                load_tfgs = SUBIDAS.get(params.get('model'))()
                resul = load_tfgs.upload_file_confirm(params['list_tfg'])
                if resul['status']:
                    resul_status = status.HTTP_200_OK
                else:
                    resul = dict(message=resul['message'])
                    resul_status = status.HTTP_400_BAD_REQUEST
            else:
                resul = dict(message="Sin privilegios")
                resul_status = status.HTTP_405_METHOD_NOT_ALLOWED
            self.logger.info('FIN WS - UPLOADFILECONFIRMVIEW POST del usuario: %s con resultado: %s' % (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=resul_status)
        except Exception as e:
            resul = dict(status=False, message="Error en la llamada")
            self.logger.critical('UPLOADFILECONFIRMVIEW POST: %s %s' % (resul, e))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #4
0
 def put(self, request):
     try:
         params = utils.get_params(request)
         self.logger.info('INICIO WS - TFGASIGVIEWCONVOCATORIA PUT del usuario: %s con parametros: %s' %
                          (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
         if request.user.has_perm('tfgs.tfg_asig.change') or request.user.is_admin:
             tfg = Tfg.objects.get(titulo=params.get('tfg'))
             tfg_asig = Tfg_Asig.objects.get(tfg=tfg)
             serializer = self.serializer_class(tfg)
             params = json.loads(params.get('datos'))
             resul = serializer.update(tfg_asig, params)
             if resul['status']:
                 resul = utils.to_dict(resul)
                 resul_status = status.HTTP_200_OK
             else:
                 resul = dict(message=resul['message'])
                 resul_status = status.HTTP_400_BAD_REQUEST
         else:
             resul = dict(message="Sin privilegios")
             resul_status = status.HTTP_400_BAD_REQUEST
         self.logger.info('FIN WS - TFGASIGVIEWCONVOCATORIA PUT del usuario: %s con resultado: %s' %
                          (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
         return Response(resul, status=resul_status)
     except Tfg.DoesNotExist:
         resul = dict(message="El tfg indicado no existe")
         self.logger.error('TFGASIGVIEWCONVOCATORIA PUT del usuario: %s con resultado: %s' %
                           (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
         return Response(resul, status=status.HTTP_400_BAD_REQUEST)
     except Exception as e:
         resul = dict(status=False, message="Error en la llamada")
         self.logger.critical('TFGASIGVIEWCONVOCATORIA PUT: %s %s' % (resul, e))
         return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #5
0
    def delete(self, request):
        """
        Eliminar un subtipo de evento
        :param request:
        :return :
        """
        try:
            params = utils.get_params(request)
            self.logger.info('INICIO WS - SUBTIPOEVENTOSVIEW DELETE del usuario: %s con params: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
            if request.user.is_admin:
                subtipo = SubTipo_Evento.objects.get(codigo=params.get('codigo'))
                serializer = self.serializer_class(subtipo)
                resul = serializer.delete(subtipo)
            else:
                resul = dict(status=False, message="Parametros incorrectos")
            self.logger.critical('FIN WS - SUBTIPOEVENTOSVIEW DELETE del usuario: %s con resultado: %s' %
                                 (request.user.email if hasattr(request.user, 'email') else request.user.username,
                                  resul))
            return Response(resul)

        except SubTipo_Evento.DoesNotExist:
            resul = dict(status=False, message="La titulacion indicada no existe")
            self.logger.error('INICIO WS - SUBTIPOEVENTOSVIEW DELETE del usuario: %s con resultado: %s' %
                              (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            resul = dict(status=False, message="Error en la llamada")
            self.logger.critical('INICIO WS - SUBTIPOEVENTOSVIEW DELETE del usuario: %s con resultado: %s %s' %
                                 (request.user.email if hasattr(request.user, 'email') else request.user.username,
                                  resul, e))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #6
0
def grad_check_tf_wb(num_samples, h_sizes):
	tf.enable_eager_execution()
	(x_set, y_set), _ = gen_samples(num_samples)
	layer_sizes = gen_layer_sizes(len(h_sizes)+1, 1, 1, h_sizes)
	mus_W, rhos_W, mus_b, rhos_b = init_distributions(layer_sizes)
	eps_W, eps_b = get_eps(layer_sizes)
	W, b, sigmas_W, sigmas_b = get_params(mus_W, rhos_W, mus_b, rhos_b, eps_W, eps_b)
	w0  = tf.get_variable('w0',  layer_sizes[0][0], initializer=tf.constant_initializer(W[0]), dtype=tf.float64)
	b0  = tf.get_variable('b0',  layer_sizes[0][1], initializer=tf.constant_initializer(b[0]), dtype=tf.float64)
	w1  = tf.get_variable('w1',  layer_sizes[1][0], initializer=tf.constant_initializer(W[1]), dtype=tf.float64)
	b1  = tf.get_variable('b1',  layer_sizes[1][1], initializer=tf.constant_initializer(b[1]), dtype=tf.float64)
	
	x = tf.constant(x_set[0].reshape(-1,1), dtype=tf.float64)
	y = tf.constant(y_set[0].reshape(-1,1), dtype=tf.float64)
	
	with tf.GradientTape() as tape:
		z0 = tf.matmul(x,w0)+b0
		a0 = tf.nn.relu(z0)
		y_hat = tf.matmul(a0,w1)+b1
	
		loss = -tf_calc_log_likelihood(y, y_hat)
		gw0, gb0, gw1, gb1 = tape.gradient(loss,[w0,b0,w1,b1])
		
	x  = x.numpy()
	y  = y.numpy()
	z0 = [z0.numpy()]
	a0 = [a0.numpy()]
	y_hat = y_hat.numpy()

	gW, gb = W_grad_log_likelihood(W, b, z0, a0, y, y_hat, x, num_samples)
	print "grad_check w_0:", np.linalg.norm(gW[0]-gw0)
	print "grad_check w_1:", np.linalg.norm(gW[1]-gw1)
	print "grad_check b_0:", np.linalg.norm(gb[0]-gb0)
	print "grad_check b_1:", np.linalg.norm(gb[1]-gb1)
예제 #7
0
    def delete(self, request):
        """
        Eliminar un tfg
        :param request:
        :return :
        """

        try:
            params = utils.get_params(request)
            self.logger.info('INICIO WS - TFGVIEW DELETE del usuario: %s con parametros: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
            if 'titulo' in params:
                tfg = Tfg.objects.get(titulo=params.get('titulo'))
                serializer = self.serializer_class(tfg)
                resul = serializer.delete_tfg(tfg)
                if resul['status']:
                    resul_status = status.HTTP_200_OK
                else:
                    resul = dict(message=resul['message'])
                    resul_status = status.HTTP_400_BAD_REQUEST
            else:
                resul = dict(message="Parametros incorrectos")
                resul_status = status.HTTP_400_BAD_REQUEST
            self.logger.info('FIN WS - TFGVIEW DELETE del usuario: %s con resultado: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=resul_status)
        except Tfg.DoesNotExist:
            resul = dict(message="El tfg indicado no existe")
            self.logger.error('TFGVIEW DELETE del usuario: %s con resultado: %s' %
                              (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            resul = dict(status=False, message="Error en la llamada")
            self.logger.critical('TFGVIEW DELETE: %s %s' % (resul, e))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #8
0
def text(**kwargs):
    if request.args.get('submit') is not None:
        active = request.form.get('tabStatus')
        params = []
        if active == 'page':
            mode = 'page'
            params.append('title')
        else:
            mode = 'content'
        return redirect(url_for('.text', mode=mode, **get_params(params)), code=c.REQUEST)

    if not request.form.get('tabStatus', False):
        if kwargs.get('mode', None) == 'page':
            kwargs['tabStatus'] = 'page'
        else:
            kwargs['tabStatus'] = 'content'

    form = contribtracker.form.getForm()(request.form, **kwargs)
    data = contribtracker.model.Model(form=form)

    if form.validate(data):
        data.render()
    return render('index.html',
                  tool=__name__,
                  form=form,
                  data=data)
예제 #9
0
    def delete(self, request):
        """
        Eliminar un evento
        :param request:
        :return :
        """
        try:
            params = utils.get_params(request)
            self.logger.info('INICIO WS - EVENTOSVIEW DELETE del usuario: %s con params: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
            if request.user.is_admin:
                evento = Evento.objects.get(id=params.get('id'))
                serializer = self.serializer_class(evento)
                resul = serializer.delete(evento)
            else:
                resul = dict(status=False, message="Parametros incorrectos")
            self.logger.critical('FIN WS - EVENTOSVIEW DELETE del usuario: %s con resultado: %s' %
                                 (request.user.email if hasattr(request.user, 'email') else request.user.username,
                                  resul))
            return Response(resul)

        except Evento.DoesNotExist:
            resul = dict(status=False, message="El evento indicado no existe")
            self.logger.error('INICIO WS - EVENTOSVIEW DELETE del usuario: %s con resultado: %s' %
                              (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
        except Exception:
            resul = dict(status=False, message="Error en la llamada")
            self.logger.critical('INICIO WS - EVENTOSVIEW DELETE del usuario: %s con resultado: %s' %
                                 (request.user.email if hasattr(request.user, 'email') else request.user.username,
                                  resul))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #10
0
 def create(self, request):
     """
     POST
     Insertar un nuevo subtipo de evento
     :param request:
     :return :
     {status: True/False, data:{datos del subtipo de evento}
     """
     try:
         params = utils.get_params(request)
         if params.get('delete'):
             return SubTipo_EventosViewSet().delete(request)
         self.logger.info('INICIO WS - SUBTIPOEVENTOSVIEW CREATE del usuario: %s con params: %s' %
                          (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
         resul = SubTipo_Evento.objects.create(codigo=params.get('codigo'), nombre=params.get('nombre'))
         if resul.id:
             resul = utils.to_dict(dict(status=True, data=resul))
             resul_status = status.HTTP_200_OK
         else:
             resul = dict(message=resul['message'])
             resul_status = status.HTTP_400_BAD_REQUEST
             self.logger.info('FIN WS - SUBTIPOEVENTOSVIEW CREATE del usuario: %s con params: %s' %
                              (request.user.email if hasattr(request.user, 'email') else request.user.username,
                               resul))
         return Response(resul, status=resul_status)
     except Exception as e:
         resul = dict(status=False, message="Error en la llamada")
         self.logger.critical('FIN WS - SUBTIPOEVENTOSVIEW CREATE del usuario: %s con params: %s %s' %
                              (request.user.email if hasattr(request.user, 'email') else request.user.username,
                               resul, e))
         return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #11
0
    def post(self, request):
        """
        POST
        Subir un fichero comprimido .zip con la documentacion
        :param request:
        :return :

        """
        try:
            params = utils.get_params(request)
            self.logger.info('INICIO WS - TRIBUNALUPLOADDOCVIEW POST del usuario: %s con parametros: %s' % (request.user.email if hasattr(request.user, 'email') else request.user.username, request.FILES['file']))
            if request.user.has_perm('comisiones_evaluacion.tribunal.change') or request.user.is_admin:
                doc = request.FILES['file']
                tfg = Tfg.objects.get(titulo=params.get('tfg'))
                tfg_asig = Tfg_Asig.objects.get(tfg=tfg)
                tribunal = Tribunales.objects.get(tfg=tfg_asig)
                change_doc = Tribunal(request.user, tribunal)
                resul = change_doc.upload_doc(doc)
                if resul['status']:
                    resul_status = status.HTTP_200_OK
                else:
                    resul = dict(message=resul['message'])
                    resul_status = status.HTTP_400_BAD_REQUEST
            else:
                resul = dict(message="Sin privilegios")
                resul_status = status.HTTP_405_METHOD_NOT_ALLOWED
            self.logger.info('FIN WS - UPLOADFILEVIEW POST del usuario: %s con resultado: %s' % (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=resul_status)
        except Exception as e:
            resul = dict(status=False, message="Error en la llamada")
            self.logger.critical('UPLOADFILEVIEW POST: %s %s' % (resul, e))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #12
0
 def put(self, request):
     """
     Actualizar datos de un tribunal
     :param request: tfg <str>, campos <dict>
     :return :
     """
     try:
         params = utils.get_params(request)
         self.logger.info('INICIO WS - TRIBUNALESNVIEW PUT del usuario: %s con parametros: %s' %
                          (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
         if request.user.has_perm('comisiones_evaluacion.tribunal.change') or request.user.is_admin:
             tfg = Tfg.objects.get(titulo=params.get('tfg'))
             tfg_asig = Tfg_Asig.objects.get(tfg=tfg)
             tribunal = Tribunales.objects.get(tfg=tfg_asig)
             serializer = self.serializer_class(tribunal)
             params = json.loads(params.get('datos'))
             resul = serializer.update(request.user, tribunal, params)
             if resul['status']:
                 resul_status = status.HTTP_200_OK
             else:
                 resul = dict(message=resul['message'])
                 resul_status = status.HTTP_400_BAD_REQUEST
         else:
             resul = dict(message="Parametros incorrectos")
             resul_status = status.HTTP_400_BAD_REQUEST
         self.logger.info('FIN WS - TRIBUNALESNVIEW PUT del usuario: %s con resultado: %s' %
                          (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
         return Response(resul, status=resul_status)
     except Exception as e:
         resul = dict(status=False, message="Error en la llamada")
         self.logger.critical('TRIBUNALESNVIEW PUT: %s %s' % (resul, e))
         return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #13
0
def index(**kwargs):
    if request.args.get('submit') is not None:
        active = request.form.get('tabStatus')
        params = ['siteDest', 'siteSource']
        if active == 'page':
            params.append('title')
        return redirect(url_for('.index', **get_params(params)), code=c.REQUEST)

    normalize(['title'], kwargs)
    if not request.form.get('tabStatus', False):
        if kwargs.get('siteDest', False) and not kwargs.get('title', False):
            kwargs['tabStatus'] = 'content'
        else:
            kwargs['tabStatus'] = 'page'

    if not request.form.get('siteDest', False) and not request.form.get('siteSource', False):
        kwargs['siteDest'] = 'th'
        kwargs['siteSource'] = 'en'

    form = wikitranslator.form.getForm()(request.form, **kwargs)
    data = wikitranslator.model.Model(form=form)
    if form.validate(data):
        data.render()
    return render('index.html',
                  tool=__name__,
                  form=form,
                  data=data)
예제 #14
0
    def list(self, request):
        """
        GET
        Obtener los datos de todos o de alguna comision
        :param request:
        :return :
        {status: True/False, data:{serializer del tfg o tfgs}
        """
        try:
            params = utils.get_params(request)
            self.logger.info('INICIO WS - COMISIONEVALUACIONVIEW LIST del usuario: %s con parametros: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
            comisiones = Comision_Evaluacion.objects.all()
            resul = utils.procesar_datos_comisiones(request.user, self.serializer_class(comisiones, many=True).data)

            # if len(resul) == 0:
            #     raise NameError("No hay comisiones almacenadas")
            self.logger.info('FIN WS - COMISIONEVALUACIONVIEW LIST del usuario: %s con resultado: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(dict(data=resul), status=status.HTTP_200_OK)
        except NameError as e:
            resul = dict(message=e.message)
            self.logger.error('COMISIONEVALUACIONVIEW LIST del usuario: %s con resultado: %s' %
                              (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
        except Comision_Evaluacion.DoesNotExist:
            resul = dict(message="la comision indicada no existe")
            self.logger.error('COMISIONEVALUACIONVIEW LIST del usuario: %s con resultado: %s' %
                              (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            resul = dict(status=False, message="Error en la llamada")
            self.logger.critical('COMISIONEVALUACIONVIEW LIST: %s %s' % (resul, e))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #15
0
 def list(self, request):
     """
     GET
     Obtener los datos de todos o de algun tribunal
     :param request:
     :return :
     {status: True/False, data:{serializer del tfg o tfgs}
     """
     try:
         params = utils.get_params(request)
         if params.get('delete'):
             return TribunalesViewSet().delete(request)
         self.logger.info('INICIO WS - TRIBUNALESNVIEW LIST del usuario: %s con parametros: %s' %
                          (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
         tribunales = Tribunales.objects.all()
         resul = utils.procesar_datos_tribunales(request.user, self.serializer_class(tribunales, many=True).data)
         # if len(resul) == 0:
         #     raise NameError("No hay tribunales almacenados")
         self.logger.info('FIN WS - TRIBUNALESNVIEW LIST del usuario: %s con resultado: %s' %
                          (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
         return Response(dict(data=resul), status=status.HTTP_200_OK)
     except NameError as e:
         resul = dict(message=e.message)
         self.logger.error('TRIBUNALESNVIEW LIST del usuario: %s con resultado: %s' %
                           (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
         return Response(resul, status=status.HTTP_400_BAD_REQUEST)
     except Tribunales.DoesNotExist:
         resul = dict(message="El tribunal indicado no existe")
         self.logger.error('TRIBUNALESNVIEW LIST del usuario: %s con resultado: %s' %
                           (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
         return Response(resul, status=status.HTTP_400_BAD_REQUEST)
     except Exception as e:
         resul = dict(status=False, message="Error en la llamada")
         self.logger.critical('TRIBUNALESNVIEW LIST: %s %s' % (resul, e))
         return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #16
0
def index(**kwargs):
    if request.args.get('submit') is not None:
        active = request.form.get('tabStatus')
        params = ['siteDest', 'siteSource']
        if active == 'page':
            params.append('title')
        return redirect(url_for('.index', **get_params(params)),
                        code=c.REQUEST)

    normalize(['title'], kwargs)
    if not request.form.get('tabStatus', False):
        if kwargs.get('siteDest', False) and not kwargs.get('title', False):
            kwargs['tabStatus'] = 'content'
        else:
            kwargs['tabStatus'] = 'page'

    if not request.form.get('siteDest', False) and not request.form.get(
            'siteSource', False):
        kwargs['siteDest'] = 'th'
        kwargs['siteSource'] = 'en'

    form = wikitranslator.form.getForm()(request.form, **kwargs)
    data = wikitranslator.model.Model(form=form)
    if form.validate(data):
        data.render()
    return render('index.html', tool=__name__, form=form, data=data)
예제 #17
0
파일: agent.py 프로젝트: Vaillus/RL_toolkit
    def check(self, action_type: str, action_dim: int, state_dim: int) -> bool:
        agent_action_type = get_params("misc/agent_action_type")
        assert action_type == agent_action_type[self.type], "env and agent\
             action types don't match"

        is_ok = self.agent.num_actions == action_dim and self.agent.state_dim == state_dim
        return is_ok
예제 #18
0
    def list(self, request):
        """
        GET
        Obtener los datos de todos o de algun tfg
        :param request:
        :return :
        {status: True/False, data:{serializer del tfg o tfgs}

        """
        try:
            params = utils.get_params(request)
            self.logger.info('INICIO WS - TFGVIEW LIST del usuario: %s con parametros: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
            # if 'titulo' in params:
            #     tfg = Tfg.objects.get(titulo=params['titulo'])
            #     resul = self.serializer_class(tfg).data
            underscore = params.get('_', False) # comprobar que no se manda el parametro '_' - cosas del JQuery
            if len(params) > 0 and not underscore:
                params = utils.procesar_params_tfg(request.user, params)
                tfgs = Tfg.objects.filter(**params)
                if len(tfgs) > 0:
                    resul = utils.procesar_datos_tfgs(request.user, self.serializer_class(tfgs, many=True).data)
                else:
                    resul = []

            else:
                # tfg_asig = Tfg_Asig.objects.all()
                # resul = self.serializer_class(tfg_asig, many=True).data
                # if len(resul) == 0:
                #     raise NameError("No hay tfgs almacenados")
                params = utils.procesar_params_tfg(request.user, {})
                tfgs = Tfg.objects.filter(**params)
                paginador = Paginator(tfgs, 20)
                pagina = params.get('pagina')
                try:
                    tfgs = paginador.page(pagina)
                    resul = {
                    'resul': utils.procesar_datos_tfgs(request.user, self.serializer_class(tfgs, many=True).data),
                    'pagina': pagina, 'num_paginas': paginador.num_pages}
                except PageNotAnInteger:
                    resul = utils.procesar_datos_tfgs(request.user, self.serializer_class(tfgs, many=True).data)
            resul_status = status.HTTP_200_OK
            self.logger.info('FIN WS - TFGVIEW LIST del usuario: %s con resultado: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(dict(data=resul), status=resul_status)
        except NameError as e:
            resul = dict(message=e.message)
            self.logger.error('TFGVIEW LIST del usuario: %s con resultado: %s' %
                              (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
        except Tfg.DoesNotExist:
            resul = dict(message="El tfg indicado no existe")
            self.logger.error('TFGVIEW LIST del usuario: %s con resultado: %s' %
                              (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            resul = dict(status=False, message="Error en la llamada")
            self.logger.critical('TFGVIEW LIST: %s %s' % (resul, e))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #19
0
        def decorated(*args, **kwargs):

            # debug requests
            if app.debug:
                app._debug(str(request.method) + " " + str(request.path) +
                           " " + str(get_params()),
                           separate=True)

            return func(*args, **kwargs)
예제 #20
0
def list_menu():
    params = utils.get_params()
    if params.get('get'):
        generate_menu(params)
    else:
        for menu in menus:
            add_list_item(menu)
    if handle > -1:
        xbmcplugin.endOfDirectory(handle)
예제 #21
0
def list_menu():
    params = utils.get_params()
    if params.get('get'):
        generate_menu(params)
    else:
        for menu in menus:
            add_list_item(menu)
    if handle > -1:
        xbmcplugin.endOfDirectory(handle)
예제 #22
0
파일: cli.py 프로젝트: PowerOfDark/Exam
def edit_question(meta, id, **kwargs):
    """
    Edits an existing question
    """

    args = get_params(**kwargs)
    meta.insert_question(True, id, **args)

    click.echo(f"Question `{id}` updated successfully")
    save_meta(meta)
예제 #23
0
    def create(self, request):
        """
        POST
        Asignar un TFG a uno o varios alumnos
        :param request:
        :return:
        {status: True/False, data:{serializer del tfg asignado y de los alumnos}
        """

        try:
            params = utils.get_params(request)
            if params.get('delete'):
                return Tfg_asigViewSet().delete(request)
            self.logger.info('INICIO WS - TFGASIGVIEW POST del usuario: %s con parametros: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
            if request.user.has_perm('tfgs.tfg_asig.change') or request.user.is_admin:
                alumno_2 = None
                alumno_3 = None
                tfg = Tfg.objects.get(titulo=params.get('tfg'))
                # Si es profesor
                if Profesor.objects.filter(email=request.user.email).exists() and request.user.email != tfg.tutor.\
                        email:
                    raise NameError("El profesor no es tutor del Tfg")
                alumno_1 = utils.get_or_create_alumno(params.get('alumno_1'))
                if 'alumno_2' in params:
                    alumno_2 = utils.get_or_create_alumno(params.get('alumno_2'))
                if 'alumno_3' in params:
                    alumno_3 = utils.get_or_create_alumno(params.get('alumno_3'))

                serializer = self.serializer_class(data=dict(tfg=tfg.id, alumno_1=alumno_1.id, alumno_2=alumno_2,
                                                             alumno_3=alumno_3))
                if serializer.is_valid():
                    resul = serializer.create(serializer.validated_data)
                    if resul['status']:
                        resul = utils.to_dict(resul)
                        resul_status = status.HTTP_200_OK
                    else:
                        resul = dict(message=resul['message'])
                        resul_status = status.HTTP_400_BAD_REQUEST
                else:
                    resul = dict(message=serializer.errors)
                    resul_status = status.HTTP_400_BAD_REQUEST
            else:
                resul = dict(message="Sin privilegios")
                resul_status = status.HTTP_400_BAD_REQUEST
            self.logger.info('FIN WS - TFGASIGVIEW POST del usuario: %s con resultado: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=resul_status)
        except NameError as e:
            self.logger.error('FIN WS - TFGASIGVIEW POST: %s' % e.message)
            return Response(dict(message=e.message), status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            resul = dict(status=False, message="Error en la llamada")
            self.logger.critical('FIN WS - TFGASIGVIEW POST: %s %s' % (resul, e))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #24
0
    def _initialize_parameters(self):
        """Retrieve parameters if they exist, else replace with defaults"""
        n_dim_state, n_dim_obs = self.n_dim_state, self.n_dim_obs

        arguments = get_params(self)
        defaults = {
            'transition_matrices':
            np.eye(n_dim_state),
            'transition_offsets':
            np.zeros(n_dim_state),
            'transition_covariance':
            np.eye(n_dim_state),
            'observation_matrices':
            np.eye(n_dim_obs, n_dim_state),
            'observation_offsets':
            np.zeros(n_dim_obs),
            'observation_covariance':
            np.eye(n_dim_obs),
            'initial_state_mean':
            np.zeros(n_dim_state),
            'initial_state_covariance':
            np.eye(n_dim_state),
            'random_state':
            0,
            'em_vars': [
                'transition_covariance', 'observation_covariance',
                'initial_state_mean', 'initial_state_covariance'
            ],
        }
        converters = {
            'transition_matrices': array2d,
            'transition_offsets': array1d,
            'transition_covariance': array2d,
            'observation_matrices': array2d,
            'observation_offsets': array1d,
            'observation_covariance': array2d,
            'initial_state_mean': array1d,
            'initial_state_covariance': array2d,
            'random_state': check_random_state,
            'n_dim_state': int,
            'n_dim_obs': int,
            'em_vars': lambda x: x,
        }

        parameters = preprocess_arguments([arguments, defaults], converters)

        return (parameters['transition_matrices'],
                parameters['transition_offsets'],
                parameters['transition_covariance'],
                parameters['observation_matrices'],
                parameters['observation_offsets'],
                parameters['observation_covariance'],
                parameters['initial_state_mean'],
                parameters['initial_state_covariance'])
예제 #25
0
파일: cli.py 프로젝트: PowerOfDark/Exam
def add_answer(meta, question_id, text, correct, likelihood, id):
    """
    Adds (or modifies) an answer to a question in problem set
    """

    optional = get_params(is_correct=correct)
    question = meta.find_question(question_id)
    question.insert_answer(id, text=text, likelihood=likelihood, **optional)

    click.echo(f"Answer `{id}` updated successfully")
    save_meta(meta)
예제 #26
0
    def post(self):
        (
            username,
            password,
        ) = get_params([
            Argument('username', type=str, required=True),
            Argument('password', type=str, required=True),
        ])

        if username == 'admin' and password == '123456':
            return Response()
        raise ResponseError(info='账号密码错误!')
예제 #27
0
def clear_regimes(directory=diffusion_maps, clear_reg=clear_reg):
    files = os.listdir(directory)
    for f in files:
        pkl_loc = os.path.join(directory, f)
        pkl_file = open(pkl_loc, 'rb')
        data = pickle.load(pkl_file)
        traj_params = {traj:get_params(traj) for traj in data['traj_list']}
        regime = list(traj_params.values())[0]['regime']
        print("Read regime %s" %regime)
        pkl_file.close()
        if regime[:len(clear_reg)] == clear_reg:
            os.remove(pkl_loc)
예제 #28
0
def infer_manual(argv=None):
    """Run the inference and print the results to stdout."""
    # Initialize the estimator and run the prediction
    model_estimator = tf.estimator.Estimator(model_fn=model_fn,
                                             model_dir=FLAGS.model_dir,
                                             params=get_params())

    for res in POTENTIAL_RESPONSES:
        result = model_estimator.predict(
            input_fn=lambda: test_inputs(INPUT_CONTEXT, res))

        for r in result:
            print('response: ', res, 'dot: ', r[0])
예제 #29
0
파일: cli.py 프로젝트: PowerOfDark/Exam
def add_question(meta, id, **kwargs):
    """
    Adds a question to the problem set
    """

    args = get_params(**kwargs)
    try:
        meta.insert_question(False, id, **args)
    except KeyError as ex:
        raise click.ClickException("Invalid question ID") from ex

    click.echo(f"Question `{id}` added successfully")
    save_meta(meta)
예제 #30
0
def index(**kwargs):
    if request.args.get("submit") is not None:
        return redirect(url_for(".index", **get_params(["title", "oldid"])), code=c.REQUEST)

    normalize(["title"], kwargs)
    form = dykchecker.form.getForm()(request.form, **kwargs)
    data = dykchecker.model.Model(form=form)
    if form.validate(data):
        data.render()
        return render("page.html", tool=__name__, form=form, data=data)

    else:
        return render("index.html", tool=__name__, form=form)
예제 #31
0
 def create(self, request):
     """
     POST
     Insertar un tfg nuevo
     :param request:
     :return :
     {status: True/False, data:{datos del tfg insertado o de todos los tfgs}
     """
     try:
         params = utils.get_params(request)
         if params.get('delete'):
             return TfgViewSet().delete(request)
         self.logger.info('INICIO WS - TFGVIEW CREATE del usuario: %s con parametros: %s' %
                          (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
         if request.user.has_perm('tfgs.tfg.create') or request.user.is_admin:
             # request.data['tutor'] = Profesor.objects.get(email=request.data['tutor'])
             # if 'cotutor' in request.data:
             #     request.data['cotutor'] = Profesor.objects.get(email=request.data['tutor'])
             # serializer = self.serializer_class(data=request.data)
             # if serializer.is_valid():
             #     resul = serializer.create(serializer.validated_data)
             #     if resul['status']:
             #         resul = utils.to_dict(resul)
             #         resul_status = status.HTTP_200_OK
             #     else:
             #         resul = dict(message=resul['message'])
             #         resul_status = status.HTTP_400_BAD_REQUEST
             # else:
             #     resul = dict(message=serializer.errors)
             #     resul_status = status.HTTP_400_BAD_REQUEST
             resul = Tfg.objects.create(conocimientos_previos=params.get('conocimientos_previos'),
                                        cotutor=params.get('cotutor'), descripcion=params.get('descripcion'),
                                        tutor=params.get('tutor'), hard_soft=params.get('hard_soft'),
                                        titulo=params.get('titulo'), tipo=params.get('tipo'),
                                        n_alumnos=params.get('n_alumnos'), titulacion=params.get('titulacion'))
             if resul['status']:
                 resul['data'] = self.serializer_class(resul['data']).data
                 resul_status = status.HTTP_200_OK
             else:
                 resul = dict(message=resul['message'])
                 resul_status = status.HTTP_400_BAD_REQUEST
         else:
             resul = dict(message="Sin privilegios")
             resul_status = status.HTTP_405_METHOD_NOT_ALLOWED
         self.logger.info('FIN WS - TFGVIEW CREATE del usuario: %s con resultado: %s' %
                          (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
         return Response(resul, status=resul_status)
     except Exception as e:
         resul = dict(status=False, message="Error en la llamada")
         self.logger.critical('TFGVIEW CREATE: %s %s' % (resul, e))
         return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #32
0
def index(**kwargs):
    if request.args.get('submit') is not None:
        return redirect(url_for('.index', **get_params(['title', 'oldid'])),
                        code=c.REQUEST)

    normalize(['title'], kwargs)
    form = dykchecker.form.getForm()(request.form, **kwargs)
    data = dykchecker.model.Model(form=form)
    if form.validate(data):
        data.render()
        return render('page.html', tool=__name__, form=form, data=data)

    else:
        return render('index.html', tool=__name__, form=form)
예제 #33
0
def execute():
    def signal_handler(_signo, _stack_frame):
        sys.stderr.write('Caught ' + _signo + ', exiting')
        sys.exit(1)

    signal.signal(signal.SIGTERM, signal_handler)

    content_metadata, custom_metadata = get_params()

    if len(content_metadata) > 0:
        process_tests_json(content_metadata, custom_metadata)
    else:
        # no parameters, just exit
        print('[]')
        sys.exit(0)
예제 #34
0
    def put(self, id):
        (name, ) = get_params([
            Argument('name', type=str, location=('json', 'values', )),
        ])

        resource_pack = Model.ResourcePack.get_by_id(id)
        update_data = {}
        if name:
            update_data['name'] = name

        if update_data:
            resource_pack.update(update_data)
            db.session.commit()

        return Response()
예제 #35
0
def execute():
    def signal_handler(_signo, _stack_frame):
        sys.stderr.write('Caught ' + _signo + ', exiting')
        sys.exit(1)

    signal.signal(signal.SIGTERM, signal_handler)

    content_metadata, custom_metadata = get_params()

    if len(content_metadata) > 0:
        process_tests_json(content_metadata, custom_metadata)
    else:
        # no parameters, just exit
        print('[]')
        sys.exit(0)
예제 #36
0
    def list(self, request):
        """
        GET
        Obtener los datos de todos o de algun tfg asignado
        :param request:
        :return :
        {status: True/False, data:{serializer del tfg o tfgs}

        """
        try:
            params = utils.get_params(request)
            self.logger.info('INICIO WS - TFGASIGVIEW LIST del usuario: %s con parametros: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
            if 'titulo' in params:
                tfg = Tfg.objects.get(titulo=params['titulo'])
                tfg_asig = Tfg_Asig.objects.get(tfg=tfg)
                resul = self.serializer_class(tfg_asig).data
            else:
                tfgs = Tfg_Asig.objects.all()
                if len(tfgs) == 0:
                    tfgs = []
                paginador = Paginator(tfgs, 20)
                pagina = params.get('pagina')
                try:
                    tfgs = paginador.page(pagina)
                    resul = {
                    'resul': utils.procesar_datos_tfgs_asig(request.user, self.serializer_class(tfgs, many=True).data),
                    'pagina': pagina, 'num_paginas': paginador.num_pages}
                except PageNotAnInteger:
                    resul = utils.procesar_datos_tfgs_asig(request.user, self.serializer_class(tfgs, many=True).data)
            resul_status = status.HTTP_200_OK
            self.logger.info('FIN WS - TFGVIEW LIST del usuario: %s con resultado: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(dict(data=resul), status=resul_status)
        except NameError as e:
            resul = dict(message=e.message)
            self.logger.error('TFGASIGVIEW LIST del usuario: %s con resultado: %s' %
                              (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
        except Tfg.DoesNotExist:
            resul = dict(message="El tfg indicado no existe")
            self.logger.error('TFGASIGVIEW LIST del usuario: %s con resultado: %s' %
                              (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            resul = dict(status=False, message="Error en la llamada")
            self.logger.critical('TFGASIGVIEW LIST: %s %s' % (resul, e))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #37
0
    def create(self, request):
        """
        POST
        Insertar un evento nuevo
        :param request:
        :return :
        {status: True/False, data:{datos del evento}
        """
        try:
            params = utils.get_params(request)
            if params.get('delete'):
                return EventosViewSet().delete(request)
            self.logger.info('INICIO WS - EVENTOSVIEW CREATE del usuario: %s con parametros: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
            if request.user.has_perm('eventos.evento.change') or request.user.is_admin:
                resul = Evento.objects.create_evento(contenido=params.get('contenido'),
                                                     tipo=params.get('tipo'),
                                                     convocatoria=params.get('convocatoria'),
                                                     titulacion=params.get('titulacion'),
                                                     titulo=params.get('titulo'),
                                                     autor=Usuario.objects.get(id=request.user.id),
                                                     desde=params.get('desde'), hasta=params.get('hasta'))

                if resul.get('status'):
                    resul['data'] = self.serializer_class(resul['data']).data
                    resul['data'] = utils.periodos(resul['data'])
                    resul_status = status.HTTP_200_OK
                else:
                    resul = dict(message=resul['message'])
                    resul_status = status.HTTP_400_BAD_REQUEST
            else:
                resul = dict(status=False, message="Sin privilegios")
                resul_status = status.HTTP_405_METHOD_NOT_ALLOWED
            self.logger.info('FIN WS - EVENTOSVIEW CREATE del usuario: %s con resultado: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=resul_status)
        except Exception as e:
            resul = dict(status=False, message="Error en la llamada")
            self.logger.critical('EVENTOSVIEW CREATE: %s %s' % (resul, e))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #38
0
    def delete(self, request):
        """
        DELETE
        Elimina la asignacion un TFG a uno o varios alumnos
        :param request: 
        :return :
        {status: True/False, data:{serializer del tfg que ha quedado libre}
        """

        try:
            params = utils.get_params(request)
            self.logger.info('INICIO WS - TFGASIGVIEW DELETE del usuario: %s con parametros: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
            if 'titulo' in params:
                tfg = Tfg.objects.get(titulo=params.get('titulo'))
                tfg_asig = Tfg_Asig.objects.get(tfg=tfg)
                serializer = self.serializer_class(tfg_asig)
                resul = serializer.delete(tfg_asig)
                if resul['status']:
                    # resul = utils.to_dict(resul)
                    resul_status = status.HTTP_200_OK
                else:
                    resul = dict(message=resul['message'])
                    resul_status = status.HTTP_400_BAD_REQUEST
            else:
                resul = dict(message="Sin privilegios")
                resul_status = status.HTTP_400_BAD_REQUEST
            self.logger.info('FIN WS - TFGASIGVIEW DELETE del usuario: %s con resultado: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=resul_status)
        except Tfg.DoesNotExist:
            resul = dict(message="El tfg indicado no existe")
            self.logger.error('TFGASIGVIEW DELETE del usuario: %s con resultado: %s' %
                              (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            resul = dict(status=False, message="Error en la llamada")
            self.logger.critical('TFGASIGVIEW DELETE: %s %s' % (resul, e))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #39
0
    def put(self, request):
        """
        PUT
        Cambia los datos de un evento
        :param request:
        :return :
        {status: True/False, data:{datos del evento cambiado}

        :param request:
        :return:
        """
        try:
            params = utils.get_params(request)
            self.logger.info('INICIO WS - EVENTOSVIEW PUT del usuario: %s con params: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
            if request.user.has_perm('eventos.evento.change') or request.user.is_admin:
                evento = Evento.objects.get(id=params.get('evento'))
                params = json.loads(params.get('datos'))
                serializer = EventoSerializer(evento)
                resul = serializer.update(evento, params)
                if resul['status']:
                    resul['data'] = utils.periodos(resul['data'])
                    resul_status = status.HTTP_200_OK
                else:
                    resul = dict(message=resul['message'])
                    resul_status = status.HTTP_400_BAD_REQUEST
            else:
                resul = dict(status=False, message="Sin privilegios")
                resul_status = status.HTTP_405_METHOD_NOT_ALLOWED
            self.logger.info('FIN WS - EVENTOSVIEW PUT del usuario: %s con resultado: %s' %
                                 (request.user.email if hasattr(request.user, 'email') else request.user.username,
                                  resul))
            return Response(resul, status=resul_status)
        except Exception as e:
            resul = dict(status=False, message="Error en la llamada")
            self.logger.critical('FIN WS - EVENTOSVIEW PUT del usuario: %s con resultado: %s' %
                                 (request.user.email if hasattr(request.user, 'email') else request.user.username,
                                  resul))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #40
0
 def create(self, request):
     """
     POST
     Insertar una comision nueva
     :param request:
     :return :
     {status: True/False, data:{datos de la comision insertada o de todas las comisiones}
     """
     try:
         params = utils.get_params(request)
         if params.get('delete'):
             return ComisionEvaluacionViewSet().delete(request)
         self.logger.info('INICIO WS - COMISIONEVALUACIONVIEW POST del usuario: %s con parametros: %s' %
                          (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
         if request.user.has_perm('comisiones_evaluacion.comision.create') or request.user.is_admin:
             comision = Comision(request.user, params.get('convocatoria'), params.get('anio'),
                                 params.get('titulacion'))
             resul = comision.tutores_comisiones()
             # comision.asig_tfgs()
             # while comision.reintentar:
             #     comision = Comision(request.user)
             #     resul = comision.tutores_comisiones(params.get('convocatoria'))
             #     comision.asig_tfgs()
             if resul['status']:
                 resul_status = status.HTTP_200_OK
             else:
                 resul = dict(message=resul['message'])
                 resul_status = status.HTTP_400_BAD_REQUEST
         else:
             resul = dict(message="Sin privilegios")
             resul_status = status.HTTP_405_METHOD_NOT_ALLOWED
         self.logger.info('FIN WS - COMISIONEVALUACIONVIEW POST del usuario: %s con resultado: %s' %
                          (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
         return Response(resul, status=resul_status)
     except Exception as e:
         resul = dict(status=False, message="Error en la llamada")
         self.logger.critical('COMISIONEVALUACIONVIEW POST: %s %s' % (resul, e))
         return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #41
0
 def put(self, request):
     """
     Actualizar datos de una comisión
     :param request: tfg <str>, campos <dict>
     :return :
     """
     try:
         params = utils.get_params(request)
         self.logger.info('INICIO WS - COMISIONEVALUACIONVIEW PUT del usuario: %s con parametros: %s' %
                          (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
         if request.user.has_perm('comisiones_evaluacion.comision.change') or request.user.is_admin:
             presidente = Profesor.objects.get(email=params.get('presidente'))
             comision = Comision_Evaluacion.objects.get(presidente=presidente)
             serializer = self.serializer_class(comision)
             params = json.loads(params.get('datos'))
             resul = serializer.update(request.user, comision, params)
             if resul['status']:
                 resul_status = status.HTTP_200_OK
             else:
                 resul = dict(message=resul['message'])
                 resul_status = status.HTTP_400_BAD_REQUEST
         else:
             resul = dict(message="Parametros incorrectos")
             resul_status = status.HTTP_400_BAD_REQUEST
         self.logger.info('FIN WS - COMISIONEVALUACIONVIEW PUT del usuario: %s con resultado: %s' %
                          (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
         return Response(resul, status=resul_status)
     except Profesor.DoesNotExist:
         resul = dict(message="El presidente de la comision no existe")
         self.logger.error('COMISIONEVALUACIONVIEW DELETE del usuario: %s con resultado: %s' %
                           (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
         return Response(resul, status=status.HTTP_400_BAD_REQUEST)
     except Exception as e:
         resul = dict(status=False, message="Error en la llamada")
         self.logger.critical('COMISIONEVALUACIONVIEW PUT: %s %s' % (resul, e))
         return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #42
0
    def delete(self, request):
        """
        Eliminar una comisión
        :param request:
        :return :
        """

        try:
            params = utils.get_params(request)
            self.logger.info('INICIO WS - COMISIONEVALUACIONVIEW DELETE del usuario: %s con parametros: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
            if 'titulo' in params:
                comision = Comision_Evaluacion.objects.get(presidente=params.get('presidente'))
                serializer = self.serializer_class(comision)
                resul = serializer.delete_tfg(comision)
                if resul['status']:
                    resul = utils.to_dict(resul)
                    resul_status = status.HTTP_200_OK
                else:
                    resul = dict(message=resul['message'])
                    resul_status = status.HTTP_400_BAD_REQUEST
            else:
                resul = dict(message="Parametros incorrectos")
                resul_status = status.HTTP_400_BAD_REQUEST
            self.logger.info('FIN WS - COMISIONEVALUACIONVIEW DELETE del usuario: %s con resultado: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=resul_status)
        except Comision_Evaluacion.DoesNotExist:
            resul = dict(message="La comision indicada no existe")
            self.logger.error('COMISIONEVALUACIONVIEW DELETE del usuario: %s con resultado: %s' %
                              (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            resul = dict(status=False, message="Error en la llamada")
            self.logger.critical('COMISIONEVALUACIONVIEW DELETE: %s %s' % (resul, e))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #43
0
    def put(self, request):
        """
        PUT
        Cambia los datos de un subtipo de evento
        :param request:
        :return :
        {status: True/False, data:{datos del subtipo de evento cambiado}

        :param request:
        :return:
        """
        try:
            params = utils.get_params(request)
            self.logger.info('INICIO WS - SUBTIPOEVENTOSVIEW PUT del usuario: %s con params: %s' %
                             (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
            if request.user.has_perm('eventos.subtipo_eventos.change') or request.user.is_admin:
                subtipo = SubTipo_Evento.objects.get(codigo=params.get('codigo'))
                params = json.loads(params.get('datos'))
                serializer = SubTipo_EventoSerializer(subtipo)
                resul = serializer.update(subtipo, params)
                if resul['status']:
                    return Response(utils.to_dict(resul))
                else:
                    return Response(resul)
            else:
                resul = dict(status=False, message="Sin privilegios")
                self.logger.info('FIN WS - SUBTIPOEVENTOSVIEW PUT del usuario: %s con resultado: %s' %
                                 (request.user.email if hasattr(request.user, 'email') else request.user.username,
                                  resul))
                return Response(resul, status=status.HTTP_405_METHOD_NOT_ALLOWED)
        except Exception as e:
            resul = dict(status=False, message="Error en la llamada")
            self.logger.critical('FIN WS - SUBTIPOEVENTOSVIEW PUT del usuario: %s con resultado: %s %s' %
                                 (request.user.email if hasattr(request.user, 'email') else request.user.username,
                                  resul, e))
            return Response(resul, status=status.HTTP_400_BAD_REQUEST)
예제 #44
0
def autor_todos():
    params = get_params(request)
    if request.method == 'GET':
        return autores_view.autores_todos_get(params)
    else:
        return autores_view.autores_todos_post(params)
예제 #45
0
def livros_resenhas():
    params = get_params(request)
    if request.method == 'GET':
        return livros_view.livros_resenhas_get(params)
    else:
        return livros_view.livros_resenhas_post(params)
예제 #46
0
def livros_avaliacoes():
    params = get_params(request)
    if request.method == 'GET':
        return livros_view.livros_avaliacoes_get(params)
    else:
        return livros_view.livros_avaliacoes_post(params)
예제 #47
0
def livros_desejo():
    params = get_params(request)
    if request.method == 'GET':
        return livros_view.livros_desejo_get(params)
    else:
        return livros_view.livros_desejo_post(params)