def post(self, tokenLogin, pacienteId): recuperaUsuarioAutorizado(tokenLogin) args = request.json segunda = None terca = None quarta = None quinta = None sexta = None sabado = None domingo = None periodoDias = None agendamento = None if args['tipo'] == 'periodo': periodoDias = args['periodoDias'] agendamento = ModeloAgendamento.get(ModeloAgendamento.periodoDias==periodoDias) else: segunda = args['segunda'] terca = args['terca'] quarta = args['quarta'] quinta = args['quinta'] sexta = args['sexta'] sabado = args['sabado'] domingo = args['domingo'] log.d("args " + str(segunda) + str(terca) + str(quarta)) try: agendamento = ModeloAgendamento.get((ModeloAgendamento.segunda==segunda) & (ModeloAgendamento.terca==terca) & (ModeloAgendamento.quarta==quarta) & (ModeloAgendamento.quinta==quinta) & (ModeloAgendamento.sexta==sexta) & (ModeloAgendamento.sabado==sabado) & (ModeloAgendamento.domingo==domingo)) except DoesNotExist, e: agendamento = None
def start_hook(self, dbg): # Only hook function in HOOK_FUNCTION_LIST. for f in self.func_list: if f.func_name not in config.HOOK_FUNCTION_LIST: continue h = HookPoint(f) if h.hook(dbg): self.hook_list.append(h) log.d("%d functions, %d hook success." % (len(self.func_list), len(self.hook_list)) )
def get_all_sink_inputs(cls, audio_switcher=None): arguments = ['pactl', 'list', 'short', 'sink-inputs'] return_code, stdout, stderr = utlis.run(arguments) if audio_switcher is not None: if audio_switcher.last_pactl_sink_inputs is None: log.d('\'{}\':\n{}'.format(" ".join(arguments), stdout)) audio_switcher.last_pactl_sink_inputs = stdout sink_inputs_lines = stdout.split('\n')[:-1] sink_inputs = [cls(line) for line in sink_inputs_lines] return sink_inputs
def __init__(self, row=None, json_dict=None): if row is not None: self.name, self.addr, self.last_heartbeat_ts, self.state = row elif json_dict is not None: self.name = json_dict.get('name', '') self.addr = json_dict.get('addr', '') self.last_heartbeat_ts = json_dict.get('last_heartbeat_ts', '') self.state = json_dict.get('state', '') if not self.name and not self.addr and not self.state: raise AttributeError('Badly formed Node object: %s' % json_dict) else: raise RuntimeError('Either row or json should be specified.') log.d('Initialised Node object: %s', self)
def main(): actions = { SteamvrUtils.Action.ON: ['on', '1'], SteamvrUtils.Action.OFF: ['off', '0'], SteamvrUtils.Action.DAEMON: ['daemon', 'd'], SteamvrUtils.Action.CONFIG_HELP: ['config-help', 'c'] } parser = argparse.ArgumentParser() parser.add_argument('action', choices=[ keyword for _, keywords in actions.items() for keyword in keywords ], help='action to perform on the Base Stations') parser.add_argument('--dry-run', help='Do not modify anything (bluetooth connections are still made, but never used to write).', action='store_true') parser.add_argument('--config', default=None, help='Path to a config file.') args = parser.parse_args() config = Config(config_path=args.config, dry_run_overwrite=args.dry_run) log.initialise(config) # noinspection PyBroadException try: selected_action = None for action in SteamvrUtils.Action: if args.action in actions[action]: selected_action = action if selected_action == SteamvrUtils.Action.CONFIG_HELP: config_helper = ConfigHelper(config) config_helper.print_help() return log.d('dry_run: {}'.format(config.dry_run())) steamvr_utils = SteamvrUtils( config=config ) steamvr_utils.action(selected_action) except Exception: log.e('', exc_info=True) exit(1)
def _choose(self, p1, p2, p3): ''' The same bytes can be decoded to different (valid) Kermit packets depending on which blockcheck checksum is used. This method selects which of the packets should be used. ''' if (not p2) and (not p3): return p1 elif (not p1) and (not p3): return p2 elif (not p1) and (not p2): return p3 else: log.d('Multiple decodes') log.d(self._pstr('p1', p1)) log.d(self._pstr('p2', p2)) log.d(self._pstr('p3', p3)) if p1 and p1.type == 'I': return p1 # Prefer the configured block-check. bc = self.config['receive']['block-check'].value if p1 and bc == 1: return p1 if p2 and bc == 2: return p2 if p3 and bc == 3: return p3 # Prefer more robust blockcheck. if p3: return p3 return p2
def _write_verify(self, src_pkt, ignore_response=False, max_retries=5): """Returns valid packet or None""" retries = 0 while retries < max_retries: self.write_packet(src_pkt) if ignore_response: return None pkt = self.read_any_packet() if pkt: if pkt.type == 'N': log.d('Retrying') elif (pkt.type == 'E') or (pkt.seq_ch == src_pkt.seq_ch): return pkt retries += 1 return None
def __getContent(url, requestHeaders=None): if requestHeaders == None: requestHeaders = headers try: log.d("GET - {0} [{1}]".format(url, requestHeaders)) response = urllib2.urlopen(urllib2.Request(url, headers=requestHeaders)) result = response.read() # log.d("RESPONSE - {0}".format(result)) return result except urllib2.URLError as error: log.e(str(error)) return None
def set_suspend_state(self, config, state): if config.dry_run(): log.w('Skipping because of dry run') return if state: state = "true" else: state = "false" arguments = ['pactl', 'suspend-sink', self.name, state] log.d('set_suspend_state {}'.format(' '.join(arguments))) return_code, stdout, stderr = utlis.run(arguments) if return_code != 0: log.e('\'{}\' () failed, stderr:\n{}'.format(" ".join(arguments), stderr))
def _send_bytes(self, bytes): max_retries = self.config['send-retry'].value init_wait = self.config['init-wait'].value blks = self._construct_blocks(self._split_data(bytes)) lenblks = len(blks) self.transport.clear_buffer() log.i('Waiting to hear from remote') retries = 0 while True: if retries >= init_wait: return False resp = self._rcv_resp() if resp == R.NACK or self.config['ignorerx'].value: break if resp == R.CANCEL: return False retries += 1 log.i('Sending {} bytes in {} blocks'.format(len(bytes), lenblks)) retries = 0 block_num = 0 while True: if retries == 0: log.i('Block {} of {}'.format(block_num + 1, lenblks)) self.transport.write_bytes(blks[block_num]) resp = self._rcv_resp() if resp == R.CANCEL: log.i('Remote host aborted transfer') break elif resp == R.ACK: retries = 0 block_num += 1 if block_num >= lenblks: return self._send_end_trans() else: if resp != R.NACK and resp != R.FAIL: log.d('Unhandled case ' + str(resp)) if retries >= max_retries: log.i('Too many retries.') self.transport.write_bytes(CCC) break retries += 1 log.i('Retrying ' + str(retries)) return False
def action(self, action): if action == BasestationInterface.Action.ON: if self.process is not None: raise NotImplementedError() arguments = [ sys.executable, # Current Python interpreter self.lhctrl_path, '--lh_b_id', self.config.basestation_id('b'), '--lh_b_mac', self.config.basestation_mac_address('b'), '--lh_c_id', self.config.basestation_id('c'), '--lh_c_mac', self.config.basestation_mac_address('c'), '--lh_timeout', str(10), '--ping_sleep', str(5), '--try_count', str(self.config.basestation_attempt_count_set()), '--try_pause', str(1), '--interface', str(self.config.basestation_bluetooth_interface()), ] log.i("Starting lhctrl: {}".format(arguments)) self.process = subprocess.Popen(arguments) elif action == BasestationInterface.Action.OFF: log.i('Terminating all instances of lhctrl') lhctrl_processes = [] for process in psutil.process_iter(): cmd_line = process.cmdline() if len(cmd_line) >= 2 and cmd_line[1] == self.lhctrl_path: lhctrl_processes.append(process) log.d('Found {} instances of lhctrl'.format(len(lhctrl_processes))) for process in lhctrl_processes: process.send_signal(signal.SIGINT) else: raise NotImplementedError()
def main(): addr, port = '127.0.0.1', 8080 if len(sys.argv) > 1 : addr, port = parse_args() log.d("addr: {}:{}".format(addr, port)) s = socket(AF_INET, SOCK_STREAM) s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) try: s.bind((addr, port)) s.listen(10) while 1: global lis conn,addr = s.accept() log.i("connected by {}".format(addr)) thread.start_new_thread(switch_handler, (s, conn, addr)) finally: s.close()
def __init__(self, search_string, movie_cache=None): log.d("MainFrame, start up for " + search_string) self.movie_cache = movie_cache if (movie_cache): self.movie_list = self.movie_cache.getList() else: self.movie_list = [] self.origin_search_string = search_string self.search_string = search_string self.provider = data.SearchQuest() self.root = Tkinter.Tk() self.root.title(u"影片摘要") self.root.config(menu=MainMenu(self.root)) #self.refreshView(self.movie_list) if (len(self.movie_list) == 0 and self.search_string): #threading.Thread(target = self.searchFromThread).start() self.movie_list = self.provider.getMovieListByKeyword( self.origin_search_string) self.refreshView(self.movie_list) self.center_window() self.root.mainloop()
def getImagePath(image_url, selected=False): file_name = hashlib.md5(image_url).hexdigest() + ".jpg" if (GlobalData.run_path): image_sel_path = GlobalData.run_path + os.sep + file_name if (os.path.exists(image_sel_path)): return image_sel_path image_tmp_path = config.getImageCachePath() + os.sep + file_name if (os.path.exists(image_tmp_path)): if (selected): ImageCache.update(image_url, selected) return image_tmp_path if (selected): image_path = image_sel_path else: image_path = image_tmp_path image_path = ImageCache.downloadImage(image_url, image_path) if (image_path): log.d("getImagePath from net: " + image_url) return image_path else: log.d("getImagePath fail: " + image_url)
def login(user, password): try: usuario = Usuario.get(Usuario.email == user) if usuario.senha != password: return None now = datetime.datetime.now() deleteQuery = TokenAuth.delete().where(TokenAuth.usuario==usuario).where(TokenAuth.validade<now) deleteQuery.execute() loop = True while loop: novoToken = str(uuid.uuid4()) try: TokenAuth.get(TokenAuth.token==novoToken) except DoesNotExist, e: loop = False tokenValidade = datetime.datetime.now() + datetime.timedelta(days=2) token = TokenAuth.create(usuario=usuario, token=novoToken, validade=tokenValidade) log.d("Token Criado " + token.token)
def get_port(self, device_type): if device_type == "vr": card_port_product_name_regex = self.config.audio_card_port_vr_product_name_regex( ) elif device_type == "normal": card_port_product_name_regex = self.config.audio_card_port_normal_product_name_regex( ) else: raise NotImplementedError() if card_port_product_name_regex is None: log.d( "Skipping port selection for {device_type} device because card_port_{device_type}_product_name_regex is not set." .format(device_type=device_type)) return None cards = pactl_interface.Card.get_all_cards() for card in cards: for port in card.ports: if port.product_name is not None: if re.match(card_port_product_name_regex, port.product_name): return port debug_output = '' for card in cards: debug_output += card.name + '\n' for port in card.ports: debug_output += ' {}\n'.format( port.product_name if port.product_name is not None else '-' ) log.w( 'Failed to find any port on any card matching "{}". Name of the product at every port:\n{}' .format(card_port_product_name_regex, debug_output)) return None
def __init__(self, config, stream_type): self.config = config self.stream_type = stream_type self.output_logger = OutputLogger() self.failed_stream_connections = [ ] # stream_connections for which move-sink-input failed (Failure class) vr_stream_regex = self.get_vr_stream_regex() normal_stream_regex = self.get_normal_stream_regex() if normal_stream_regex == '': normal_stream_regex = None streams = self.get_all_streams() if normal_stream_regex is None: default_stream_name = self.get_default_stream_name() default_stream = ([ stream for stream in streams if stream.name == default_stream_name ] + [None])[0] if default_stream is None: raise RuntimeError('Default stream was not found.') self.normal_stream = default_stream else: self.normal_stream = self.find_matching_stream( streams, normal_stream_regex, "normal") log.d('normal {}: {}'.format(self.get_stream_type_name(), self.normal_stream.name)) self.vr_stream = self.find_matching_stream(streams, vr_stream_regex, "vr") log.d('vr {}: {}'.format(self.get_stream_type_name(), self.vr_stream.name))
def _is_next_seq(self, prev_pkt, pkt): ''' Returns True if the sequence number of pkt succeeds the sequence number of prev_pkt; otherwise returns False. ''' # Ideally, this would also enforce the 'type' transitions from prev_pkt # to pkt, but the complete type transitions that the HP Calc can send is # not known; a message is logged when an unexpected type transition occurs. states = { 'S': 'FX', 'F': 'D', 'D': 'DZ', 'Z': 'BF', 'B': 'IS', 'X': 'D', } if not prev_pkt: if pkt.type not in 'ISGECNR': # I Initialize # S SendInitiate # G General # E Error # C Command # N Nack # R Receive log.d('Bad type. Expected one of "ISGECNR". Actual:{}'.format( pkt.type)) return True prev_seq_num = unChar(prev_pkt.seq_ch) cur_seq_num = unChar(pkt.seq_ch) is_ok = ((prev_seq_num + 1) % 64 == cur_seq_num % 64) if prev_pkt.type in states.keys(): expected_types = states[prev_pkt.type] + 'NE' if pkt.type not in expected_types: log.d('Bad type. Expected:{} Actual:{}'.format( states[prev_pkt.type], pkt.type)) else: log.d('Previous pkt type {} not in states {}'.format( prev_pkt.type, states.keys())) return is_ok
def requestSearch(self, keyword): log.d("search keyword: " + getDecodedString(keyword)) self.origin_search = keyword self.search = getUtf8String(keyword) count = config.getSearchCount() request_string = "/v2/movie/search?count=" + str( count) + "&q=" + self.search log.d("req: http://api.douban.com" + request_string) conn = httplib.HTTPConnection("api.douban.com") conn.request("GET", request_string) res = conn.getresponse() ret = res.read() if (res.status == 200): log.d("res: " + str(res.status) + ", " + str(res.reason) + ", " + ret) return ret else: log.e("res: " + str(res.status) + ", " + str(res.reason) + ", " + ret)
def login(username, password): log.d("being login.. \nusername:"******"get Captcha is :" + captcha) formData = { '_xsrf': _xsrf, 'email': username, 'password': password, 'remember_me': 'true', } formData['captcha'] = captcha loginResponse = session.post(postUrl, data=formData, headers=headers, verify=False) loginJson = json.loads(loginResponse.text) log.d('json:' + str(loginJson))
def toWebBrowser(self, event): if (self.web_url): log.d("open web browser for: " + self.web_url) webbrowser.open_new_tab(self.web_url)
def _handle_one_line(self, line): conv = Conversion() conv.from_string(line) log.d(conv.description()) self.conversions.append(conv)
def myMsg(self): log.d("\n[NOStraTV App] OK pressed \n") self.session.open(MessageBox, _("NOStraTV App!"), MessageBox.TYPE_INFO)
def cancel(self): log.d("\n[NOStraTV App] cancel\n") self.close(False, self.session)
def _server(self, exit_on_eot=False, init_pkt=None): in_name = None in_buf = [] done = False prev_pkt = None while not done: pkt = init_pkt or self.read_any_packet() if init_pkt: init_pkt = None if not pkt: log.d('No packet read') continue if self._is_resend(prev_pkt, pkt) or self._is_init_pkt(pkt): self._do_ack(pkt) continue if not self._is_next_seq(prev_pkt, pkt): self._do_nack(pkt) continue if pkt.type == 'S': self.set_receive_params(pkt) elif pkt.type == 'N': if unChar(pkt.seq_ch) == 0: # e.g. Command was rejected None # Needed only for test branch coverage module. return else: None # Needed only for test branch coverage module. continue elif pkt.type == 'G': payload = ''.join(pkt.payload) if payload == 'F': self._do_ack(pkt) done = True elif payload == 'L': self._do_ack(pkt) return elif payload.startswith('M:'): log.i('Message: {}'.format(''.join( self._unescape_payload(payload[2:])))) elif payload == 'I': self._send_bytes(None, 'HpirComm Server') prev_pkt = None continue elif pkt.type == 'F': in_name = ''.join(self._unescape_payload(pkt.payload)) if not in_name: self._do_nack(pkt) continue elif pkt.type == 'D': in_buf.extend(self._unescape_payload(pkt.payload)) elif pkt.type == 'Z': if in_buf: self._save_buf_data(in_name, in_buf) del in_buf[:] # clear buffer, but keep the same reference elif pkt.type == 'C': cmd = ''.join(pkt.payload) log.i('Executing cmd: {}'.format(cmd)) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) # CAUTION: Security hazard. stdout, stderr = p.communicate() log.i('{}'.format(stdout)) self._send_bytes(None, stdout) prev_pkt = None continue elif pkt.type == 'R': self._send_file(''.join(pkt.payload), False) prev_pkt = None continue elif pkt.type == 'B': if exit_on_eot: done = True elif pkt.type == 'X': pass elif pkt.type == 'E': log.i('Remote error: {}'.format(''.join( self._unescape_payload(pkt.payload)))) self._do_ack(pkt) return else: log.d('Unhandled packet:{}'.format(pkt.to_list())) self._do_ack(pkt) prev_pkt = pkt
def deploy(self): log.i("deploy script: " + self.deploy_script + ", to path:" + self.target_path) for dirpath, dirnames, filenames in os.walk(self.target_path): log.d("deploy to " + dirpath) shutil.copy(self.deploy_script, dirpath)
def init_at_first_bp(dbg): log.d("[*] Pydbg first point at %#x, HookPoints init..." % dbg.context.Eip, dbg) hook_man.start_hook(dbg)
def log_state(self): log.d('last_pactl_sinks:\n{}'.format(self.last_pactl_sinks)) log.d('last_pactl_sink_inputs:\n{}'.format( self.last_pactl_sink_inputs)) log.d('last_pactl_clients:\n{}'.format(self.last_pactl_clients))
def to_packet(self, buf, blockcheck, log_checksum=True): """Construct a KermitPacket from buffer""" if not buf: return None if blockcheck == 1: min_length = 6 # hdr, len, seq, type, 1-byte chksum, trailer elif blockcheck == 2: min_length = 7 # hdr, len, seq, type, 2-byte chksum, trailer elif blockcheck == 3: min_length = 8 # hdr, len, seq, type, 3-byte chksum, trailer else: log.d('Bad blockcheck value {}'.format(blockcheck)) return None if len(buf) < min_length: return None header = buf[0] length = chr(buf[1]) seq_ch = chr(buf[2]) type = chr(buf[3]) if blockcheck == 1: payload = [chr(p) for p in buf[4:-2]] chksum = chr(buf[-2]) elif blockcheck == 2: payload = [chr(p) for p in buf[4:-3]] chksum = [chr(buf[-3]), chr(buf[-2])] else: # blockcheck == 3: payload = [chr(p) for p in buf[4:-4]] chksum = [chr(buf[-4]), chr(buf[-3]), chr(buf[-2])] trailer = buf[-1] rcv_header = self.config['receive']['start-of-packet'].value if header != rcv_header: log.d('Bad header. Expected:{} Actual:{}'.format( rcv_header, header)) return None if unChar(seq_ch) > 63: log.d('Bad seq num. Actual:{} (exceeds 63)'.format(unChar(seq_ch))) return None if type not in 'BCDEFGINRSXYZ': log.d('Unknown type:{}'.format(type)) return None rcv_trailer = self.config['receive']['end-of-line'].value if trailer != rcv_trailer: log.d('Bad end-of-line. Expected:{} Actual:{}'.format( rcv_trailer, trailer)) return None pkt = KermitPacket(blockcheck, type, seq_ch, payload, rcv_header) if length != pkt.length(): log.d('Bad length. Expected:{} Actual:{}'.format( length, pkt.length())) return None if chksum != pkt.checksum(): if log_checksum: log.d('Bad checksum. Expected:{} Actual:{}'.format( chksum, pkt.checksum())) return None return pkt
def init_at_first_bp(dbg): log.d("[*] Pydbg first point at %#x, HookPoints init..."% dbg.context.Eip, dbg) hook_man.start_hook(dbg)
#!/usr/bin/env python #coding: utf-8 import sys sys.path.append('./common') import log log.logger.setLevel(log.ERROR) if __name__ == '__main__': log.initLogger('./logs/log.txt') log.d('this is a debug message') log.i("info 1+1=%d", 1 + 1) log.w('warning: %s', 'xxxxxx') log.e('error message') log.c("critical message, exit!") log.i("xxx")
def log_all(self): for command, output in self.outputs_by_command.items(): log.d('Most recent output of \'{}\':\n{}'.format(command, output))