Beispiel #1
0
class DBSchema(object):

    def __init__(self):
        self.dao = DAO()

    @staticmethod
    def bootstrap():
        return [
            """
              CREATE TABLE IF NOT EXISTS Episode(
                  id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
                  show_name VARCHAR(255) NOT NULL,
                  season_number INTEGER DEFAULT NULL,
                  episode_number INTEGER DEFAULT NULL,
                  torrent_path VARCHAR(255) DEFAULT NULL,
                  torrent_origin VARCHAR(255) DEFAULT NULL,
                  downloaded_at DATE
              )
            """
        ]

    @staticmethod
    def destroy():
        return [
            """
                DROP TABLE IF EXISTS Episode;
            """
        ]

    def execute(self, requests):
        for request in requests:
            self.dao.run(request, commit=True)
Beispiel #2
0
def update_value():
    try:
        column = request.form.get("column", None)
        value = request.form.get(column, None)

        surgeon_id = request.form.get("surgeon_id", None)
        
        if value and surgeon_id:
            dao = DAO()
            success = dao.update(column, surgeon_id, value)
            return jsonify(success)
            # if column == "training":
            #     value = json.loads(value)
            #     dao = DAO()
            #     success = dao.update_training(value, surgeon_id)
            #     return jsonify(success)
        
            # else:
            #     dao = DAO()
            #     success = dao.update(column, surgeon_id, value)
            #     return jsonify(success)
        
        else:
            pass
    
    except Exception as e:
        raise e
        return jsonify({"Error": "Something went wrong"})    
def getListTempSensors():
    dao = DAO()
    sensors = dao.getListTempSensors()
    t_list = []
    for sensor in sensors:
        t_list.append({'id_sensor': sensor.id, 'name' : sensor.name,'directory' : sensor.directory_number, 'current' : sensor.current_value, 'timestamp' : sensor.timestamp}) 
    return json.dumps(t_list)
Beispiel #4
0
 def get(self):
     '''
     return all the certs
     '''
     cert_col = DAO().get_collection("certificates")
     certs = cert_col.find({}, {'_id': 0})
     return list(certs)
def unzip(standardization_input):
    dao = DAO()
    pubMedRetrievals = dao.findAllForUnzip(PubMedRetrieval)
    for pubMedRetrieval in pubMedRetrievals:
        print pubMedRetrieval.filename
        file = os.path.join(
            standardization_input + "/" + pubMedRetrieval.download_path,
            pubMedRetrieval.filename)
        xml_file_path = file + ".xml"
        if os.path.isfile(file):
            with open(xml_file_path, 'w') as xml_file:
                with gzip.open(
                        os.path.join(
                            standardization_input + "/" +
                            pubMedRetrieval.download_path,
                            pubMedRetrieval.filename), 'rb') as f:
                    file_content = f.read()
                    xml_file.write(file_content)
                    xml_file.flush()
                    xml_file.close()
                    print pubMedRetrieval.filename + " unzip"
                    pubMedRetrieval.unzip = 1
                    pubMedRetrieval.unzip_datetime = datetime.now()
                    pubMedRetrieval.unzip_path = pubMedRetrieval.download_path
                    dao.save(pubMedRetrieval)
        else:
            print("The file " + file +
                  " not exist, please review and download again ")
Beispiel #6
0
def insert_csv_to_db(csvfile, siteName='Ebay'):
	db = Database()
	dao = DAO(db)

	item_ = Item()
	brand_ = Brand()
	category_ = Category()

	with open(csvfile, 'r') as file:
		f = csv.reader(file,delimiter = ',')
		for row in f:
			try:

				item_.category = classify(item_.imagePath, CATEGORY)
				if item_.category is None:
					raise ValueError("Category cannot be Null")

				item_.site = siteName
				item_.itemName = row[1]
				item_.itemPrice = row[2]
				item_.url = row[0]
				item_.imagePath = row[3]
				item_.brand = 'NULL'
				brand_.brandName = 'NULL'

				category_.catName = item_.category
				category_.catCode = ''

				dao.insert_item(item=item_, brand=brand_, category=category_)
			except Exception as e:
				print("Error{}".format(e) )
				pass
def getListCameraSensors():
    dao = DAO()
    sensors = dao.getListCameraSensors()
    c_list = []
    for sensor in sensors:
        c_list.append({'id_sensor': sensor.id, 'name' : sensor.name,'ip_address' : sensor.ip_address, 'current' : sensor.current_value, 'login' : sensor.login, 'password' : sensor.password}) 
    return json.dumps(c_list)
Beispiel #8
0
    def test_rate_db(self):
        dao = DAO(self.dsn)

        registry = Registry('test')
        registry.save_data("% BTG 1", dao)
        self.assertEqual(dao.get_member('test'), [('test', 600, None, None)])
        self.assertEqual(dao.get_conditions(), [('test', 1, 'BTG', '%', 1.0)])
