def query(self, query): # Create Header auth = 'Bearer ' + self.api_key header = { 'Content-Type': 'application/graphql', 'Authorization': auth, 'Accept': 'application/json' } # Create Query String query_str = query # Send Request try: response = requests.post(url=self.api_base, headers=header, data=query_str) if response.status_code == requests.codes.ok: print("Request is successful with code {} ...".format( response.status_code)) return json.loads(response.content) else: utils.log("Error in response: {}".format( response.raise_for_status())) except Exception as e: utils.log("Problem while sending request: {}".format(e)) return
def ListAllLibros(): __log = util.log("Listar libros") try: detallelibro = db.table('Detalle_Libro_Autor')\ .join('Autor', 'Detalle_Libro_Autor.idAutor', '=', 'Autor.idAutor')\ .join('Libro', 'Detalle_Libro_Autor.idLibro', '=', 'Libro.idLibro')\ .join('Editorial', 'Editorial.idEditorial', '=', 'Libro.idEditorial').get() print('Id', 'Nombre Libro\t\t', 'ISBN\t\t', 'Nombre Autor', 'Nombre Editorial', sep="\t") for dl in detallelibro: print(dl.idLibro, dl.Nombre_Libro + '\t', dl.ISBN, dl.Nombre_Autor, dl.Nombre_Editorial, sep="\t") sleep(2) except KeyError as k: __loginfo(f"{k} Error") input("Hubo un error") except KeyboardInterrupt as kb: __log.info(f"{kb} Interrupcion por teclado") print("Interrupcion por teclado\a") sleep(2) util.Salir()
def ListPrestamo(idlector): __log = util.log("Listar Prestamo") prestamo = db.table('Prestamo')\ .join('Detalle_Libro_Biblioteca', 'Detalle_Libro_Biblioteca.idDetalle_Libro_Biblioteca', '=', 'Prestamo.idDetalle_Libro_Biblioteca')\ .join('Libro', 'Libro.idLibro', '=', 'Detalle_Libro_Biblioteca.idLibro')\ .where('Prestamo.idLector', idlector).where('Prestamo.Estado', '1').get() print('Id', 'Nombre Libro', sep="\t") for pres in prestamo: print(pres.idPrestamo, pres.Nombre_Libro, sep="\t")
def SavePrestamo(idlector): __log = util.log("Guardar Prestamo") opcion = True while opcion: try: iddetlibro = int( input("Ingrese id del libro que desea un prestamo:\n")) libro = db.table('Detalle_Libro_Biblioteca')\ .join('Libro', 'Libro.idLibro', '=', 'Detalle_Libro_Biblioteca.idLibro')\ .join('Biblioteca', 'Biblioteca.idBiblioteca', '=', 'Detalle_Libro_Biblioteca.idBiblioteca')\ .where('Detalle_Libro_Biblioteca.idDetalle_Libro_Biblioteca', iddetlibro).first() print('Id', 'Nombre Libro\t\t', 'Biblioteca', sep="\t") print(libro.idDetalle_Libro_Biblioteca, libro.Nombre_Libro, "", libro.Nombre_Biblioteca, sep="\t") if libro: prestamo = db.table('prestamo').insert({ 'idLector': idlector, 'idDetalle_Libro_Biblioteca': iddetlibro }) libcant = libro.Cantidad - 1 if libro.Cantidad > 0: detalibrobiblio = db.table('Detalle_Libro_Biblioteca')\ .where('idDetalle_Libro_Biblioteca', iddetlibro)\ .update({ 'Cantidad' : libcant }) print('Se ah realizado el prestamo.') sleep(2) opcion = False else: detalibrobiblio = db.table('Detalle_Libro_Biblioteca')\ .where('idDetalle_Libro_Biblioteca', iddetlibro)\ .update({ 'Cantidad' : libcant, 'Estado' : '0' }) print("No esta disponible el libro seleccionado.") opcion = False opcion = False else: print('Seleccione un número de la lista.\a\a') opcion = True except Exception as e: __log.info(f"{e} Dato ingresado no es un numero") print("Debe ingresar un número de la lista.\a\a") sleep(2) except KeyboardInterrupt as k: __log.info(f"{k} Interrupcion por teclado.") print("Interrupcion por teclado") sleep(2) util.Salir()
def BuscarLibros(): __log = util.log("Buscar Libro") opcion = True while opcion: try: idlibro = int(input("Ingrese id del libro que desea:\n")) detallelibro = db.table('Detalle_Libro_Autor')\ .join('Autor', 'Detalle_Libro_Autor.idAutor', '=', 'Autor.idAutor')\ .join('Libro', 'Detalle_Libro_Autor.idLibro', '=', 'Libro.idLibro')\ .join('Editorial', 'Editorial.idEditorial', '=', 'Libro.idEditorial')\ .join('Detalle_Libro_Biblioteca', 'Detalle_Libro_Biblioteca.idLibro', '=', 'Libro.idLibro')\ .join('Biblioteca', 'Biblioteca.idBiblioteca', '=', 'Detalle_Libro_Biblioteca.idBiblioteca')\ .where('Detalle_Libro_Biblioteca.idLibro',idlibro).where('Estado', '1').get() print('Id', 'Nombre Libro\t\t', 'Nombre Autor\t', 'Nombre Editorial', 'Cantidad', 'Estado', 'Biblioteca', sep="\t") if detallelibro: for row in detallelibro: print(row.idDetalle_Libro_Biblioteca, row.Nombre_Libro, "", row.Nombre_Autor, "", row.Nombre_Editorial, "", row.Cantidad, row.Estado, row.Nombre_Biblioteca, sep="\t") opcion = False else: print('Ingrese el id de un libro valido.\a') sleep(2) opcion = True except Exception as e: __log.info(f"{e} El dato no es un numero.") print("Escoja un número de la lista.\a") except KeyboardInterrupt as k: __log.info(f"{k} Interrupcion por teclado") print("Interrupcion por teclado\a") sleep(2) util.Salir()
def Devolucion(): __log = util.log("Devolucion") opcion = True while opcion: try: idPrestamo = int(input("Ingrese id para devolucion:\n")) prestamo = db.table('Prestamo')\ .join('Detalle_Libro_Biblioteca', 'Detalle_Libro_Biblioteca.idDetalle_Libro_Biblioteca', '=', 'Prestamo.idDetalle_Libro_Biblioteca')\ .where('Prestamo.idPrestamo', idPrestamo)\ .first() if prestamo: db.table('Prestamo').where('Prestamo.idPrestamo', idPrestamo).update({'Estado': '0'}) if prestamo.Cantidad == 0: db.table('Detalle_Libro_Biblioteca')\ .where('idDetalle_Libro_Biblioteca', prestamo.idDetalle_Libro_Biblioteca)\ .update({ 'Cantidad' : prestamo.Cantidad + 1, 'Estado' : '1' }) else: db.table('Detalle_Libro_Biblioteca')\ .where('idDetalle_Libro_Biblioteca', prestamo.idDetalle_Libro_Biblioteca)\ .update({ 'Cantidad' : prestamo.Cantidad + 1 }) print("La devolucion se ah realizado.") sleep(2) opcion = False else: print("Ingrese un dato valido.\a\a") opcion = True except Exception as e: __log.info(f"{e} Dato ingresado no es un numero") print("Ingrese un número de la lista.\a") sleep(2) except KeyboardInterrupt as k: __log.info(f"{k} Interrupcion por teclado.") print("Interrupcion por teclado") sleep(2) util.Salir()
def BuscarTipoDoc(): __log = util.log("Buscar Tipo Documento") opcion = True while opcion: try: id_Tipo_Doc = int(input("Ingresar id del tipo de documento:\n")) TipoDoc = db.table('tipo_documento').where('idTipo_Documento', id_Tipo_Doc).first() if TipoDoc: return id_Tipo_Doc else: sleep(2) input('Ingrese un tipo de documento valido.\a') opcion = True except Exception as e: __log.info(f"{e} Dato ingresado es una letra") sleep(2) print("Debe ingresar un número de la lista.\n\a") except KeyboardInterrupt as k: __log.info(f"{k} Interrupcion por teclado") print("Interrupcion por teclado\n\a", k) util.Salir()
# Load trained weights (fill in path to trained weights here) assert model_path != "", "Provide path pointed to trained weights" print("Loading weights from: ", model_path) model.load_weights(filepath=model_path, source='ckpt') if config.GPU_COUNT > 0: model.cuda() # Test on some random images image_ids = np.random.choice(dataset_test.image_ids, 1) for image_id in image_ids: image, image_meta, gt_class_id, gt_bbox, gt_mask = dataset_test.load_image_gt( image_id, inference_config, chw=True) utils.log("original_image", image) utils.log("image_meta", image_meta) utils.log("gt_class_id", gt_class_id) utils.log("gt_bbox", gt_bbox) utils.log("gt_mask", gt_mask) visualize.display_instances(image.transpose(1, 2, 0), gt_bbox, gt_mask, gt_class_id, dataset_train.class_names, figsize=(8, 8)) results = model.detect(images=image[np.newaxis, :], metas=image_meta[np.newaxis, :])[0]
def ListAllTipoDoc(): __log = util.log("Tipo Documento") td = TipoDocumento() tipodoc = td.all() for row in tipodoc: print(row.idTipo_Documento, row.Descripcion, sep='\t')
def train_model(self, train_dataset, val_dataset, learning_rate, epochs, layers): """ 1.读取数据 2.遍历epoch 3.构造优化器 :param train_dataset: :param val_dataset: :param learning_rate: :param epochs: :param layers: :return: """ # Train utils.log("\nStarting at epoch {}. LR={}\n".format( self.epoch, learning_rate)) utils.log("Checkpoint will be saved at: {}\n".format( self.checkpoint_path)) self.set_trainable(layers) # data iterator # not generator! trainset_iter = DataLoader(train_dataset, batch_size=1, shuffle=True, num_workers=4) valset_iter = DataLoader(val_dataset, batch_size=1, shuffle=True, num_workers=4) # Optimizer object # Add L2 Regularization # Skip gamma and beta weights of batch normalization layers. trainables_wo_bn = [ param for name, param in self.named_parameters() if param.requires_grad and 'bn' not in name ] trainables_only_bn = [ param for name, param in self.named_parameters() if param.requires_grad and 'bn' in name ] optimizer = optim.SGD([{ 'params': trainables_wo_bn, 'weight_decay': self.config.WEIGHT_DECAY }, { 'params': trainables_only_bn }], lr=learning_rate, momentum=self.config.LEARNING_MOMENTUM) for epoch in range(self.epoch, epochs + 1): utils.log("Epoch {}/{}.".format(epoch, epochs)) # Training train_loss = self.train_epoch(trainset_iter, optimizer, self.config.TRAIN_STEPS_PER_EPOCH) # Validation val_loss = self.valid_epoch(valset_iter, self.config.VAL_STEPS_PER_EPOCH) # Statistics self.train_loss_history.append(train_loss) self.val_loss_history.append(val_loss) visualize.plot_loss(self.train_loss_history, self.val_loss_history, save=True, log_dir=self.log_dir) # Save model torch.save(self.state_dict(), self.checkpoint_path.format(epoch=epoch)) if self.epoch < epochs + 1: self.epoch = epochs + 1 else: utils.log("Train has been done over in current stage !!!")
def write_query(self): # Write results to the file query_results mail_adaptor = mailing.MailAdapter() mail_adaptor.open_file("query_results.txt") q_data = self.query(self.create_query()) if q_data is not None: print(q_data) data_organizations = q_data['data']['organizationSummaryQuery'][ 'organizations']['edges'] print("Data successfully retrieved...") for company in data_organizations: # Access company data data_stem = company["node"] org_id = data_stem["id"] org_data = self.query( self.org_info_query(org_id))['data']['organization'] funding = data_stem["companyPersona"]["lastFundingAmount"] funding_amount = "Undisclosed" currency = "" funding_date_info = data_stem["companyPersona"][ "lastFundingDate"] funding_date = "Undisclosed" if org_data['domains']: domain = org_data['domains'][0]['domain'] else: domain = "-" if org_data['offices']: location = org_data['offices'][0]['location']['region'][ 'name'] else: location = "-" if funding is not None: funding_amount = str(data_stem["companyPersona"] ["lastFundingAmount"]["value"]) currency = data_stem["companyPersona"][ "lastFundingAmount"]["currency"] funding_amount = utils.number_formatter(funding_amount) if funding_date_info is not None: funding_date = data_stem["companyPersona"][ "lastFundingDate"] # Assign company trello = db_dictionary.get_functions()['trello'] if trello: assign.add_assignment(domain) # Write company data in html table format mail_adaptor.open_row() # image, name, description company_image = mail_adaptor.adapt_image( meta_extractor.get_image(domain)) mail_adaptor.add_header_data(company_image, 5) mail_adaptor.add_header_data( mail_adaptor.make_bold(data_stem["name"]), 5) mail_adaptor.add_header_data( meta_extractor.get_description(domain), 5) columns = [ "Stage", "Last Funding", "Last Funding Date", "Domain", "Region" ] mail_adaptor.add_row_data(columns) values = [ data_stem["companyPersona"]["companyStage"], funding_amount + " " + currency, funding_date, domain, location ] mail_adaptor.add_row_data(values) mail_adaptor.close_row() else: utils.log("Returned data is null...") return False mail_adaptor.close_file() return True
def MenuPrincipal(): __log = util.log("Principal") opcion = True tipodoc.ListAllTipoDoc() idtipodoc = tipodoc.BuscarTipoDoc() while opcion: idlector = lector.BuscarDni(idtipodoc) if idlector: tplmenu = ('1. Prestamo', '2. Devolucion', '3. Mantenimiento') menu = util.Menu("BIBLIOTECA", tplmenu) resmenu = menu.MostrarMenu() if resmenu == 1: libro.ListAllLibros() libro.BuscarLibros() prestamo.SavePrestamo(idlector) elif resmenu == 2: prestamo.ListPrestamo(idlector) prestamo.Devolucion() elif resmenu == 3: tplmant = ('1. Autor', '2. Editorial', '3. Libro', '4. Asignar Autor al Libro', '5. Asignar Libro a la Biblioteca') mant = util.Menu("MANTENIMIENTO", tplmant) resmant = mant.MostrarMenu() if resmant == 1: opau = True while opau: tplautor = ('1. Listar Autor', '2. Agregar Autor', '3. Modificar Autor', '4. Regresar') aut = util.Menu("AUTOR", tplautor) resaut = aut.MostrarMenu() if resaut == 1: autor.ListAllAutor() opau = True elif resaut == 2: autor.AddAutor() opau = True elif resaut == 3: autor.UpdateAutor() opau = True elif resaut == 4: opau = False else: util.Salir() elif resmant == 2: oped = True while oped: tpledit = ('1. Listar Editorial', '2. Agregar Editorial', '3. Modificar Editorial', '4. Regresar') edit = util.Menu("EDITORIAL", tpledit) resedit = edit.MostrarMenu() if resedit == 1: editorial.ListAllEditorial() oped = True elif resedit == 2: editorial.AddEditorial() oped = True elif resedit == 3: editorial.UpdateEditorial() oped = True elif resedit == 4: oped = False else: util.Salir() elif resmant == 3: oplib = True while oplib: tpllib = ('1. Listar Libro', '2. Agregar Libro', '3. Modificar Libro', '4. Regresar') lib = util.Menu("LIBRO", tpllib) reslib = lib.MostrarMenu() if reslib == 1: libro.ListaLibro() oplib = True elif reslib == 2: editorial.ListAllEditorial() libro.AddLibro() oplib = True elif reslib == 3: libro.UpdateLibro() oplib = True elif reslib == 4: oplib = False else: util.Salir() elif resmant == 4: oplibaut = True while oplibaut: tpllibaut = ('1. Listar Libro - Autor', '2. Agregar Libro - Autor', '3. Regresar') libaut = util.Menu("LIBRO - AUTOR", tpllibaut) reslibaut = libaut.MostrarMenu() if reslibaut == 1: libro.ListAllLibros() oplibaut = True elif reslibaut == 2: autor.ListAllAutor() libro.AddLibroAutor() oplibaut = True elif reslibaut == 3: oplibaut = False else: util.Salir() elif resmant == 5: oplibbib = True while oplibbib: tpllibbib = ('1. Listar Libro - Biblioteca', '2. Agregar Libro - Biblioteca', '3. Regresar') libbib = util.Menu("LIBRO - BIBLIOTECA", tpllibbib) reslibbib = libbib.MostrarMenu() if reslibbib == 1: libro.ListLibBib() oplibbib = True elif reslibbib == 2: libro.AddLibBib() oplibbib = True elif reslibbib == 3: oplibbib = False else: util.Salir() else: util.Salir() else: util.Salir() else: opcion = True