def get_data_response(self, institution_id = None, request_url = ''): connect = Connect(institution_id = institution_id, request_url = request_url, config = self.config) opener = urllib2.build_opener(MyHTTPSHandler) opener.addheaders = [('accept', 'application/atom+json'),('Authorization', connect.getAuthorization_header())] #opener.addheaders = [('accept', 'application/xml'),('Authorization', connect.getAuthorization_header())] response = opener.open(request_url).read() return response
def connect(self, *args): """ Called via our connect thread... Attempt to create a new connection with our Connect class and store the value to our self.connection instance variable """ # With the potential dropped internet connections, sessions ending and more, # which have caused errors, it's easier and safer if we attempt to create a # new instance of Connect which provides a clean session. Future improvements # could be made to rectify this action to help memory/performance. self.connection = Connect() self.title = GumpyTitles.CONNECTING try: self.connection.connect() rumps.notification(GumpyTitles.CONNECTION_SUCCESS, '', 'Have a cookie') # This explicitly calls get_tickets method on a rumps.Timer (new thread) interval if self.refresh_interval_timer is None: self.refresh_interval_thread() else: # If this isn't the first time connect is being called, we will update # our ticket results by refreshing our interval thread which calls get_tickets self.refresh_interval_thread(force_refresh=True) except Exception as e: rumps.alert(e) finally: self.title = GumpyTitles.GUMPY
def query_page(request): dbchoice1 = base64.decodestring(request.GET.get('dbchoice1')) page_id = request.GET.get('page_id') sqltext = open('/tmp/1.txt', 'r').read() db_connect = Connect(host=dbchoice1, sqltext1=sqltext) (result_desc, messages, page_counts) = db_connect.connectexec(page_id=int(page_id)) if re.compile(r'v\$').search(sqltext) or re.compile(r'V\$').search( sqltext) or re.compile(r'dba_\$').search(sqltext) or re.compile( r'DBA_\$').search(sqltext): cols = [] rows = [] for row in messages: for col in row: cols.append(str(col).decode('utf-8', 'ignore')) rows.append(cols) messages = rows return render_to_response( 'result.html', { 'dbchoice1': base64.encodestring(dbchoice1), 'messages': messages, 'page_counts': page_counts, 'result_descs': result_desc }) else: return render_to_response( 'result.html', { 'dbchoice1': base64.encodestring(dbchoice1), 'messages': messages, 'page_counts': page_counts, 'result_descs': result_desc })
def __init__(self): self.connection = Connect('ora-scsp.srv.mst.edu', 1521, os.environ['DBEAVER_USERNAME'], os.environ['DBEAVER_PASSWORD'], 'scsp.mst.edu') self.connection.establish_connection()
def start(self): """ Start server """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((self._host, self._port)) sock.listen(1) t = 0 while True: # Connect to wifi if time.time() > t + 30: Connect.check_and_reconnect() t = time.time() print(t) try: self._connect, address = sock.accept() request = self._get_request() if len(request) == 0: self._connect.close() continue if self._on_request_handler: if not self._on_request_handler(request, address): continue route = self.find_route(request) if route: route["handler"](request) else: self.not_found() except Exception as e: self.internal_error(e) finally: self._connect.close()
class BookConditions(Resource): def __init__(self): self.connection = Connect( 'ora-scsp.srv.mst.edu', 1521, os.environ['DBEAVER_USERNAME'], os.environ['DBEAVER_PASSWORD'], 'scsp.mst.edu' ) self.connection.establish_connection() def get(self): order_by = ' ORDER BY BOOK_CONDITION.JACKET_CONDITION ' req = { 'jacket_condition':request.args.get("jacket_condition"), } where_cmds = [] if req['jacket_condition'] != None: where_cmds.append(' BOOK_CONDITION.TITLE = \'{}\' '.format(req['title'])) where_cmds.append(' BOOK_CONDITION.AUTHOR = \'{}\' '.format(req['author'])) where_cmds.append(' BOOK_CONDITION.EDTION = \'{}\' '.format(req['edtion'])) where_cmds.append(' BOOK_CONDITION.JACKET_CONDITION = \'{}\' '.format(req['jacket_condition'])) command = 'SELECT TITLE, AUTHOR, EDITION, JACKET_CONDITION FROM GCWZF4.BOOK_CONDITION {} {} {}'.format('WHERE' if len(where_cmds)>0 else '','AND'.join(where_cmds), order_by) data = self.connection.get_query_data( command ) jacket_conditions = [] return_val = [] return_code = 200 if data != []: for row in data: jacket_conditions.append({ "title":row[0], "author":row[1], "edition":row[2], "jacket_condition":row[3], }) return_val = jacket_conditions else: return_val = 'ERROR' return_code = 500 self.connection.close_connection() return return_val, return_code def post(self, name): pass def put(self, name): pass def delete(self, name): pass
def __init__(self): Config.__init__(self) self.si = Connect().si self.utl = Utils(label='wait') self.queue = Queue() self.content = self.si.RetrieveContent() self.vms = [] self.MAX_DEPTH = 10 self.migration_between_hosts = self.migration_possible(self.esxi_hosts) self.migration_between_datasources = self.migration_possible(self.ds_names)
def run(self): print("Welcome to Bronzer") connect = Connect() connect.startConnect() welcome_msg = connect.retriveMsg() print(welcome_msg) handler = Handler() while (True): cmd = input("Bronzer>> ") if not cmd.strip(): continue if cmd.strip() == "exit": connect.sendCmd(cmd) break else: print(handler.handle(cmd)) # if cmd.strip() == "shell": # os.system("adb shell") # msg = connect.sendCmd(cmd) # print(msg) # handler = Handler() # rtn_msg = handler.handle(cmd) # print(rtn_msg) connect.stopConnect() exit(0)
class Authors(Resource): def __init__(self): self.connection = Connect( 'ora-scsp.srv.mst.edu', 1521, os.environ['DBEAVER_USERNAME'], os.environ['DBEAVER_PASSWORD'], 'scsp.mst.edu' ) self.connection.establish_connection() def get(self): order_by = ' ORDER BY AUTHORS.AUTHOR ' req = { 'author':request.args.get("author"), } where_cmds = [] if req['author'] != None: where_cmds.append(' AUTHORS.AUTHOR = \'{}\' '.format(req['author'])) command = 'SELECT * FROM GCWZF4.AUTHORS {} {} {}'.format('WHERE' if len(where_cmds)>0 else '','AND'.join(where_cmds), order_by) data = self.connection.get_query_data( command ) authors = [] return_val = [] return_code = 200 if data != []: for row in data: authors.append({ "author":row[0], "image_path":row[1]}) return_val = authors else: return_val = 'ERROR' return_code = 500 self.connection.close_connection() return return_val, return_code def post(self, name): pass def put(self, name): pass def delete(self, name): pass
def create_device(self,thing_name): network_id=my_ids.NETWORK_ID network_name= my_ids.NETWORK_NAME device_id=open('device\\'+thing_name+'\\device_id.txt','r') device_id=device_id.read() device_name=thing_name network_data=connect.get_network(network_id,network_name) self.send_data(network_data) device_data=connect.get_device(device_id,device_name,network_id) self.send_data(device_data)
class Grades(Resource): def __init__(self): self.connection = Connect( 'ora-scsp.srv.mst.edu', 1521, os.environ['DBEAVER_USERNAME'], os.environ['DBEAVER_PASSWORD'], 'scsp.mst.edu' ) self.connection.establish_connection() def get(self): order_by = ' ORDER BY GRADE.BOOK_GRADE ' req = { 'grade':request.args.get("grade"), } where_cmds = [] if req['grade'] != None: where_cmds.append(' GRADE.BOOK_GRADE = \'{}\' '.format(req['grade'])) command = 'SELECT * FROM GCWZF4.GRADE {} {} {}'.format('WHERE' if len(where_cmds)>0 else '','AND'.join(where_cmds), order_by) data = self.connection.get_query_data( command ) grades = [] return_val = [] return_code = 200 if data != []: for row in data: grades.append({"grade":row[0]}) return_val = grades else: return_val = 'ERROR' return_code = 500 self.connection.close_connection() return return_val, return_code def post(self, name): pass def put(self, name): pass def delete(self, name): pass
def __init__(self): id = unique_id() self.hex_id = b'{:02x}{:02x}{:02x}{:02x}'.format( id[0], id[1], id[2], id[3]) # Alimentação self.p4 = Pin(4, Pin.OUT) self.p4.value(1) # Buzzer e LED self.p2 = Pin(2, Pin.OUT) # LED self.p5 = Pin(5, Pin.OUT) # BUZZER # Deixa pré-definido para não reenviar, caso se conecte a rede, ativa o reenvio self.reenvio = True # Botão self.alimentacao = Timer(2) self.p15 = Pin(15, Pin.IN, Pin.PULL_DOWN) self.p15.irq(trigger=Pin.IRQ_RISING, handler=self.button) # Acelerômetro self.z = ADC(Pin(32)) self.y = ADC(Pin(35)) self.x = ADC(Pin(34)) # Pino da bateria self.p33 = ADC(Pin(33)) self.p33.width(ADC.WIDTH_10BIT) self.p33.atten(ADC.ATTN_11DB) # Timer da bateria self.bateria_timer = Timer(1) self.bateria_timer.init(period=1800000, mode=Timer.PERIODIC, callback=self.bateria) self.acelerometro() self.t_rede = Timer(-1) self.t_rede.init(period=300000, mode=Timer.PERIODIC, callback=self.reiniciar) self.c = Connect() self.connection = self.c.start() self.client = Client(self.connection) self.t_rede.deinit() self.t_reenvio = Timer(3) self.reenvio = False
class JacketConditions(Resource): def __init__(self): self.connection = Connect('ora-scsp.srv.mst.edu', 1521, os.environ['DBEAVER_USERNAME'], os.environ['DBEAVER_PASSWORD'], 'scsp.mst.edu') self.connection.establish_connection() def get(self): order_by = ' ORDER BY JACKET_CONDITIONS.JACKET_CONDITION ' req = { 'jacket_condtion': request.args.get("jacket_condtion"), } where_cmds = [] if req['jacket_condtion'] != None: where_cmds.append( ' JACKET_CONDITIONS.JACKET_CONDITION = \'{}\' '.format( req['jacket_condtion'])) command = 'SELECT * FROM GCWZF4.JACKET_CONDITIONS {} {} {}'.format( 'WHERE' if len(where_cmds) > 0 else '', 'AND'.join(where_cmds), order_by) data = self.connection.get_query_data(command) jacket_conditions = [] return_val = [] return_code = 200 if data != []: for row in data: jacket_conditions.append({"jacket_conditions": row[0]}) return_val = jacket_conditions else: return_val = 'ERROR' return_code = 500 self.connection.close_connection() return return_val, return_code def post(self, name): pass def put(self, name): pass def delete(self, name): pass
def delete_device(self,item_id): nid=my_ids.NETWORK_ID delete_url='/network/'+nid+'/device/'+item_id func_method=str('DELETE') params={} params['url']=delete_url socket=connect.connect_to_server() message=connect.get_message(func_method,params) c=socket.send(message.encode('utf-8')) data = socket.recv(2000) decoded = json.loads(data.decode('utf-8')) return decoded
def result(request): logger = logging.getLogger('testdj') key = request.POST.get('m1') dbchoice1 = request.POST.get('dbchoice') p = re.compile(r'^select') if key == '': return render_to_response('search.html', {'error': 'NULL'}) if not (p.search(key)): return render_to_response('search.html', {'error': 'notValidSelect'}) if re.compile(r'for update').search(key): return render_to_response('search.html', {'error': 'forUpdate'}) logger.warning('SQL: ' + key + ' DB EXEUTION:' + dbchoice1 + ' USER: '******'REMOTE_ADDR']) db_connect = Connect(host=dbchoice1, sqltext1=key) (result_desc, messages, page_counts) = db_connect.connectexec() p2 = re.compile(r'ORA-') if (p2.search(str(messages))): return render_to_response('search.html', {'dberrormsg': messages}) else: open('/tmp/1.txt', 'w+').write(key) if re.compile(r'v\$').search(key) or re.compile(r'V\$').search( key) or re.compile(r'dba_\$').search(key) or re.compile( r'DBA_\$').search(key): cols = [] rows = [] for row in messages: for col in row: cols.append(str(col).decode('utf-8', 'ignore')) rows.append(cols) messages = rows return render_to_response( 'result.html', { 'dbchoice1': base64.encodestring(dbchoice1), 'messages': messages, 'page_counts': page_counts, 'result_descs': result_desc }) else: return render_to_response( 'result.html', { 'dbchoice1': base64.encodestring(dbchoice1), 'messages': messages, 'page_counts': page_counts, 'result_descs': result_desc })
def __init__(self): self.hotelAttributes = [ "name", "pageLink", "description", "address", "city", "nation", "numberReview", "averageVote", "position", "cleanliness", "service", "qualityPrice" ] self.reviewAttributes = ["reviewer", "text", "vote", "month", "year"] self.typeStatistics = [ "averageVote", "position", "cleanliness", "service", "qualityPrice" ] self.classValutation = ["none", "bad", "average", "good"] self.columns = os.popen('stty size', 'r').read().split()[1] self.connection = Connect() self.graphConnection = GraphConnect()
class ServerFSM: mode = "" def __init__(self): self.state = Wait_for_connect() def recv_data(self): return self.state.recv_data(self) def make_connection(self): print("make_connection") self.connection_one = Connect() self.connection_one.make_connection() def make_connection2(self): print("make_connection2") self.connection_two = Connect() self.connection_two.make_connection() def select_game(self): print("select_game") if not ( self.mode == "ttt" or self.mode == "mol" ): self.mode = self.connection_one.send_data("Choose game (mol - more or less OR ttt - Tic-Tac-Toe) :", True) if not (self.mode == "ttt" or self.mode == "mol"): self.mode = self.connection_one.send_data("Choose game (mol - more or less OR ttt - Tic-Tac-Toe) :", True) if self.mode == "mol": return True else: return False else: return True def start_game(self): print("start game") if self.mode == 'ttt': self.game = MultiplayerGameplay(self.connection_one, self.connection_two) self.game.start() else: self.game = MoLGameplay(self.connection_one) self.connection_two = False self.game.start() def make_disconnect(self): print("make disconnect") if self.connection_two: self.connection_two.close_connection() self.connection_one.close_connection()
class AuthorBooks(Resource): def __init__(self): self.connection = Connect('ora-scsp.srv.mst.edu', 1521, os.environ['DBEAVER_USERNAME'], os.environ['DBEAVER_PASSWORD'], 'scsp.mst.edu') self.connection.establish_connection() def get(self): order_by = ' ORDER BY BOOK_EDITIONS.PUBLISH_YEAR, BOOK_EDITIONS.TITLE ' req = { 'author': request.args.get("author"), } where_cmds = [] if req['author'] != None: where_cmds.append(' BOOK_EDITIONS.AUTHOR = \'{}\' '.format( req['author'])) command = 'SELECT AUTHORS.AUTHOR, AUTHORS.IMAGE_PATH, TITLE, PUBLISH_YEAR FROM GCWZF4.BOOK_EDITIONS JOIN GCWZF4.AUTHORS ON AUTHORS.AUTHOR = BOOK_EDITIONS.AUTHOR {} {} {}'.format( 'WHERE' if len(where_cmds) > 0 else '', 'AND'.join(where_cmds), order_by) print(command) data = self.connection.get_query_data(command) authors = {} return_val = [] return_code = 200 if data != []: authors['author'] = data[0][0] authors['image_path'] = data[0][1] authors['books'] = [] for row in data: authors['books'].append({ "title": row[2], "publish_year": row[3] }) return_val = authors else: return_val = 'ERROR' return_code = 500 self.connection.close_connection() return return_val, return_code
def __init__(self): super().__init__() exitShortcut = QShortcut(QKeySequence('Ctrl+W'), self, qApp.quit) self.connect = Connect() self.all_models = self.connect.session.query(Models).all() self.labelkey_name = QLabel('Name', self) self.labelkey_parts = QLabel('Parts', self) self.labelkey_current_quantity = QLabel('Current Quantity', self) self.labelval_name = QLabel('Name', self) self.labelval_parts = QLabel('Parts', self) self.labelval_current_quantity = QLabel('Current Quantity', self) self.showInfo('M1') self.list = QListView(self) self.list_model = QStandardItemModel(self.list) self.createList() print('Current index of view: ', self.list.currentIndex()) self.hboxlayout = QHBoxLayout() self.label_grid = QGridLayout() self.buildLayout() self.show()
def __init__(self): super().__init__() exitShortcut = QShortcut(QKeySequence('Ctrl+W'), self, qApp.quit) self.connect = Connect() self.all_models = self.connect.session.query(Models).all() self.table = self.table = QTableWidget(5, 3, self) self.setTableHeaders() self.organiseTable() self.populate('M1') self.createconnections() self.table.move(100, 100) self.createList() self.list.currentItemChanged.connect(self.listClicked) # print('Current Item :', self.list.currentItem()) self.positionWidgets() self.mainhbox = QHBoxLayout() self.mainhbox.addWidget(self.list) self.mainhbox.addWidget(self.table) self.setLayout(self.mainhbox) self.setGeometry(0, 0, 640, 440) self.show()
def CreateSuggestionsTable(suggestions_dir): db = Connect() suggestions = db.suggestions # By default, the suggestions for a particular host will be an empty list of # pathogens and an empty list of controls. all_suggestions = defaultdict(lambda: defaultdict(lambda: { 'pathogens': [], 'controls': [] })) # Each suggestion file is read one by one. for host_suggestions_file in os.listdir(suggestions_dir): match = re.match(r'(.*)_(\w+)_(controls|pathogens).txt', host_suggestions_file) if not match: logging.info('Skipping %s' % host_suggestions_file) continue else: logging.info('Working on %s' % host_suggestions_file) host = match.group(1) subtype = match.group(2) is_p = 1 if match.group(3) == 'pathogens' else 0 # Stores all organism ids that were matched. matched = [] # Reads the organism names from the hits table and creates a mapping from # host cannonical name to host id. hits = db['%s_hits' % host] organisms = {} for result in hits.find({}, {'organism': 1}): organisms[_NormalizedName(result['organism'])] = str(result['_id']) # For each line in the suggestions file, checks if the cononical organism # name is a prefix of an organism in the hits collection. full_path = os.path.join(suggestions_dir, host_suggestions_file) with open(os.path.join(suggestions_dir, host_suggestions_file)) as f: for suggestion in f: target_name = _NormalizedName(suggestion) for organism_name, organism_id in organisms.iteritems(): if organism_name.startswith(target_name): matched.append(organism_id) # Adds the list of pathogen or control suggestions to the host. all_suggestions[host][subtype][ 'pathogens' if is_p else 'controls'] = matched # Adds the suggestions per organism to the mongo collection. for host, val in all_suggestions.iteritems(): try: suggestions.insert({'host': host, 'suggestions': val}) except DuplicateKeyError: pass # There should only be one entry per host. suggestions.ensure_index([('host', pymongo.ASCENDING)], unique=True, dropDups=True)
class Years(Resource): def __init__(self): self.connection = Connect('ora-scsp.srv.mst.edu', 1521, os.environ['DBEAVER_USERNAME'], os.environ['DBEAVER_PASSWORD'], 'scsp.mst.edu') self.connection.establish_connection() def get(self): order_by = ' ORDER BY BOOK_EDITIONS.PUBLISH_YEAR, BOOK_EDITIONS.TITLE ' req = { 'author': request.args.get("author"), } where_cmds = [] if req['author'] != None: where_cmds.append(' BOOK_EDITIONS.AUTHOR = \'{}\' '.format( req['author'])) command = 'SELECT BOOK_EDITIONS.PUBLISH_YEAR, BOOK_EDITIONS.TITLE FROM GCWZF4.BOOK_EDITIONS {}'.format( order_by) data = self.connection.get_query_data(command) years = {} years['publish_year'] = {} return_val = [] return_code = 200 if data != []: for row in data: print(row[0]) if row[0] not in years['publish_year']: years['publish_year'][row[0]] = [row[1]] else: years['publish_year'][row[0]].append(row[1]) return_val = years else: return_val = 'ERROR' return_code = 500 self.connection.close_connection() return return_val, return_code
def get_state(self,device_name,datas,value_id,network_id,device_id,val_name): url_state='/network/'+network_id+'/device/'+device_id+'/value/'+value_id+'/state' state=datas.get('state') types=datas.get('type') report_id=open('device\\'+device_name+'\\value\\'+val_name+'\\state\\Report\\state_id.txt','r') report_id=report_id.read() control_id=open('device\\'+device_name+'\\value\\'+val_name+'\\state\\Control\\state_id.txt','r') control_id=control_id.read() data=state results=connect.get_state(report_id,data,network_id,device_id,value_id,'Report') self.send_data(results) results=connect.get_state(control_id,data,network_id,device_id,value_id,'Control') self.send_data(results)
def connect(): win = Connect() win.setWindowTitle('FASWU') r = win.showModal() if r: global ip, port ip = win.ip.text() port = win.port.text() print(ip) print(port) con = win.con if con == 1: print('server clicked...') server(ip, port) elif con == 2: print('client clicked...') client(ip, port)
def __init__(self, training=False, tensorboard=False, graph=False, lr=1e-5, gamma=0.95, batch=5000, sample=100, epis=250): # HYPER PARAMETERS self.LEARNING_RATE = lr self.GAMMA = gamma self.EXPLORE_START = 0.95 self.EXPLORE_STOP = 0.01 self.DECAY_RATE = 1e-4 self.BATCH_SIZE = batch self.SAMPLE_SIZE = sample self.N_EPISODES = epis self.NAME = f"lr({self.LEARNING_RATE})_gamma({self.GAMMA})_batch({self.BATCH_SIZE})_sample({self.SAMPLE_SIZE})" print(self.NAME) self.memory = deque(maxlen=100000) self.last_dist = 0 self.conn = Connect() self.create_dqn() print("Model successfully set up!") if training: if tensorboard: self.tensorboard() reward, loss = self.train(tensorboard) if graph: self.graph(reward, loss) else: self.run() self.conn.close()
def update_loop(url, interval=0, port=80): """ Download image, update display, sleep, loop. Gives up on any error :param url: :param interval: :param port: :return: """ e = EPD() e.enable() sep = url.find('/') host = url[:sep] path = url[sep:] del sep while True: print("Mem free: %d" % gc.mem_free()) c = Connect(host, port, debug=True) content = c.get_quick(path) print("Uploading...", end='') e.upload_whole_image(content) print("done.") e.display_update() del content del c if interval > 0: to_sleep = interval print("Sleeping for %ds" % interval, end='') time.sleep(to_sleep) print('.') else: input("Press enter to update (Ctrl-C to stop).") gc.collect()
def get(team): a = Connect() a.connect() page = 1 with open('twitter_scrape_file.txt', 'a') as file: while True: re = requests.get( 'https://sportspyder.com/teams/{}/tweeter_types/3/tweets?page={}' .format(team, page)) bs = BeautifulSoup(re.content, 'html.parser') tweets = bs.find_all('div', attrs={'class': 'twitter_content'}) if len(tweets) == 0: return for i in tweets: t = Tweet(team, i.find('span', attrs={ 'class': 'username' }).text, i.find('span', attrs={ 'class': 'time' }).text, i.find('div', attrs={ 'class': 'text' }).text) file.write(str(t.time)) file.write('\n') a.insert(t.insert()) page += 1 print(page)
def main(): canv = Canvas("static/pdf/report.pdf", pagesize=landscape(letter)) styles = getSampleStyleSheet() style = styles["BodyText"] header = Paragraph( "<bold><font size=18>Prima Nota Proloco San Piero</font></bold>", style) riga = Connect.primanota() data = [[ 'DATA', 'DESCRIZIONE', 'CASSA USCITE', 'CASSA ENTRATE', 'BANCA USCITE', 'BANCA ENTRATE' ]] # data.append(['DATA', 'DESCRIZIONE', 'CASSA USCITE', 'CASSA ENTRATE', 'BANCA USCITE', 'BANCA ENTRATE']) for rigas in riga: data.append([ rigas['data'], rigas['descrizione'], rigas['cassa_uscite'], rigas['cassa_entrate'], rigas['banca_uscite'], rigas['banca_entrate'] ]) t = Table(data) t.setStyle( TableStyle([("BOX", (0, 0), (-1, -1), 0.25, colors.black), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black)])) data_len = len(data) for each in range(data_len): if each % 2 == 0: bg_color = colors.lightgrey else: bg_color = colors.whitesmoke t.setStyle( TableStyle([('BACKGROUND', (0, each), (-1, each), bg_color)])) aW = 640 aH = 560 w, h = header.wrap(aW, aH) header.drawOn(canv, 72, aH) aH = aH - h w, h = t.wrap(aW, aH) t.drawOn(canv, 72, aH - h) canv.save() file = "static/pdf/report.pdf" print(file) return file
def request_state(self, method, url, socket): params = {} params['url'] = url message = connect.get_message(method, params) socket.send(message.encode('utf-8')) data = socket.recv(2000) time.sleep(1) data = json.loads(data) time.sleep(1) results = data.get('result') results = ast.literal_eval(results) time.sleep(1) state = results.get('data') return state
def String_values(self, vid, vname, vpermission, vtype, nid, deviceid): string = {} string['max'] = 100 value = {} value[':id'] = vid value[':type'] = 'urn:seluxit:xml:bastard:value-1.1' value['name'] = vname value['permission'] = vpermission value['type'] = vtype value['string'] = string results = connect.get_value(value, nid, deviceid) self.send_value(results)
def Decimal_values(self, vid, vname, vpermission, vtype, nid, deviceid): number = {} number['min'] = 0 number['max'] = 1000000000000 #in openhab its java big decimal number['step'] = 0.1 value = {} value[':id'] = vid value[':type'] = 'urn:seluxit:xml:bastard:value-1.1' value['name'] = vname value['permission'] = vpermission value['type'] = vtype value['number'] = number results = connect.get_value(value, nid, deviceid) self.send_value(results)
def main(): params = [ "&", "2", "-4508.7", "-4508.7", "400", "015", "165", "2", "1", "1", "500", "0" ] test = Connect() test.importParam(params) mode_num = input("Enter 1 for OCP, 2 for ASV: ") if (mode_num == '1'): test.readOCP() print(test.ocpData) print(test.ocp_average) if (mode_num == '2'): test.readData() plt.plot(test.xData, test.yData, 'r-') plt.title("Potential: {}, Scan Rate: {}, Gain: {}".format( params[3], params[4], params[5])) plt.show()
import pprint import datetime from connect import Connect from writer import Writer from controller import Controller from model import Model print("================================================================================") print("================================================================================") host = raw_input("host: ") username = raw_input("username: "******"password: "******"") db_connect = db_access.mysql() default_cursor = db_connect.cursor() #fetch databases default_cursor.execute("SHOW DATABASES") database_list = default_cursor.fetchall() print("================================================================================") print("||Result: {0} db found! ".format(len(database_list))) print("================================================================================") counter = 0 for db in database_list: print("|| {0} - db: {1}".format(counter, db[0])) counter += 1 print("================================================================================") selected_db = input("Please, select the number of the db that you want to process: ") print("================================================================================") selected_db_name = database_list[selected_db][0] #user selected database name print("Selected database: {0}".format(selected_db_name)) user_db_access = Connect(host, username, password, selected_db_name)
# # tables.py # if __name__ == '__main__': from connect import Connect # automatically sets default schema handler = Connect() ###### #### employee ###### new_table = "EMPLOYEE" # drop if handler.table_exists(new_table): query = "DROP TABLE %s" % new_table handler.run_query(query) # create query = """ CREATE TABLE PROFILE.%s ( firstname VARCHAR(30), lastname VARCHAR(30), middlename VARCHAR(30), birthdate VARCHAR(12), phone VARCHAR(30), gender CHAR(1), email VARCHAR(50) UNIQUE NOT NULL,
def run(self): woken = self.wifi_pin() self.epd.enable() if not self.check_battery_level(): return False try: self.epd.get_sensor_data() except ValueError: self.log("Can't communicate with display, flashing light and giving up") heartbeat(True) sleep_ms(15000) return True if self.rtc.alarm_left() > 0: self.log("Woken up but the timer is still running, refreshing screen only") self.epd.display_update() self.feed_wdt() return True try: self.cfg = Config.load(sd=self.sd) self.log("Loaded config") except (OSError, ValueError) as e: self.log("Failed to load config: " + str(e)) self.display_no_config() try: self.connect_wifi() except: pass # everything while True: sleep_ms(10) self.feed_wdt() self.feed_wdt() self.connect_wifi() content = b'' try: self.log("Connecting to server %s:%d" % (self.cfg.host, self.cfg.port)) c = Connect(self.cfg.host, self.cfg.port, debug=self.debug) self.feed_wdt() cause = Display.reset_cause() if woken: cause = "user" self.log("Reset cause: " + cause) if len(self.cfg.upload_path) > 0: temp = self.epd.get_sensor_data() # we read this already c.post(self.cfg.upload_path, battery=self.battery.value(), reset=cause, screen=temp) self.log("Fetching metadata from " + self.cfg.metadata_path) metadata = c.get_quick(self.cfg.metadata_path, max_length=1024, path_type='json') # This will set the time to GMT, not localtime self.set_alarm(c.last_fetch_time, metadata) self.feed_wdt() del metadata del self.battery self.log("Fetching image from " + self.cfg.image_path) self.epd.image_erase_frame_buffer() self.feed_wdt() length, socket = c.get_object(self.cfg.image_path) if length != 15016: raise ValueError("Wrong data size for image: %d" % length) self.feed_wdt() except (RuntimeError, ValueError, OSError) as e: self.log("Failed to get remote info: " + str(e)) self.display_cannot_connect() self.rtc.alarm(time=3600000) return True sleep_ms(1000) # How do we make the write to display more reliable? self.feed_wdt() self.log("Uploading to display") self.display_file_image(socket) c.get_object_done() # close off socket if self.cfg.src == "sd": # If we've got a working config from SD instead of flash self.log("Transferring working config") Config.transfer() self.log("SUCCESS") self.log("Finished. Mem free: %d" % gc.mem_free()) return True
if val.find("'") >= 0: val = val.replace("'", '"') return str(val) ################################################# # MAIN ################################################# if __name__ == '__main__': from connect import Connect # automatically sets default schema handler = Connect() # dump data from excel sheet print "Dumping data from excel into DB..." datasource = os.getcwd() + '/xl/Profile_data_Advanced.xlsx' book = xlrd.open_workbook(datasource) sheet = book.sheet_by_index(0) col_names = sheet.row_values(0) col_names = [str(x) for x in col_names] col_types = [type(x) for x in sheet.row_values(1)] # col length is the length of the longest entry in the col col_len = [] for i in range(sheet.ncols): col = sheet.col_values(i)
else: val = int(val) return val ################################################# # MAIN ################################################# if __name__ == '__main__': from connect import Connect # automatically sets default schema handler = Connect() # drop table handler.run_query("DROP TABLE PROFILE.BIGTABLE_EMPLOYEE") # create table handler.run_query( """ CREATE TABLE BIGTABLE_EMPLOYEE ( firstname VARCHAR(30), lastname VARCHAR(30), email VARCHAR(50), id BIGINT, agency_code CHAR(5), traveler_profile BIGINT, loyalty_type SMALLINT,