Beispiel #9
0
 def get(self, id):
     '''
     verify a certificate according to id
     '''
     cert_col = DAO().get_collection("certificates")
     cert = cert_col.find_one({'id': URN_UUID_PREFIX + id}, {'_id': 0})
     return verify_certificate_json(cert)
def getListDoorSensors():
    dao = DAO()
    sensors = dao.getListDoorSensors()
    d_list = []
    for sensor in sensors:
        d_list.append({'id_sensor': sensor.id, 'name' : sensor.name,'pin' : sensor.pin_number, 'current' : sensor.current_value ,'timestamp' : sensor.timestamp})
    return json.dumps(d_list)
def setTempSensor():
    idSensor = request.form['id_capt_temp']
    nameSensor =u'CAPTEUR'
    min_tempSensor = request.form['capt_min_tmp']
    max_tempSensor = request.form['capt_max_tmp']
    dao = DAO()
    dao.setTempSensor(id_sensor=int(idSensor), name=nameSensor,min_temp=int(min_tempSensor),max_temp=int(max_tempSensor))
    return min_tempSensor+" "+max_tempSensor+" "+idSensor
Beispiel #12
0
def tos():

    try:
        dao = DAO()
        tos_content = dao.get_page_content("tos")
        return render_template("tos.html", content = tos_content)

    except Exception as e:
        return "Your request cannot be processed"
Beispiel #13
0
def about_us():

    try:
        dao = DAO()
        
        about_us_content = dao.get_page_content("about_us")
        return render_template("about_us.html", content = about_us_content)

    except Exception as e:
        return "Your request cannot be processed"
Beispiel #14
0
def getCommunityCode(communityName):
    dao = DAO()

    querySQL = "SELECT * FROM community"
    results = dao.query(querySQL)
    for result in results:
        if result[1] == communityName:
            return result[2]

    return None
Beispiel #15
0
def why_acms():

    try:
        dao = DAO()
        
        why_acms_content = dao.get_page_content("why_acms")
        return render_template("why_acms.html", content = why_acms_content)

    except Exception as e:
        return "Your request cannot be processed"
Beispiel #16
0
def update_checkbox():
    try:
        checked = request.form.get("checked", None)
        _id = request.form.get("surgeon_id", None)
        if _id:
            dao = DAO()
            doit = dao.update("uneditable", _id, int(checked))
            return jsonify(doit)

    except Exception as e:
        print(str(e))
Beispiel #17
0
 def run_command(self, config):
     '''
        Runs the command via a subprocess
     '''
     dao = DAO(config)
     try:
         dao.put_log(str(datetime.now()) + " " + self.build_command())
         p = subprocess.check_output(self.interface + " " + self.build_command(), shell=True, stderr=subprocess.STDOUT)
         dao.put_log(str(datetime.now()) + " " + p)
     except subprocess.CalledProcessError as cpe:
         dao.put_log(str(datetime.now()) + " " + cpe.cmd)
         dao.put_log(str(datetime.now()) + " " + cpe.output)
def addStateToScenario():
    id_scenario = int(request.form['id_scenario'])
    type_sensor = request.form['type']
    id_sensor = int(request.form['id'])
    operator = request.form['operator']
    value = float(request.form['value'])
    if type_sensor != 'temperature':
	operator = u"null"

    dao = DAO()
    dao.createState(id_scenario, id_sensor, type_sensor, value, operator)
    return json.dumps({'success': 'true', 'id_scenario' : id_scenario})
Beispiel #19
0
def get_current_surgeons():
    logger = Logger()
    
    try:
        dao = DAO()
        # lat, lng = request.form["lat"], request.form["lng"]
        surgeons = dao.get_surgeons() 
        return jsonify(surgeons)

    except Exception as e:
        logger.log(str(e))
        return "Your request cannot be processed at this time"
def getListScenarios():
    dao = DAO()
    scenarios = dao.getListScenarios()
    states = dao.getListStates()
    sc_list = []
    for scenario in scenarios:
	st_list = []
	for state in states :
		if state.id_scenario == scenario.id:
			capteur = dao.getSensor(state.id_sensor, state.type_sensor)
			st_list.append({'id': state.id, 'id_capteur' : state.id_sensor, 'name': capteur.name, 'type': state.type_sensor, 'value' : state.value, 'operator' : state.operator}) 
        sc_list.append({'id': scenario.id, 'name' : scenario.name, 'states' : st_list, 'timestamp' : scenario.timestamp, 'status' : scenario.status}) 
    return json.dumps(sc_list)
Beispiel #21
0
def init_issuer_id(config):
    issuer_id = generate_issuer_file(config)
    col = DAO().get_collection("issuer_id")
    if col.find_one():
        _id = col.find_one()["_id"]
        selector = {"_id": _id}
        col.replace_one(selector, issuer_id)
    if not col.find_one():
        col.insert_one(issuer_id)
    print(issuer_id)
