def get_context_data(self, **kwargs): helper = utils() kwargs = super(UpdateAppointmentStatus, self).get_context_data(**kwargs) # if the doctor click the update button appointment_id = self.request.GET["appointment_id"] if self.request.GET['start'] == '1': # start the session db_sync(appointment_id, {"status": STATUS_IN_SESSION}) # update the session start time dbutils.update(appointment_id, {"session_start_time": helper.get_current_time()}) # get waiting time and update waiting_duration arrive_time = dbutils.query(appointment_id, "arrive_time") waiting_duration = helper.get_duration(arrive_time, helper.get_current_time()) dbutils.update(appointment_id, {"waiting_duration": waiting_duration}) else: # end the session db_sync(appointment_id, {"status": STATUS_COMPLETED}) # get session time session_start_time = dbutils.query(appointment_id, "session_start_time") session_time = helper.get_duration(session_start_time, helper.get_current_time()) dbutils.update(appointment_id, {"session_duration": session_time}) messages.success(self.request, "You have updated the appointment status successfully!") return kwargs
def get_context_data(self, **kwargs): kwargs = super(PatientCheckIn, self).get_context_data(**kwargs) helper = utils() # get first_name and last_name from url first_name = self.request.GET.get("first_name") last_name = self.request.GET.get("last_name") full_name = first_name + " " + last_name # get date_of_birth from url date_of_birth = self.request.GET.get("date_of_birth") # get all appointments try: appointments_iterator = helper.get_all_appointments(first_name, last_name, date_of_birth) except Exception: # indication of whether there exists appointment today. 1 denote there is no appointment today kwargs["err"] = 1 return kwargs result = helper.get_appointments_render(appointments_iterator) # compare the newest result with db, if there is new data, add it. dbutils.add(result) # pass all appointment to the page kwargs["appointments"] = result # patient name kwargs["last_name"] = last_name kwargs["first_name"] = first_name kwargs["pid"] = helper.get_patient(first_name, last_name, date_of_birth)["id"] # size for no appointments kwargs["size"] = len(result) return kwargs
def transition_terminar(self): "Crear las lineas de producto en la venta y finalizar wizard" logger.info('Borrar lineas del producto temporal al Finalizar Wizard') pool = Pool() t = Transaction() ut = utils() Sale = pool.get('sale.sale') sale = Sale.search([('id', '=', t.context['active_id'])])[0] OrdenTrabajo = pool.get('sale_printery_budget.orden_trabajo') SaleLine = pool.get('sale.line') interior = OrdenTrabajo.search([('id', '=', self.elegir_interior.orden_trabajo.id)])[0] sale_lines = SaleLine.search(['id_interior', '=', interior.id_interior]) # Borrar lineas anteriores y orden de trabajo anterior SaleLine.delete(sale_lines) OrdenTrabajo.delete([interior]) # Genero lineas nuevas. ut.interior = self.interior lineas_venta = ut.creo_lineas_de_venta() ut.creo_orden_trabajo(sale, lineas_venta) ut.crear_otra_cantidad_base(sale) ut.borrar_productos_temporales(self.interior.id_wizard_start) return 'end'
def transition_terminar(self): "Crear las lineas de producto en la venta y finalizar wizard" logger.info('Borrar lineas del producto temporal al Finalizar Wizard') t = Transaction() Sale = Pool().get('sale.sale') sale = Sale.search([('id', '=', t.context['active_id'])])[0] ut = utils() ut.interior = self.interior if hasattr(self.interior, 'producto_papel') == False or self.interior.producto_papel is None: # Primera vez que se ejecuta la pantalla interior. try: ut.borrar_productos_temporales(self.interior.id_wizard_start) except: logger.info('Primera vez que se ejecuta la pantalla. No se pudo borrar productos temporales') # Debo verificar que la venta ya tiene lineas de venta. Si es así, # calcular otras cantidades y return 'end'. if sale.lines: ut.crear_otra_cantidad_base(sale) return 'end' lineas_venta = ut.creo_lineas_de_venta() ut.creo_orden_trabajo(sale, lineas_venta) ut.crear_otra_cantidad_base(sale) ut.borrar_productos_temporales(self.interior.id_wizard_start) return 'end'
def __init__(self): self.path = None self.data = loader() self.processedmetro = None self.windir = None self.weather = None self.meanmetro = None self.helper = utils()
def get_context_data(self, **kwargs): helper = utils() kwargs = super(TimeStat, self).get_context_data(**kwargs) appointment_id = self.request.GET['appointment_id'] """ get the time stat """ kwargs["time_stat"] = helper.get_time_stat(appointment_id) return kwargs
def __init__(self): self.utils = utils() self.prefix = 'l_' self.suffix = 'fk' self.shoulder = ('%sshoulder%s' % (self.prefix, self.suffix)) self.elbow = ('%selbow_%s' % (self.prefix, self.suffix)) self.wrist = ('%swrist_%s' % (self.prefix, self.suffix)) self.radius = 0.2 self.scale = 1
def Greedy_Search(self): graph = Graph() funcUtils = utils() funcUtils.read_file_first_space('Cidades_grafo.txt', graph) funcUtils.read_file_and_connect('Cidades_grafo.txt', graph) heuristics = {} funcUtils.create_heuristics('Cidades_Faro.txt', heuristics) nodeStart = input("What is the source node?\n") funcUtils.Greedy_Search_util(graph, heuristics, nodeStart.capitalize(), 'Faro')
def depth_Limited_Search(self): graph = Graph() funcUtils = utils() funcUtils.read_file_first_space('Cidades_grafo.txt', graph) funcUtils.read_file_and_connect('Cidades_grafo.txt', graph) nodeStart = input("What is the source node?\n") nodeGoal = input("What is the goal node?\n") limit = input("what is the limit?\n") funcUtils.depth_Limited_Search_util(graph, nodeStart.capitalize(), nodeGoal.capitalize(), limit)
def uniform_cost_search(self): graph = Graph() funcUtils = utils() funcUtils.read_file_first_space('Cidades_grafo.txt', graph) funcUtils.read_file_and_connect('Cidades_grafo.txt', graph) nodeStart = input("What is the source node?\n") nodeGoal = input("What is the goal node?\n") funcUtils.uniform_cost_search_util(graph, nodeStart.capitalize(), nodeGoal.capitalize(), verbose=True)
def default_interior(self, fields): "Crear las lineas de producto en la venta" logger.info('default_retomar_calcular_papel_interior') pool = Pool() ut = utils() OrdenTrabajo = pool.get('sale_printery_budget.orden_trabajo') interior = OrdenTrabajo.search([('id', '=', self.elegir_interior.orden_trabajo.id)])[0] # Borrar producto temporal anterior ut.interior = interior ut.borrar_productos_temporales(interior.id_interior) # Copiar la orden de trabajo en modelo interior res = { 'cantidad': interior.cantidad, 'sale_id': interior.sale.id, 'calle_horizontal': interior.calle_horizontal, 'calle_vertical': interior.calle_vertical, 'cantidad': interior.cantidad, 'colores_frente': interior.colores_frente, 'colores_dorso': interior.colores_dorso, 'es_tapa': interior.es_tapa, 'tipo_papel': interior.tipo_papel.id, 'sin_pinza': interior.sin_pinza, 'formato_pliego': interior.formato_pliego, 'categoria': interior.categoria, 'ancho': interior.ancho, 'altura': interior.altura, 'postura_papel': interior.postura_papel, 'postura_trabajo': interior.postura_trabajo, #'maquina': interior.maquina.id, 'tinta_superficie_cubierta': interior.tinta_superficie_cubierta, 'tinta': interior.tinta.id, 'solapa': interior.solapa, 'lomo': interior.lomo, 'gramaje': interior.gramaje, 'id_wizard_start': interior.id_interior, 'velocidad_maquina': interior.velocidad_maquina, 'plancha_adicional': 0, 'cantidad_paginas': interior.cantidad_paginas, } if hasattr(interior, 'doblado') != False and interior.doblado is not None: res['doblado'] = interior.doblado.id if hasattr(interior, 'encuadernado') != False and interior.encuadernado is not None: res['encuadernado'] = interior.encuadernado.id res['cantidad_broches'] = interior.cantidad_broches if hasattr(interior, 'laminado') != False and interior.laminado is not None: res['laminado'] = interior.laminado.id res['laminado_orientacion'] = interior.laminado_orientacion return res
def __init__(self, args, sess): self.sess = sess if args.train: self.mode = 'all' elif args.pretrain: self.mode = 'pretrain_generator' else: self.mode = 'test' #model config self.rec_base = 0.0 self.rec_weight = 0.5 self.discriminator_iterations = 3 self.reconstructor_iterations = 3 self.pretrain_discriminator_steps = 501 self.coverage_weight = 0.1 self.lmbda = 10 self.source_sequence_length = args.source_length self.code_sequence_length = args.code_length self.batch_size = args.batch_size self.num_steps = args.num_steps self.load_model = args.load self.saving_step = args.saving_step self.result_path = args.test_output self.input_path = args.test_input #trivial things self.generator_lstm_length = [ self.source_sequence_length + 1 for _ in range(self.batch_size) ] self.code_lstm_length = [ self.code_sequence_length + 1 for _ in range(self.batch_size) ] self.utils = utils(args) #the model of generator, reconstructor, discriminator will be save in seperately directory self.model_dir = args.model_dir """ if not os.path.exists(os.path.join(self.model_dir,'code')): os.makedirs(os.path.join(self.model_dir,'code')) if self.mode == 'all': subprocess.call('cp ./*.py '+ os.path.join(self.model_dir,'code'), shell=True) """ self.vocab_size = self.utils.vocab_size self.word_embedding_dim = 300 self.BOS = 1 self.EOS = 0 self.build_model() self.tensorflow_init()
def __init__(self): self.utils = utils() self.config = self.utils.load_config() self.json_f = self.config['json'] fp = open(self.json_f, 'r') self.json = json.load(fp) fp.close() self.db = MySQLDatabase(self.json['db_name'], host = self.json['db_ip'], port = self.json['db_port'], user = self.json['db_user'], passwd = self.json['db_pwd'])
def __init__(self): self.utils = utils() self.config = self.utils.load_config() self.json_f = self.config['json'] fp = open(self.json_f, 'r') self.json = json.load(fp) fp.close() #generate schema self.schema = self.gen_sql_schema() #inject schema (create/drop DB if needed) self.inject_schema()
def get_context_data(self, **kwargs): helper = utils() kwargs = super(Demographic, self).get_context_data(**kwargs) appointment_id = self.request.GET['appointment_id'] patient_id = self.request.GET['patient_id'] patient_detail = helper.get_patient_id(patient_id) # get the recent body info boiler_plate_body = PatientBodyDbUtils.get_recent_body_info(patient_id) boiler_plate_important = helper.get_init_dict(patient_detail) # give the patient a boilerplate form = DemographicForm(initial=helper.merge(boiler_plate_body, boiler_plate_important)) kwargs['form'] = form kwargs['appointment_id'] = appointment_id kwargs['patient_id'] = patient_id return kwargs
def get_context_data(self, **kwargs): helper = utils() kwargs = super(AddAppointmentStatus, self).get_context_data(**kwargs) my_request_get = self.request.GET # construct the params for post res = {'doctor': DOCTOR_ID, 'duration': my_request_get['duration'], 'exam_room': my_request_get['exam_room'], 'office': OFFICE_ID, 'patient': my_request_get['patient_id'], 'scheduled_time': my_request_get['scheduled_time']} try: helper.post_appointment(res) messages.success(self.request, "You have added the appointment successfully!") except Exception: messages.error(self.request, "add failure!") kwargs["patient_id"] = my_request_get['patient_id'] return kwargs
def ToDoList(request): """ to-do list app """ helper = utils() if request.method == 'POST': form = ListForm(request.POST or None) if form.is_valid(): form.save() all_items = List.objects.all messages.success(request, "new item has been added successfully!!!") return render(request, "to_do_list.html", {'all_items': all_items}) else: all_items = List.objects.all return render(request, "to_do_list.html", {'all_items': all_items})
def get_context_data(self, **kwargs): kwargs = super(DoctorWelcome, self).get_context_data(**kwargs) helper = utils() # get doctor info doctor = helper.get_doctor(DOCTOR_ID) # get all today's appointments for the doctor appointments_iterator = helper.get_all_appointments(doctor_id=DOCTOR_ID) # iterate result = helper.get_appointments_render(appointments_iterator) # doctor first name and last name for the welcome kwargs['first_name'] = doctor['first_name'] kwargs['last_name'] = doctor['last_name'] kwargs['appointments'] = result kwargs["size"] = len(result) # get average waiting time for today kwargs['average_waiting_time'] = helper.get_average_waiting_time(result) return kwargs
def save_apk_info_file(self, button): apk_path = utils().save_file() text = '' if apk_path is not '': f = open(apk_path, 'w') start_iter = self.main_info_textview.get_buffer().get_start_iter() end_iter = self.main_info_textview.get_buffer().get_end_iter() text = self.main_info_textview.get_buffer().get_text( start_iter, end_iter, True) start_iter = self.permission_textview.get_buffer().get_start_iter() end_iter = self.permission_textview.get_buffer().get_end_iter() text += self.permission_textview.get_buffer().get_text( start_iter, end_iter, True) start_iter = self.signature_textview.get_buffer().get_start_iter() end_iter = self.signature_textview.get_buffer().get_end_iter() text += self.signature_textview.get_buffer().get_text( start_iter, end_iter, True) f.write(text) f.close()
def get_context_data(self, **kwargs): helper = utils() kwargs = super(UpdatePatientInfo, self).get_context_data(**kwargs) my_request_get = self.request.GET # get appointment id appointment_id = my_request_get["appointment_id"] # get current time current_time = helper.get_current_time() # update in the local db hange the status on the remote db db_sync(appointment_id, {"status": STATUS_ARRIVED, "arrive_time": current_time}) helper.change_appointment_status(appointment_id, STATUS_ARRIVED) # update the demographic data patient_id = my_request_get["patient_id"] helper.update_patient_info(patient_id, helper.get_init_dict(my_request_get)) # update the patient body information to the database PatientBodyDbUtils.add(helper.get_body_info_dict(my_request_get)) messages.success(self.request, "You have checked in successfully! Please wait patiently :-)") return kwargs
def default_interior(self, fields): "Crear las lineas de producto en la venta" logger.info('default_interior') ## Desde aca puedo crear las lineas de los productos. # Primero preguntar si cls.interior.producto_papel es distinto de None. # Si es asi, entonces cargo las lineas. t = Transaction() Sale = Pool().get('sale.sale') ut = utils() ut.interior = self.interior sale = Sale.search([('id', '=', t.context['active_id'])])[0] res = { 'categoria': 'folleto', 'calle_horizontal': Decimal('0.5'), 'calle_vertical': Decimal('0.5'), 'colores_frente': 0, 'colores_dorso': 0, 'plancha_adicional': 0, 'cantidad_paginas': 4, 'cantidad': sale.cantidad, 'sale_id': sale.id, } if hasattr(self.interior, 'producto_papel') == False or self.interior.producto_papel is None: # Primera vez que se ejecuta la pantalla interior. try: ut.borrar_productos_temporales(self.interior.id_wizard_start) except: logger.info('Primera vez que se ejecuta la pantalla. No se pudo borrar productos temporales') return res lineas_venta = ut.creo_lineas_de_venta() ut.creo_orden_trabajo(sale, lineas_venta) ut.crear_otra_cantidad_base(sale) ut.borrar_productos_temporales(self.interior.id_wizard_start) return res
def get_apk_path(): path = utils().select_file() return path
def classify(self,dataSet,labels,inputVector): ''' tile(input,A) repeats the input A times. We want the input to be replicated m times, but no replication along columns. So, tile args = (dataSet.numRows,1) ''' diffMat = tile(inputVector, (dataSet.shape[0],1)) - dataSet #calculate Euclidean distance = sqrt((in.p1-data.p1)^2 +(in.p2-data.p2)^2+...) sqDiffMat = diffMat**2 sqDistances = sqDiffMat.sum(axis=1) distances = sqDistances**0.5 sortedDistIndices = distances.argsort() classCount={} #for each entry in the top k, find the label for that entry, and inc count of that label. for i in range(self.k): labelI = labels[sortedDistIndices[i]] classCount[labelI] = classCount.get(labelI,0) +1 #find the most frequent label. sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1),reverse=True) return sortedClassCount[0][0] if __name__=='__main__': kNNObject = kNN(4) #[group,labels] = kNNObject.createTestDataSet() utilityObject = utils() [group,labels] = utilityObject.file2Matrix('../datingTestSet.txt') classifiedLabel = kNNObject.classify(group,labels,[999,-222,0.1]) print classifiedLabel fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(group[:,1],group[:,2]) plt.show()
ikHandle = self.createIkHandle()[0] # Create and constrain arm ik handle cmds.pointConstraint(wristControl, ikHandle) cmds.poleVectorConstraint(poleVector, ikHandle) # Create null groups self.utils.createNullGroup(wristControl) self.utils.createNullGroup(poleVector) # Lock controller attributes self.utils.lockAttrs(wristControl, rotate=True, scale=True, visibility=True) self.utils.lockAttrs(poleVector, rotate=True, scale=True, visibility=True) # Create an Arm Rig myUtils = utils() myIkArm = IKSkeleton() myFkArm = FKSkeleton() prefix = 'l_' armBindJoints = ['%sshoulder_bind' % prefix, '%selbow_bind' % prefix, '%swrist_bind' % prefix] # Create IK Armutils myUtils.jointCheck(armBindJoints) ikJoints = myUtils.createJoints(armBindJoints, myIkArm.prefix, myIkArm.suffix, myIkArm.radius) myIkArm.createIkControls() # Create Fk Arm fkJoints = myUtils.createJoints(armBindJoints, myFkArm.prefix, myFkArm.suffix, myFkArm.radius) myFkArm.createFkControls(fkJoints, armBindJoints) # Position IK/FK Switcher
# app.py - a flask api using flask_restful from flask import Flask, request, jsonify from flask_cors import CORS from utils import * import json import uclnlp_service_pb2_grpc as pb2_grpc import uclnlp_service_pb2 as pb2 from config import config, rpc_endpoints app = Flask(__name__) CORS( app ) # to enable CORS for the routes, unless from the front end response becomes Network Error @app.route('/get_score', methods=['GET']) def get_score(): url = request.args.get('url') result = utils.get_stance_classify(url) return str(result) proxy_port = 7005 utils = utils() if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=proxy_port)
import cv2 import numpy as np import PIL.Image import matplotlib.pyplot as plt from utils import * import time # Set this variable to False if you want to view a background image # and also set the path to your background image # Background Image Source: https://pixabay.com/photos/monoliths-clouds-storm-ruins-sky-5793364/ BLUR = True BG_PTH = "bg1.jpg" utilsInst = utils() utilsInst.init() # Load the DeepLabv3 model to memory utilsInst.load_model() # Read the background image to memory bg_image = cv2.imread(BG_PTH) bg_image = cv2.cvtColor(bg_image, cv2.COLOR_BGR2RGB) # Start a video cam session video_session = cv2.VideoCapture(0) # Define a blurring value kernel size for cv2's Gaussian Blur blur_value = (51, 51) # Define two axes for showing the mask and the true video in realtime # And set the ticks to none for both the axes
def db_sync(appointment_id, params): helper = utils() dbutils.update(appointment_id, params) helper.change_appointment_status(appointment_id, params['status'])
def get_context_data(self, **kwargs): helper = utils() kwargs = super(NewAppointmentForm, self).get_context_data(**kwargs) patient_id = self.request.GET['patient_id'] kwargs["patient_id"] = patient_id return kwargs