Beispiel #22
0
 def get(self, inp):
     query = inp["query"]
     if("city" not in query):
         return 418, "Impossible de trouver la ville ou mauvais appel (._.  )"
     if("act" in query):
         r = DAO().guess_City_byGActivity(query["city"], query["act"])
     else:
         r = DAO().guess_input_positions(query["city"])
     return {
         "code": 200,
         "header": [],
         "content": "application/json",
         "res": str.encode(JSONDecEncoder().encode(r))
         }
	def test_find(self):
		
		testDataContent = [
		  '648:abcdefghi',
		  '517:QjhWkizN5t',
		  '323:dwcIY99gTN1',
		  '653:UlfY2UvMfeuX'
		]
		data1 = DAO(testDataContent)

		found = data1.find('abcdefghi')
		assert found.tasktime == '648' and found.taskstring == 'abcdefghi'

		notFound = data1.find('nonexistent')
		assert notFound is None
def createScenario():
    name = request.form['name']
    type_sensor = request.form['type']
    id_sensor = int(request.form['id'])
    operator = request.form['operator']
    value = float(request.form['value'])
    message = request.form['message']
    time = int(request.form['time'])
    if type_sensor != 'temperature':
	operator = u"null"

    dao = DAO()
    id_scenario = dao.createScenario(name, message, time)
    dao.createState(id_scenario, id_sensor, type_sensor, value, operator)
    return json.dumps({'success': 'true', 'id_scenario' : id_scenario})
Beispiel #25
0
class Janela:
	def __init__(self):
		self.top = Tkinter.Tk()
		self.Lb1 = Listbox(self.top)
		self.L1 = Label(self.top, text="Digite o username:"******"Digite o email:")
		self.E2 = Entry(self.top, bd = 5)
		self.B = Tkinter.Button(self.top, text="Adicionar", command=self.eventoAdicionar)
		self.Br = Tkinter.Button(self.top, text="Remover", command=self.eventoRemover)
		self.L1.pack()
		self.E1.pack()
		self.L2.pack()
		self.E2.pack()
		self.dao = DAO()

		vet = self.dao.listar()
		for row in vet:
			self.Lb1.insert(row.username, row.email)
		self.Lb1.pack()

		self.B.pack()
		self.Br.pack()
		self.top.mainloop()

	def eventoAdicionar(self):
		if (str(self.E1.get()) > 0 and str(self.E2.get()) > 0):
			user = User(str(self.E1.get()), str(self.E2.get()))
			resultado = self.dao.inserir(user)
			if (resultado is True):
				self.Lb1.insert(self.Lb1.size(), user.email)
				tkMessageBox.showinfo("Foi...", "Adicionou...." )
			else:
				tkMessageBox.showinfo("Foi...", "Não Adicionou.......")
		else:
			tkMessageBox.showinfo("Foi...", "Não Adicionou.......")

	def eventoRemover(self):
	#print self.Lb1.curselection()
		if (len(self.Lb1.curselection())>0):
			print self.Lb1.get(self.Lb1.curselection()[0])
			self.dao.removerPorUsername(self.Lb1.get(self.Lb1.curselection()[0]))
			tkMessageBox.showinfo("Foi...", "Removeu....")
			self.Lb1.delete(self.Lb1.curselection())
		else:
			tkMessageBox.showinfo("Foi...", "Selecione um item....")
Beispiel #26
0
 def dbimport(sname, dbname, uname, upass):
     """Import data from db using DAO"""
     dao = DAO(sname, dbname, uname, upass)
     if dao.connect():
         dao.query()
         dao.close()
     rdict = dao.get()
     return rdict
Beispiel #27
0
def init_certificate_template(config):
    template = create_certificate_template(config)
    col = DAO().get_collection("certificate_template")
    if col.find_one():
        _id = col.find_one()["_id"]
        selector = {"_id": _id}
        col.replace_one(selector, template)
    else:
        col.insert_one(template)
    print(template)
Beispiel #28
0
 def post(self, inp):
     if("city" in inp["data"].keys()):
         return {
             "code": 200,
             "header": [],
             "content": "application/json",
             "res": str.encode(JSONDecEncoder().encode(DAO().get_City_Pos(inp["data"].getvalue("city"))))
         }
     return 418, "wait !!"
	def test_add_entry(self):

		data1 = DAO([])
		assert data1.is_empty()

		data1.add_entry('648', 'abcdefghi')

		assert not data1.is_empty()

		found = data1.find('abcdefghi')
		assert found.tasktime == '648' and found.taskstring == 'abcdefghi'

		with pytest.raises(Exception):
			data1.add_entry('648', 'abcdefghi')
			data1.add_entry('000', 'abcdefghi')
Beispiel #30
0
def calc_macros():
    food_dao = DAO()
    name = input("Enter name of food: ")
    if name == 'x':
        return None
    food_by_name = food_dao.get_foods_by_name(name)
    if food_by_name is None:
        print("No foods found")
        return None
    else:
        size = input("Enter amount: ")
        if size == 'x':
            return None
        ratio = float(size) / food_by_name.ss()
        print(f"ratio: {ratio}") # testing
        altered_food = FoodItem()
        altered_food.set_info_from_tuple(food_by_name.get_tuple())
        altered_food.proportionalize(ratio)
        return altered_food
Beispiel #31
0
def unique_latlng(*args, **kwargs):
    try:
        title = request.form.get("title", None)
        if title:
            dao = DAO()
            unique_set = []

            latlngs = dao.get_latlngs(title)
            
            for latlng_obj in latlngs:
                current_latlngs = latlng_obj["latlng"].split("|")
                for latlng in current_latlngs:
                    if latlng not in unique_set:
                        unique_set.append(latlng)

            return jsonify(unique_set)

    except Exception as e:
        return jsonify({"Error": "Something went wrong"})    
Beispiel #32
0
    def retrieve_documents(self, assessor, query_id, doc_retrieval_count):
        """
        Get documents documents from assessment index for given assessor and query id.
        If there aren't enough documents in assessor index, it will be fetched from crawled index.

        :param assessor: assessor id
        :param query_id: query id
        :param doc_retrieval_count: total docs to retrieve
        :return:
        """

        dao = DAO()

        if not dao.index_exists():
            dao.create_index()
            existing_doc_count = 0
        else:
            existing_doc_count = dao.get_doc_count(assessor, query_id)

        print 'existing count', existing_doc_count

        if existing_doc_count < doc_retrieval_count:
            dao.add_additional_docs(existing_doc_count, doc_retrieval_count,
                                    assessor, query_id)

        assessment_list = dao.retrieve_docs(assessor, query_id,
                                            doc_retrieval_count)

        doc_list = []

        for doc in assessment_list:

            doc_index_id = doc.get_index_id()
            doc_query_id = doc.get_query_id()
            doc_assessor_ = doc.get_assessor()
            doc_url = doc.get_document()
            doc_grade = doc.get_grade()

            doc_list.append({
                'index_id': doc_index_id,
                'query_id': doc_query_id,
                'assessor': doc_assessor_,
                'document': doc_url,
                'grade': doc_grade
            })

        return doc_list
Beispiel #33
0
class Test(unittest.TestCase):
    def setUp(self):
        self.dao = DAO()
        self.dao.connect()

    def tearDown(self):
        self.dao.commit()

    def testCreation(self):
        self.dao.create_db()

    def testInsertInstrument(self):
        self.dao.insert_instrument(('600000', u'浦发银行'))
Beispiel #34
0
 def get(self, inp):
     query = inp["query"]
     if ("city" not in query):
         return 418, "Impossible de trouver les installations sans ville ou mauvais appel (._.  )"
     if ("city" in query and "range" in query and "act" in query):
         r = DAO().get_installation(query["city"], query["act"], int(query["range"]))
     else:
         if ("city" in query and "range" in query and "act" not in query):
             r = DAO().get_installation(query["city"], "", int(query["range"]))
         else:
             if ("city" in query and "range" not in query and "act" in query):
                 r = DAO().get_installation(query["city"], query["act"])
             else:  # "city" in query and "range" not in query and "act" not in query
                 r = DAO().get_installation(query["city"], "")
     return {
         "code": 200,
         "header": [],
         "content": "application/json",
         "res": str.encode(JSONDecEncoder().encode(r))
     }
Beispiel #35
0
def log(ser, iSecInterval):
    dao = DAO()
    ser.flushInput()
    t0 = time.time()-iSecInterval
    try:
        while True: # Moche caca !!
            t = time.time()
            if t-t0 > iSecInterval:
                while ser.read() != 'O': pass
                # Should have used struct.unpack? Hmmm...
                a,b,x,c,d = map(ord,ser.read(5)) # maps where lists... so 2009...
                iRawO = a+b*256
                iRawA = c+d*256
                dao.newEntry(t, iRawA, iRawO)
                t0 += iSecInterval
                print time.ctime(t), DAO.RAW_TO_CELSIUS(iRawA), DAO.RAW_TO_CELSIUS(iRawO)
            time.sleep(.001)
            ser.flushInput()
    except KeyboardInterrupt:
        print 'Ending'
Beispiel #36
0
 def get(self, inp):
     query = inp["query"]
     if ("act" not in query):
         return 418, "Impossible de trouver l'activitée ou mauvais appel (._.  )"
     if ("city" in query and "range" in query):
         r = DAO().guess_Activities_byGCity(query["city"], query["act"],
                                            int(query["range"]))
     else:
         if ("city" in query):
             r = DAO().guess_Activities_byGCity(query["city"], query["act"])
         else:
             r = [
                 act["ActLib"]
                 for act in DAO().guess_input_activites(query["act"])
             ]
     return {
         "code": 200,
         "header": [],
         "content": "application/json",
         "res": str.encode(JSONDecEncoder().encode(r))
     }
Beispiel #37
0
class Test(unittest.TestCase):

    def setUp(self):
        self.dao = DAO()
        self.dao.connect()

    def tearDown(self):
        self.dao.commit()

    def testCreation(self):
        self.dao.create_db()

    def testInsertInstrument(self):
        self.dao.insert_instrument(('600000', u'浦发银行'))
Beispiel #38
0
class ReportService(object):
    mapAPI = MapApi()
    
    def __init__(self):
        self._dao = DAO()
    
    def insert(self,report):
        report = Report.fromJson(report)
        if report.latitude is not None and report.longitude is not None:
            report.address = ReportService.mapAPI.reverse_geocode(report.latitude, report.longitude)        
            
        id_ = self._dao.insert_report(report)
        if report.pic is not None and len(report.pic) != 0:
            img = report.pic.decode('base64')
            with open('static/{}.jpg'.format(id_), 'wb') as imgfile:
                imgfile.write(img)
        
    
    def fetch_all(self):
        reports = self._dao.fetch_all_reports()
        return { "results" : [ Report.toJson(report) for report in reports] }
    
    def get_report(self, Id):
        rep = self._dao.get(Id)
        if rep is not None:
            return Report.toJson(rep)
        else:
            return None

    def get_reports_by_location(self, location):
        reports = self._dao.fetch_report_with_address(location)
        return { "results" : [ Report.toJson(report) for report in reports] }

    def update_status(self, Id, new_status):
        self._dao.update_field(Id, "status", new_status)
Beispiel #39
0
def get_surgeons_by_title():
    try:
        dao = DAO()
        title = request.form.get("title", None)

        if title:
            surgeons_editable = dao.by_title(title)
            surgeons_editable_deleted = dao.by_title(title, deleted=True)

            return_data = {
                "surgeons_editable": surgeons_editable,
                "surgeons_editable_deleted": surgeons_editable_deleted
            }

            return jsonify(return_data)

        else:
            return "No title found"

    except Exception as e:
        print(str(e))
        return jsonify({})
Beispiel #40
0
def all_systems_go():
    dao = DAO(session())
    instance = ClockServer(dao)

    server = SimpleXMLRPCServer(("localhost", 8080),
                                requestHandler=RequestHandler,
                                logRequests=False,
                                allow_none=True)
    server.register_introspection_functions()
    server.register_instance(instance)

    mainlog.info("The server is running")
    server.serve_forever()
Beispiel #41
0
def search():
    logger = Logger()
    dao = DAO()

    try:
        search_value = str(request.form["search_value"]).strip()
        all_results = []

        if len(search_value.strip()) == 5 and search_value.isdigit():
            # logger.log("Searching %s" % search_value)
            by_zip = dao.by_zip(search_value)
            # logger.log(str(by_zip))
            all_results.extend(by_zip)

        else:
            by_name = dao.by_name(search_value)
            all_results.extend(by_name)

        return jsonify(all_results)

    except Exception as e:
        return logger.filename + " " + str(e)
	def test_remove_entry(self):

		testDataContent = [
		  '648:abcdefghi',
		  '517:QjhWkizN5t',
		  '323:dwcIY99gTN1',
		  '653:UlfY2UvMfeuX'
		]
		data1 = DAO(testDataContent)
		assert data1.find('abcdefghi')

		data1.remove_entry('abcdefghi')
		assert data1.find('abcdefghi') is None

		with pytest.raises(Exception):
			data1.remove_entry('abcdefghi')
Beispiel #43
0
	def __init__(self):
		self.top = Tkinter.Tk()
		self.Lb1 = Listbox(self.top)
		self.L1 = Label(self.top, text="Digite o username:"******"Digite o email:")
		self.E2 = Entry(self.top, bd = 5)
		self.B = Tkinter.Button(self.top, text="Adicionar", command=self.eventoAdicionar)
		self.Br = Tkinter.Button(self.top, text="Remover", command=self.eventoRemover)
		self.L1.pack()
		self.E1.pack()
		self.L2.pack()
		self.E2.pack()
		self.dao = DAO()

		vet = self.dao.listar()
		for row in vet:
			self.Lb1.insert(row.username, row.email)
		self.Lb1.pack()

		self.B.pack()
		self.Br.pack()
		self.top.mainloop()
Beispiel #44
0
#!/usr/bin/python

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("hash", help="""The hash of the file to investigate""")
args = parser.parse_args()

import config
from dao import DAO

dao = DAO()

data = dao.getInfoByHash(args.hash)

if data == None:
    print "Don't know about %s" % args.hash
else:
    print data["hash"], "is", data["mimetype"]
    print "found %d times" % len(data["path"])
    n = 0
    powner = None
    ppath = None
    for (date, owner, path) in data["path"]:
	if powner != owner:
	    powner = owner
	    ppath = None
	if path is not None:
	    print "  %s | %10s | %s" % (date, owner, path)
	    n = n+1
	elif path is None and ppath is not None:
Beispiel #45
0
    print('Import pylab+numpy...', end='')
    import pylab
    import numpy as np
    print(' Ok')
except ImportError:
    print(' No pylab')
    pylab = None
    np = None


sDB = 'cristal.db'




if __name__=='__main__':
    if not pylab:
        dao = DAO(sDB)
        dao.displaySensors()
        dao.displayWaves()
        print('for t,v in dao.iterMeasures(sensID, waveID)')
    else:
        dao = DAODrawer(sDB)
        dao.assertPylab()
        dao.displaySensors()
        dao.displayWaves()
        dao.pylabPltWave(3, [], 1300)



Beispiel #46
0
        iface.iTempEau   = wire.dSensors[unhexlify(b'289abbab05000057')].GetTemperatureRaw()
        iface.iTempAirDS = wire.dSensors[unhexlify(b'28cde9f505000027')].GetTemperatureRaw()
        # Temperatures from the MLX90614
        try:
            iface.iTempAirML = bus.read_word_data(0x5A, 0x06)
            iface.iTempObj   = bus.read_word_data(0x5A, 0x07)
        except IOError:
            print('IO Err on I2C bus, but it\'s okay')
        # Cmd is not elaborated here yet (install Adafruit_BBIO for Py3 first)
        time.sleep(0.01)
    print('Measures stopped')



if __name__=='__main__':
    dao = DAO(sDB)
    # One time inits
    if True:
        # The serials are hexlified versions, to be more readable.
        dao.newSensor(b'DS18B20P', b'28cde9f505000027', exprRawToCelsiusDS)
        dao.newSensor(b'DS18B20P', b'289abbab05000057', exprRawToCelsiusDS) # Waterproof
        dao.newSensor(b'MLX90614', b'Ambient', exprRawToCelsiusMLX)
        dao.newSensor(b'MLX90614', b'Object', exprRawToCelsiusMLX)
        dao.newSensor(b'CommandeBouilleur')

    iface = Iface()
    bEnd = Value('b', False)
    Thread(target=workerHWIFace, args=(iface,bEnd)).start()

    if True:
        dao.newWave(sComment='Cristaux, chauffe un peu pas longtemps')
Beispiel #47
0
class PDQHandler(AbstractHandler):

    REQ_MP, RES_MP = PDQ_REQ_MP, PDQ_RES_MP
    PDQ_FIELD_NAMES = {
        '@PID.3.1': "IDENTIFIER",
        '@PID.5.1.1': 'SURNAME',
        '@PID.5.2': 'NAME',
        '@PID.7.1': 'DOB'
    }

    def __init__(self, message):
        self.dao = DAO()
        msg = parse_message(message, message_profile=self.REQ_MP)
        super(PDQHandler, self).__init__(msg)

    def _create_res(self, ack_code, patients):
        res = Message('RSP_K21', reference=self.RES_MP)
        r, q = res.msh, self.incoming_message.msh
        r.msh_5, r.msh_6 = q.msh_3, q.msh_4
        res.msh.msh_5 = self.incoming_message.msh.msh_3
        res.msh.msh_6 = self.incoming_message.msh.msh_4
        r.msh_7.ts_1 = DTM(datetime.datetime.now())
        r.msh_9 = 'RSP^K22^RSP_K21'
        r.msh_10 = uuid.uuid4().hex

        r, q = res.msa, self.incoming_message.msh
        r.msa_1 = ack_code
        r.msa_2 = q.msh_10.msh_10_1

        r, q = res.qak, self.incoming_message.qpd
        r.qak_1 = q.qpd_2
        r.qak_2 = ('OK'
                   if len(patients) > 0 else 'NF')
        r.qak_4 = str(len(patients))

        res.qpd = self.incoming_message.qpd
        g = res.add_group('rsp_k21_query_response')
        for i, p in enumerate(patients):
            s = g.add_segment('PID')
            s.pid_1 = str(i)
            s.pid_3.cx_1 = p["IDENTIFIER"]
            s.pid_3.cx_4 = "master"
            s.pid_5 = "%s^%s" % (p["SURNAME"], p["NAME"])
            s.pid_7.ts_1 = p["DATETIME_OF_BIRTH"]
            s.pid_8 = p["ADMINISTRATIVE_SEX"]
            s.pid_11.xad_3 = p["CITY"]
            s.pid_13.xtn_1 = p["PHONE"]
            s.pid_13.xtn_4 = p["EMAIL"]
            s.pid_18.cx_1 = p["ACCOUNT_NUMBER"]
            s.pid_23 = p["BIRTH_PLACE"]
        return res

    def _create_err(self, code, desc):
        res = self._create_res('AR', 'AR', [])
        res.err.err_1, res.err.err_2 = code, desc
        return res

    def reply(self):
        logger.info("Received message:\n{}".format(self.incoming_message.to_er7().replace("\r", "\n")))

        params = dict((self.PDQ_FIELD_NAMES[q.qip_1.value], q.qip_2.value)
                      for q in self.incoming_message.qpd.qpd_3
                      if q.qip_1.value in self.PDQ_FIELD_NAMES)

        logger.info("Extracted parameters: {}".format(params))

        if '' in params.values() or ('DOB' in params and not check_date(params.get('DOB'))):
            return self._create_err("100", "Invalid params")
        else:
            p = self.dao.get_data(params)

        res = self._create_res('AA', p)
        res = res.to_mllp()
        logger.info("Sending result: {}".format(res.replace("\r", "\n")))
        return res
def removeScenario():
	id_scenario = int(request.args['id_scenario'])
	dao = DAO()
	dao.removeScenario(id_scenario)
	return json.dumps({'success': 'true'})
def changeScenarioStatut(id_scenario=None):
    dao = DAO()
    dao.setStatusToScenario(int(id_scenario))
    return json.dumps({'success': 'true'})
Beispiel #50
0
from dao import DAO
from domain import Equity
import json

equity_ticker = 'JT_TEST'
equity_exchange = 'TJE'
equity_name = 'James Test Equity'
equity_industry = 'Industrial James'
equity_dow = True
equity_sp = True

e = Equity(None, equity_ticker, equity_name, equity_exchange, equity_industry, equity_dow, equity_sp)
dao = DAO()

print('Creating a test equity')
e = dao.create_equity(e)
print('Created the following equity: ' + json.dumps(e.__dict__))
print('Passed\r\n')

print('Retrieving all equities')
equities = dao.get_all_equities()
found_test_equity = False
for j in equities:
    print(json.dumps(j.__dict__))
    if j.equity_id == e.equity_id:
        found_test_equity = True
print('Done retrieving equities - found ' + str(len(equities)) + ' equities')
if found_test_equity:
    print('Passed')
else:
    print('Failed!!!!')
Beispiel #51
0
 def __init__(self, message):
     self.dao = DAO()
     msg = parse_message(message, message_profile=self.REQ_MP)
     super(PDQHandler, self).__init__(msg)
Beispiel #52
0
Datei: mydb.py Projekt: Miaou/BBB
            log.write(time.ctime()+" : "+str(e) + "\n")
            mesure_reussie.value = False
            diode.value = False
        finally:
            time.sleep(1)
    
    print('End of DS measurement')
    log.write(time.ctime() + " : End of DS measurement")
    log.write("\nTotal time : " + str(time.time()-temps))
    log.close()


iface = Bulk()
stop = Value('b', False)
db = 'essai.db'
dao = DAO(db)
mesure_reussie = Value('b', False)
if False:
    #time.sleep(15)
    dao.newSensor(b'SHT21', b'RH')
    dao.newSensor(b'SHT21', b'Temperature')
    dao.newWave(sComment='Premier essai avec la nouvelle BBB')
    dao.commentSensor(1, 'Derriere le PC', 'Air(%RH)')
    dao.commentSensor(2, 'Derriere le PC', 'Air(.C)')
    Thread(target=workerSHT, args=(iface, stop)).start()

    try:
        while True:
            dao.newMeasure(1, iface.shtRH)
            dao.newMeasure(2, iface.shtTemp)
            time.sleep(5)
Beispiel #53
0
#!/usr/bin/python
import os
import shutil
import mimetypes

import config
from dao import DAO
from file import File
#
# main
#
dao = DAO()

for (status, directory) in (('OK', config.OKDirectory),
			    ('X', config.XDirectory),
			    ('COPYRIGHT', config.COPYRIGHTDirectory)):
    for root, dirs, files in os.walk(directory):
	for name in files:
	    file = File(root,name)
	    dao.mark(file.hash, status)
	    print "%-10s : %s" % (status, file.fullName)
	    os.unlink(file.fullName)
	
Beispiel #54
0
		    type=int,
		    default=1000)

args = parser.parse_args()

import os
import shutil
import mimetypes

import config
from dao import DAO
from file import File
#
# main
#
dao = DAO()

for dir in (config.ExfilterDirectory, config.OKDirectory, 
		config.COPYRIGHTDirectory, config.XDirectory):
	if not os.path.isdir(dir):
		print "W: Creating", dir
		os.mkdir(dir)

prevdst = ""
count = 0
for (hash, mimetype, path,file) in dao.exfilter(mimetype=args.mime,
						filename=args.name):
    ext = mimetypes.guess_extension(mimetype)
    if ext is None:
	ext = ".unknown"
    src = os.path.join(path,file)
Beispiel #55
0
 def __init__(self):
     self._dao = DAO()
Beispiel #56
0
 def setUp(self):
     self.dao = DAO()
     self.dao.connect()
Beispiel #57
0
 def __init__(self, repo_path):
     self.dao = DAO(repo_path)
Beispiel #58
0
class WriterWiki(object):
    
    def __init__(self, repo_path):
        self.dao = DAO(repo_path)
    
    def get_page(self, name):
        page = self.dao.get_page(name)
        if page is None:
            page = Page(name, StringIO.StringIO(""))
        return page
        
    def update_page(self, page):
        self.dao.store_page_update(page)
        
    def snapshot(self):
        self.dao.add_all_commit()
        
    def get_template_names(self):
        return self.dao.get_template_names()
        
    def get_template(self, name):
        return self.dao.get_template(name)
        
    def get_recently_modified_pages(self):
        return self.dao.get_recently_modified_pages()
        
    def get_all_pages(self):
        return self.dao.get_all_pages()
    
    # manage the working set
    ###################################################################
    
    def get_workingset(self):
        return self.dao.get_workingset()
        
    def add_to_workingset(self, page):
        if not self.dao.page_exists(page):
            return
        ws = self.dao.get_workingset()
        if page not in ws:
            ws.append(page)
        self.dao.update_workingset(ws)
        
    def remove_from_workingset(self, page):
        ws = self.dao.get_workingset()
        if page in ws:
            ws.remove(page)
        self.dao.update_workingset(ws)
        
    # manage the tags
    ###################################################################
    
    def get_tags(self, page):
        if not self.dao.page_exists(page):
            return {}
        tags = self.dao.get_tags(page)
        if tags is None:
            return {}
        return tags
        
    def set_tags(self, page, tags):
        if not self.dao.page_exists(page):
            return
        self.dao.set_tags(page, tags)
        
    def get_tag_cloud(self):
        return self.dao.get_all_tags()
        
    def get_tagged_pages(self, tag):
        return self.dao.get_tagged_pages(tag)
        
    # manage the works
    ###################################################################
    
    def get_work_names(self):
        return self.dao.get_work_names()
        
    def get_work_pages(self, work_name):
        work = self.dao.get_work(work_name)
        return work.get("pages", [])
        
    def add_to_work(self, work, page):
        w = self.dao.get_work(work)
        if not w.has_key("pages"):
            w["pages"] = []
        if page not in w["pages"]:
            w["pages"].append(page)
        self.dao.save_work(work, w)
        
    def get_works_for_page(self, page):
        page_works = []
        works = self.get_work_names()
        for work_name in works:
            work = self.dao.get_work(work_name)
            if page in work.get("pages", []):
                page_works.append(work_name)
        return page_works
        
    def add_work(self, name, desc):
        work = self.dao.get_work(name)
        if work is None:
            work = {}
        work["name"] = name
        work["description"] = desc
        self.dao.save_work(name, work)
Beispiel #59
0
#!/usr/bin/env python
from dao import DAO

# test driver
if __name__ == "__main__" :
	myDAO = DAO("localhost", "root", "macroot", "dddb")
	lat = -2.0
	long = -2.5
	print "updating carrier1 -> ({},{})".format(lat,long)
	myDAO.updateCarrierLoc( "carrier1", lat, long)

	myDAO = DAO("localhost", "root", "macroot", "dddb")
	print "updating carrier2 -> offline"
	myDAO.updateCarrierOnOff( "carrier2", 0)

	myDAO = DAO("localhost", "root", "macroot", "dddb")
	print "carrier1 accepting delivery 1"
	myDAO.updateCarrierAccept( "carrier1", "1" )

	myDAO = DAO("localhost", "root", "macroot", "dddb")
	print "completing carrier2"
	myDAO.updateCarrierComplete( "carrier2", 1 )

	print "getAccepted('carrier1'): {}".format( myDAO.getAccepted('carrier1') )

	print "Get all free carriers:"
	frees = myDAO.getAvailableCarriers()
	for carrier in frees:
		print carrier

	newDelivery = myDAO.createDelivery( 1.2, 1.2,
Beispiel #60
0
#!/usr/bin/python
import os
import MySQLdb

import config
from dao import DAO
from file import File
	
#
# Process one file
def processFile(dao, f):
    dao.insertFile(f)
    print f.hash, ":", name, f.size, "(%s)" % f.mimetype
    

#
# main
#
# Walk throught directories
dao = DAO()
for root, dirs, files in os.walk(config.BaseDirectory):
    for name in files:
	try:
	    file = File(root, name)
	    processFile(dao, file)
	except OSError as (errno, strerror):
	    print "E : OSError", errno, "while processing", name, "(",strerror,")"
	except IOError as (errno, strerror):
	    print "E : IOError", errno, "while processing", name, "(",strerror,")"
dao.done()