def do_invite_message_received(self, bin_header, slp, message): '''method called when an invite message is received in the switchboard''' if slp.content_type == msn_slp.SLPMessage.CONTENT_SESSION_REQ: if 'Context' not in slp.body: common.debug('no context in p2p invite', 'p2p') return if slp.body['EUF-GUID'] == msn_slp.SLPMessage.EUFGUID_FILE: # is a file rawcontext = slp.body['Context'] context = msn_p2p.FTContext(base64.b64decode(rawcontext)) # create a ft receiver here msn_p2p.FTReceiver(self, context, slp, bin_header) return else: data = self.get_data_by_context(slp.body['Context']) if data is not None: msn_p2p.Sender(self, bin_header, slp, data) return elif slp.content_type in (msn_slp.SLPMessage.CONTENT_TRANS_REQ, msn_slp.SLPMessage.CONTENT_TRANS_RESP): # its a direct connect invite if not self.dchandler: self.dchandler = msn_p2p.DCHandler(self, bin_header, slp) else: self.dchandler.handle_invite(bin_header, slp) return common.debug('invalid invite message', 'p2p')
def checkBytesPassword(bWord): isGood = False #print(word) # res = test2.match(word) # if res: # debug("test2 pass") word = bWord.decode() if not 'i' in word and not 'l' in word and not 'o' in word: prevChar = bWord[0] counter = 0 straightChars = 1 res = test3.match(word) if res: debug("test3 pass") for char in bWord: if counter > 0: if char == (prevChar + 1): straightChars += 1 else: straightChars = 1 if straightChars == 3: isGood = True debug("test1 pass") break prevChar = char counter += 1 return isGood
def processCommand(self, command, tid, params): if command == 'CHL': self.callbacks.challenge(self, command, tid, params) self.socket.on_login = False #self.emit('challenge', command, tid, params) elif command == 'ILN': self.callbacks.statusChange(self, command, tid, params) gobject.idle_add(self.emit, 'initial-status-change', command, tid, params) elif command == 'NLN': self.callbacks.statusOnline(self, command, tid, params) self.emit('status-online', command, tid, params) elif command == 'FLN': self.callbacks.statusOffline(self, command, tid, params) self.emit('status-offline', command, tid, params) elif command == 'RNG': self.emit('switchboard-invitation', command, tid, params) elif command == 'ADL': if params != 'OK': payload = self.socket.receivePayload(int(params)) # this looks like when someone adds you # <ml><d n="gmail.com"><c n="luismarianoguerra" t="1" l="8" \ # f="[Mariano%20Guerra]%20(IRC%20is%20just%20multiplayer%20 \ # notepad.)" /></d></ml> email = payload.split('<c n="')[1].split('"')[0] + '@' + \ payload.split('<ml><d n="')[1].split('"')[0] nick = '' try: nick = payload.split(' f="')[1].split('"')[0] nick = urllib.unquote(nick) except: pass lists = self.contactManager.lists if email not in lists['Block'] and email not in lists['Allow']: self.emit('add-notification', command, tid, params, \ email, nick) elif command == 'RML': if params != 'OK': payload = self.socket.receivePayload(int(params)) # this looks like when someone removes you: # <ml><d n="gmail.com"><c n="luismarianoguerra" t="1" \ # l="8" /></d></ml> email = payload.split('<c n="')[1].split('"')[0] + '@' + \ payload.split('<ml><d n="')[1].split('"')[0] self.emit('remove-notification', command, tid, params, email) elif command == 'UBX': payload = self.socket.receivePayload(int(params)) payload = payload.decode('utf-8', 'replace').encode('utf-8') common.debug('<<< ' + payload, 'core') if int(params) > 0: try: self.parseUBX(command, tid, params, payload) except Exception, e: common.debug('Unable to handle UBX: ' + str(e))
def __call__(self, key, values): """ Reducer Program: generate the model arguments Inputs: key: untified id values: resultD and resultH Outputs: model arguments """ globalD = None globalH = None for value in values: debug(np.shape(value[1])) debug(np.shape(value[0])) globalD = globalD + np.array(value[0]) if globalD is not None else np.array(value[0]) globalH = globalH + np.array(value[1]) if globalH is not None else np.array(value[1]) debug("global") debug(np.shape(globalH)) debug(np.shape(globalD)) yield "nonused", (globalD.tolist(), globalH.tolist())
def sync_addresses(self, wallet): common.debug('downloading wallet history') #sets Wallet internal indexes to be at the next unused address for mix_depth in range(wallet.max_mix_depth): for forchange in [0, 1]: unused_addr_count = 0 last_used_addr = '' while unused_addr_count < wallet.gaplimit or\ wallet.index[mix_depth][forchange] <= wallet.index_cache[mix_depth][forchange]: addrs = [wallet.get_new_addr(mix_depth, forchange) for i in range(self.BLOCKR_MAX_ADDR_REQ_COUNT)] #TODO send a pull request to pybitcointools # because this surely should be possible with a function from it blockr_url = 'http://' + self.blockr_domain + '.blockr.io/api/v1/address/txs/' #print 'downloading, lastusedaddr = ' + last_used_addr + ' unusedaddrcount= ' + str(unused_addr_count) res = btc.make_request(blockr_url+','.join(addrs)) data = json.loads(res)['data'] for dat in data: #if forchange == 0: # print ' nbtxs ' + str(dat['nb_txs']) + ' addr=' + dat['address'] + ' unused=' + str(unused_addr_count) if dat['nb_txs'] != 0: last_used_addr = dat['address'] unused_addr_count = 0 else: unused_addr_count += 1 if last_used_addr == '': wallet.index[mix_depth][forchange] = 0 else: wallet.index[mix_depth][forchange] = wallet.addr_cache[last_used_addr][2] + 1
def statusOnline( self, msnp, command, tid, params ): '''handles NLN messages which notify when a contact logs in or changes status, nick, capabilities, msnobj, etc''' status = tid t = params.split(' ') email = t[0].lower() nick = urllib.unquote(t[2]).decode('utf-8', 'replace').encode('utf-8') oldStatus = self.msn.contactManager.getContactStatus( email ) self.msn.contactManager.setContactStatus( email, status ) if len( t ) == 5: msnobj = t[4] contact = self.msn.contactManager.getContact( email ) contact.clientid = int(t[3]) if contact != None: msnObject = Msnobj.createFromString( msnobj ) if contact.msnobj == None or \ (msnObject != None and \ msnObject != contact.msnobj): contact.msnobj = msnObject self.msn.emit( 'msnobj-changed', msnObject, (oldStatus=='FLN') ) if self.msn.contactManager.getContactNick( email ) != nick: self.msn.emit( 'nick-changed', email, nick ) self.msn.contactManager.setContactNick( email, nick ) if oldStatus != status: common.debug('%s (%s) changed status from %s to %s' % \ (nick, email, oldStatus, status), 'signal handler') self.msn.emit( 'user-online', email, oldStatus ) self.msn.emit( 'contact-status-change', email, status ) contact = self.msn.contactManager.getContact( email ) self.msn.emit( 'user-attr-changed', contact )
def statusOnline( self, msnp, command, tid, params ): '''handle a friend going online''' status = tid t = params.split(' ') email = t[ 0 ].lower() nick = urllib.unquote(t[1]) nick = nick.decode('utf-8', 'replace').encode('utf-8') oldStatus = self.msn.contactManager.getContactStatus( email ) self.msn.contactManager.setContactStatus( email, status ) if len( t ) == 4: msnobj = t[ 3 ] contact = self.msn.contactManager.getContact( email ) if contact != None: msnObject = Msnobj.createFromString( msnobj ) if contact.msnobj == None or \ (msnObject != None and \ msnObject != contact.msnobj): contact.msnobj = msnObject self.msn.emit( 'msnobj-changed', msnObject, (oldStatus=='FLN') ) if self.msn.contactManager.getContactNick( email ) != nick: self.msn.emit( 'nick-changed', email, nick ) self.msn.contactManager.setContactNick( email, nick ) if oldStatus != status: common.debug('%s (%s) changed status from %s to %s' % \ (nick, email, oldStatus, status), 'signal handler') self.msn.emit( 'user-online', email, oldStatus ) self.msn.emit( 'contact-status-change', email, status ) contact = self.msn.contactManager.getContact( email ) self.msn.emit( 'user-attr-changed', contact )
def slice_charset(self): self.charset_list = [] self.charset_lib = {} charset = images.get_image(self.settings["charset"]) charset_rect = charset.get_rect() width = self.settings["tile_size"].width height = self.settings["tile_size"].height number_of_horizontal_slices = charset_rect.width / width number_of_vertical_slices = charset_rect.height / height for v in range(0, number_of_vertical_slices): for h in range(0, number_of_horizontal_slices): subsurface = charset.subsurface(pygame.Rect( width * h, height * v, width, height )) tile_rect = subsurface.get_rect() scale = game.settings.get('screen')["scale"] subsurface = pygame.transform.scale(subsurface, (tile_rect.width * scale, tile_rect.height * scale)) self.charset_list.append(subsurface) self.charset_lib["default"] = self.charset_list[60] debug(self.charset_list, "Created " + str(number_of_horizontal_slices * number_of_vertical_slices) + " Tiles from " + self.settings["charset"])
def get_default_version(env): """Returns the default version string to use for MSVS. If no version was requested by the user through the MSVS environment variable, query all the available the visual studios through get_installed_visual_studios, and take the highest one. Return ------ version: str the default version. """ if 'MSVS' not in env or not SCons.Util.is_Dict(env['MSVS']): # get all versions, and remember them for speed later versions = [vs.version for vs in get_installed_visual_studios()] env['MSVS'] = {'VERSIONS' : versions} else: versions = env['MSVS'].get('VERSIONS', []) if 'MSVS_VERSION' not in env: if versions: env['MSVS_VERSION'] = versions[0] #use highest version by default else: debug('get_default_version: WARNING: no installed versions found, ' 'using first in SupportedVSList (%s)'%SupportedVSList[0].version) env['MSVS_VERSION'] = SupportedVSList[0].version env['MSVS']['VERSION'] = env['MSVS_VERSION'] return env['MSVS_VERSION']
def find_vs_dir_by_vc(self): SCons.Tool.MSCommon.vc.get_installed_vcs() dir = SCons.Tool.MSCommon.vc.find_vc_pdir(self.vc_version) if not dir: debug('find_vs_dir(): no installed VC %s' % self.vc_version) return None return dir
def check(cls): checks = [c.check() for c in cls.__subclasses__()] result = all(c.status for c in checks) msg = [c.message for c in checks if c.message] for m in msg: common.debug(m, error=True) return cls(result, msg)
def registerClient(password, client_id, url, client_password): """Test connection.""" if password == config.password: attk_server.add_client(client_id, url, client_password) debug('client registered, returning server id: %s' % config.client_id) return config.client_id return False
def acceptMessage(self, stanza): """Tell if the message is accepted or not.""" section = 'Message filters' sender = stanza.get_from().bare() try: crit = config.get(section, 'accept') except (NoOptionError, NoSectionError): crit = 'roster+self' debug("Critere: %s" % crit, 8); if crit == 'all': return True if crit == 'none': return False if crit in ['self', 'roster+self']: if sender == self.jid.bare(): return True if crit in ['list', 'roster+list']: try: list = config.get(section, 'list').split(', ') except (NoOptionError, NoSectionError): list = [] if sender.as_utf8() in list: return True if crit in ['roster', 'roster+list', 'roster+self']: try: self.roster.get_item_by_jid(sender) return True except KeyError: return False return False
def add_watchonly_addresses(self, addr_list, wallet_name): common.debug('importing ' + str(len(addr_list)) + ' addresses into account ' + wallet_name) for addr in addr_list: self.rpc('importaddress', [addr, wallet_name, False]) if common.config.get("BLOCKCHAIN", "blockchain_source") != 'regtest': print 'now restart bitcoind with -rescan' sys.exit(0)
def do_login_successful(self): '''logged in :D''' common.debug("logged in", 'core') self.connected = True self.soapManager = SoapManager.SoapManager(self) self.soapManager.start() self.socket.disconnectAll() self.socket.connect('input', self.process) self.socket.connect('hangup', self.socketHangup) self.signals.append(gobject.timeout_add(500, self.soapManager.process)) self.signals.append(gobject.timeout_add(5000, self.checkPing)) mlCache = self.getCacheFileData(self.user + "_ml.xml") diCache = self.getCacheFileData(self.user + "_di.xml") if mlCache and diCache and not self.safemode: common.debug("parsing membership list", 'core') start = time.time() try: self.setMembershipListXml(mlCache) common.debug("done:" + str(time.time() - start), 'core') common.debug("parsing dynamic items", 'core') start = time.time() self.setDynamicItemsXml(diCache) self.getNickFromDynamicItems(diCache) common.debug("done:" + str(time.time() - start), 'core') except Exception, e: #TODO: pylint print "error parsing lists", e self.getMembershipListSync() self.getDynamicItemsSync() self.emit('user-list-change')
def getDisplayPicture(self, email): '''start a P2P session to get the display picture''' if self.msn is None: return email = email.lower() contact = self.msn.contactManager.getContact(email) if contact == None: common.debug('contact (' + email + ') not found in ' + \ 'getDisplayPicture', 'switchboard') return msnobj = contact.msnobj if msnobj == None: common.debug(email + ' has no msnobj in getDisplayPicture', \ 'switchboard') return #print "Switchboard.getDisplayPicture(email=%s)" % email filename = os.path.join(self.msn.cacheDir, contact.displayPicturePath) if not os.path.exists(filename): #print "Requesting avatar for ", email msn_p2p.Receiver(self.msn.p2p[email], msnobj) else: #print "Avatar cached at %s - updating path" % filename self.msn.emit("display-picture-changed", self, msnobj, email)
def callback(self, **status): global server debug('client callback %s' % repr(status)) self.status = status self.running = False server.finish_attack(self.attack_id, self.status)
def moveUserToGroup(self, user, srcGroup, destGroup, stage=0): '''move a user from a group erasing it from de source group''' if stage == 0: contactID = self.contactManager.getContactId(user) sourceGid = self.contactManager.getGroupId(srcGroup) destGid = self.contactManager.getGroupId(destGroup) if sourceGid == 'nogroup': self.addUserToGroup(user, destGroup) return if destGid == 'nogroup': self.removeUserFromGroup(user, srcGroup) return if srcGroup == destGroup: common.debug('src and dest groups are the same') return elif self.contactManager.getGroup(destGid).getUser(user) != None: common.debug('dest group already contain the user') return self.contactManager.removeUserFromGroup(user, sourceGid) self.contactManager.addUserToGroup(user, destGid) self.emit('user-list-change') soap.requests.remove_from_group(contactID, sourceGid, self.onMoveUserToGroup, user, srcGroup, destGroup, 0) elif stage == 1: gid = self.contactManager.getGroupId(destGroup) contactID = self.contactManager.getContactId(user) soap.requests.add_to_group(gid, contactID, self.onMoveUserToGroup, user, srcGroup, destGroup, 1)
def getContact(self, email): email = email.lower() if self.contacts.has_key(email): return self.contacts[email] else: common.debug('user %s not found, returning dummy user' % (email,)) return self.getDummyContact(email)
def sendMessage(self, msg='', format='', \ contentType='text/plain; charset=UTF-8', \ acknowledgeType='A', extraHeader=''): header = "MIME-Version: 1.0\r\n" if contentType != "": header += "Content-Type: " + contentType + "\r\n" if extraHeader != "": header += extraHeader + '\r\n' if contentType == 'text/plain; charset=UTF-8': msg = msg[:1100] #TODO: use something like MAX_MESSAGE_LENGTH self.emit('message-sent', msg, format, contentType.split('charset=')[1]) if format != "": header += format + "\r\n\r\n" else: header += "\r\n" if self.status != 'established': self.messageQueue.append({ 'msg': msg, \ 'header': header, \ 'acknowledgeType': acknowledgeType, \ }) elif self.status == 'established': try: self.socket.sendPayloadCommand('MSG', acknowledgeType, \ header + msg) except Exception, e: common.debug('socket error on switchboard, closing', 'switchboard') common.debug(str(e), 'switchboard') self.setStatus('closed')
def __call__(self, data): """ Mapper Program: Inputs: data, which is the whole split block data Outputs: key: untified id value: resultD,resultH """ # SETP1: read data matrix and do some transpose resultH = None resultD = None for docID, doc in data: for term in doc.split("\n"): self.SEP = self.SEP if self.SEP is not None else get_sep(term) point = np.fromstring(term, dtype=np.float64, sep=self.SEP) (localH, localD) = self.calculate(point) if resultH is not None: resultH = resultH + localH resultD = resultD + localD else: resultH = localH resultD = localD debug(np.shape(resultH)) debug(np.shape(resultD)) yield "nonused", (resultD.tolist(), resultH.tolist())
def onUserAdded(self, response, email, group, *callback_and_args_triple): '''this method is called when the addUser soapRequest get a response''' common.debug('add user: '******' ' + str(response.status)) if response.status[0] == 200: # Now that we have the contact id, we show it self.contactManager.setContactIdXml(email, response.body) guid = response.body.split('<guid>')[1].split('</guid>')[0] self.emit('contact-added', email, guid, None, None, 'FLN', None, False) if group == '': self.emit('user-list-change') else: # once we now the id we can add it to a group self.addUserToGroup(email, group) if len(callback_and_args_triple[0]) == 3: # alias hack foo(bar, lol) func, acco, alias = callback_and_args_triple[0] if alias != '': func(acco, alias) else: self.contactManager.removeContact(email) self.emit('user-list-change') self.emit('error', 'user-add-error', _('User could not be added: %s') % \ common.parseSoapFault(response))
def rpc(self, method, args): if method not in ['importaddress', 'walletpassphrase']: common.debug('rpc: ' + method + " " + str(args)) res = self.jsonRpc.call(method, args) if isinstance(res, unicode): res = str(res) return res
def changeNick(self, nick, initial=False): nick = nick.decode('utf-8', 'replace').encode('utf-8') if nick == '': nick = self.user if not initial and self.nick == nick: common.debug('trying to set the same nick') return if len(nick) > 129: # to avoid problems with utf-8 return oldNick = self.nick self.nick = nick #self.contactManager.setContactNick(self.user, self.nick) self.emit('self-nick-changed', oldNick, self.nick) self.socket.sendCommand("PRP", "MFN " + urllib.quote(nick)) if not initial: if self.rid != "":# self.affinityCache != '': soap.requests.update_profile(self.proxy, self.affinityCache, \ self.rid, common.escape(nick), \ common.escape(self.personalMessage), self.onNickChanged, oldNick)
def __init__ (self, src_vm, src_ip, dst_vm, dst_ip, json_file): self.info = load_json(json_file) vm_list = pprint.pformat(sorted(self.info['vms'].keys())) if not self.info['vms'].has_key(src_vm): error('VM [%s] does not exist in %s !' % (src_vm, vm_list)) return None if not self.info['vms'].has_key(dst_vm): error('VM [%s] does not exist in %s !' % (dst_vm, vm_list)) return None self.src_vm = src_vm self.src_ip = src_ip self.dst_vm = dst_vm self.dst_ip = dst_ip (self.src_port_id, self.src_port_tag) = get_port_ovs_id_tag(self.info, src_vm, src_ip) (self.dst_port_id, self.dst_port_tag) = get_port_ovs_id_tag(self.info, dst_vm, dst_ip) if not self.src_port_id: error('%s does not have port with IP %s' % (src_vm, src_ip)) return None if not self.dst_port_id: error('%s does not have port with IP %s' % (dst_vm, dst_ip)) return None debug(src_ip + ': ' + str(self.src_port_id)) debug(dst_ip + ': ' + str(self.dst_port_id)) pass
def __get_edge_color (self, src_tag, dst_tag): if not self.highlight_file: return self.__get_color('edge') sport = src_tag dport = dst_tag m = re.search('\S+:(\S+)', src_tag) if m: sport = m.group(1) m = re.search('\S+:(\S+)', dst_tag) if m: dport = m.group(1) spass = self.__port_pass(sport) dpass = self.__port_pass(dport) sfail = self.__port_fail(sport) dfail = self.__port_fail(dport) debug('%s (p%d f%d) -> %s (p%d f%d)' % (sport, spass, sfail, dport, dpass, dfail)) if spass or dpass: return self.colors['edge_pass'] if sfail and dfail: return self.colors['fail'] return self.colors['dontcare']
def find_vs_dir_by_vc(self): SCons.Tool.MSCommon.vc.get_installed_vcs() ivc = SCons.Tool.MSCommon.vc.InstalledVCMap.get(self.vc_version) if not ivc: debug('find_vs_dir(): no installed VC %s' % self.vc_version) return None return ivc.get_vc_dir()[:-len(ivc.vc_subdir)]
def rpc(self, method, args): if method != 'importaddress': common.debug('rpc: ' + method + " " + str(args)) res = self.jsonRpc.call(method, args) if isinstance(res, unicode): res = str(res) return res
def analyze (json_filename, params): settings['debug'] = True BASE_DIR = os.path.dirname(os.path.dirname(__file__)) print 'analyze BASE_DIR ---> ',BASE_DIR CUR_DIR = os.getcwd() os.chdir(BASE_DIR + '/ovs') NEW_DIR = os.getcwd() #return BASE_DIR + ':' + CUR_DIR + ':' + NEW_DIR debug('This is what I am going to analyze') my_info = load_json(json_filename) for test in test_suite.keys(): flag = 'test:' + test if params[flag] or params['test:all']: (result, cmds) = test_suite[test]['func'](my_info) if result: test_suite[test]['result'] = 'PASS' else: test_suite[test]['result'] = 'FAIL' lines = test_suite[test]['formatter'](cmds, result, my_info, test_suite[test]['help']) test_suite[test]['html'] = lines debug(params['test:report_file']) f = report_file_open(params['test:report_file']) for test in test_suite.keys(): if test_suite[test]['html']: for line in test_suite[test]['html']: f.write(line) report_file_close(f) os.chdir(CUR_DIR)
def checkAttack(attack_id): debug('xml.checkAttack %s' % attack_id) try: if attack_id in attk_client.attacks: return attk_client.attacks[attack_id].check() else: raise err_not_running() except Fault: raise
def get_installed_visual_studios(): global InstalledVSList global InstalledVSMap if InstalledVSList is None: InstalledVSList = [] InstalledVSMap = {} for vs in SupportedVSList: debug('trying to find VS %s' % vs.version) if vs.get_executable(): debug('found VS %s' % vs.version) InstalledVSList.append(vs) InstalledVSMap[vs.version] = vs return InstalledVSList
def run(self, mode=-1): result = True if not common.any2bool( xbmc.getInfoLabel("Window(%s).Property(%s)" % (10000, "SystemRecovery.Running"))): # set windows setting to true window = xbmcgui.Window(10000) window.setProperty("SystemRecovery.Running", "true") if self.remoteFS.RootPath is not None and self.remoteFS.RootPath != '': common.debug( "Local directory: " + self.localFS.RootPath + ", Remote directory: " + self.remoteFS.RootPath, "SystemRecovery") if mode == self.Backup: if common.setting("compress_backups"): # delete old temp file if self.localFS.exists( common.path('special://temp/backup.zip')): self.localFS.rmfile( common.path('special://temp/backup.zip')) # save the remote file system and use the zip vfs self.savedRemoteFS = self.remoteFS self.remoteFS = ZipFileSystem( common.path("special://temp/backup.zip"), "w") self.remoteFS.setRootPath(self.remoteFS.RootPath + time.strftime("%Y%m%d%H%M") + "/") # run backup process self.backup() result = self.status >= 0 elif mode == self.Restore: if self.restorePoint.split('.')[-1] != 'zip': self.remoteFS.setRootPath(self.remoteFS.RootPath + self.restorePoint + "/") # run restore process self.restore() result = self.status >= 0 else: result = False # cleaning locations self.localFS.cleanup() self.remoteFS.cleanup() else: result = False # reset the window setting window.setProperty("SystemRecovery.Running", "") else: common.warn( 'Script already running, no additional instance is needed') result = False return result
def solve(self, V1, V2, P, timeout=None): if timeout: self.timeout = timeout self.starttime = time.time() self.V1 = V1 self.V2 = V2 self.P = P self.varstodict() self.C = [] # Constraints self.O = {} # Objective fnc otostart = time.time() self.encode_onetoone() self.ototime = time.time() - otostart if self.lefttime() <= 0: raise Timeout() pstart = time.time() self.encode_P() self.ptime = time.time() - pstart if self.lefttime() <= 0: raise Timeout() mstart = time.time() self.build_model() self.mtime = time.time() - mstart if self.lefttime() <= 0: raise Timeout() sstart = time.time() solve_rounds = 0 result = None while result is None: self.solve_model() result = self.decode_model() solve_rounds += 1 self.stime = time.time() - sstart if self.verbose: debug('OTO time: %.3f', round(self.ototime, 3)) debug('P time: %.3f', round(self.ptime, 3)) debug('M time: %.3f', round(self.mtime, 3)) debug('S time: %.3f', round(self.stime, 3)) debug('S rounds: %d', solve_rounds) return result
def main(): """ This method is called when the game is initialized. It will continue to run for the entirety of the duration of the game :return: None """ print("... Starting chess game v0.1") pygame.init() board = Board() screen = pygame.display.set_mode((common.GAME_WIDTH, common.GAME_HEIGHT)) pygame.display.set_caption(common.TITLE + " (\"" + board.current_color.capitalize() + "\" to move)") pygame.display.set_icon(pygame.image.load(os.path.join("pics", "Icon.png"))) clock = pygame.time.Clock() pygame.font.init() screen.fill(pygame.Color("white")) dict_images = load_images() position = False run = True while run: clock.tick(common.MAX_FPS) if not redraw_game_state(screen, board, dict_images): run = False pygame.quit() pygame.display.set_caption(common.TITLE + " (\"" + board.current_color.capitalize() + "\" to move)") for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() if event.type == pygame.MOUSEBUTTONDOWN: mouse_current_position = pygame.mouse.get_pos() last_position = position position = click_on_chessboard(mouse_current_position) if position is not False: board.select(position) common.debug("Position: (%d, %d)" % (position[0], position[1])) if position is not False and last_position is not False: if board.is_move_valid(last_position, position): board.move(last_position, position) board.update_current_color() board.cancel() position = False
def _setTrimmedCache(self): if self.__RESTRICTCACHE and self.__MAXCACHESIZE is not None: now = time.time() cache_trim_delay = 0 # delay time is in seconds if now - self._lastcachetrim > cache_trim_delay: common.debug('Trimming the cache down to %s bytes' % self.__MAXCACHESIZE) cache_root = xbmc.translatePath( 'special://profile/addon_data/%s/data/' % common.AddonId()).decode('utf-8') folders, fls = xbmcvfs.listdir(cache_root) folders.sort(key=lambda x: os.path.getmtime( os.path.join(cache_root, x)), reverse=True) cachesize = 0 firstfolder = True for folder in folders: if self._isPlaybackChanged(): common.debug( "Cancel cache trimming due to the change of player content" ) break cachesize = cachesize + self._sizepath( os.path.join(cache_root, folder)) common.debug('Looking at folder %s cache size is now %s' % (folder, cachesize)) if cachesize > self.__MAXCACHESIZE and not firstfolder: self._setCleanedDirectory( os.path.join(cache_root, folder)) common.debug('Deleted files in folder %s' % folder) firstfolder = False self._lastcachetrim = now
def process(include_diag=False): input_data = common.read_string_file() grid = defaultdict(int) for line in input_data: # debug(line) if line: points = [[int(p) for p in point.strip().split(",")] for point in line.split("->")] increment = [0, 0] for pos in (0, 1): difference = points[1][pos] - points[0][pos] if difference: increment[pos] = difference // abs(difference) debug(f"{points=} {increment=}") # all(increment) will be true for a diag but not a straight if include_diag or not all(increment): point = points[0] while True: grid[tuple(point)] += 1 debug(tuple(point)) point[0] += increment[0] point[1] += increment[1] if point == points[1]: grid[tuple(point)] += 1 debug(tuple(point)) break debug(grid) print_grid(grid) return len([v for v in grid.values() if v >= 2])
def getHttpResponse(self): response = self.connection.getresponse() text = response.read().strip() if response.status == 500: common.debug("500 internal server error", "psocket") self.quit() return 'OUT' elif response.status != 200: raise httplib.HTTPException("Server not available") try: # this header contains important information # such as the IP of the next server we should connect # and the session id assigned data = response.getheader('x-msn-messenger', '') if data.count("Session=close"): common.debug("Session closed", "socket") self.quit() return 'OUT' # parse the field self.sessionID = data.split("; GW-IP=")[0].replace( "SessionID=", "") self.gatewayIP = data.split("; ")[1].replace("GW-IP=", "") self.host = self.gatewayIP self.path = "/gateway/gateway.dll?SessionID=" + self.sessionID except Exception, e: common.debug('In getHttpResponse: ' + str(e), 'socket') common.debug('Data: "%s"' % data, 'socket')
def process_p1(): mappings = { "forward": ("horizontal", 1), "down": ("depth", 1), "up": ("depth", -1) } position = {"horizontal": 0, "depth": 0} input_data = common.read_string_file() for instruction in input_data: (direction, amount) = instruction.split(" ") (key, multiplier) = mappings[direction] position[key] += int(amount) * multiplier debug(position) return position["horizontal"] * position["depth"]
def main(): parser = argparse.ArgumentParser() g = parser.add_mutually_exclusive_group(required=True) g.add_argument('-a', '--all', action='store_true', help='Run tests against all challenge binaries') g.add_argument('-c', '--chals', nargs='+', type=str, help='List of challenge names to test') g = parser.add_mutually_exclusive_group() g.add_argument('--povs', action='store_true', help='Only run tests against POVs') g.add_argument('--polls', action='store_true', help='Only run tests against POLLS') parser.add_argument( '-o', '--output', default=None, type=str, help= 'If provided, an excel spreadsheet will be generated and saved here') args = parser.parse_args(sys.argv[1:]) # Disable other tests depending on args if args.povs: Tester.polls_enabled = False if args.polls: Tester.povs_enabled = False if args.all: debug('Running tests against all challenges\n') tests = test_challenges(listdir(BUILD_DIR)) else: debug('Running tests against {} challenge(s)\n'.format(len( args.chals))) tests = test_challenges(args.chals) if args.output: generate_xlsx(os.path.abspath(args.output), tests)
def process_algo( instructions, ops={ "+": add, "*": mul }, calculate_parenthesis_func=calculate_parenthesis, ): stack = [[]] debug(f"Algo instructions: {instructions}") for inst in instructions: debug(f"Stack: {stack}") if inst in ops: stack[-1].append(ops[inst]) elif inst == "(": stack.append([]) elif inst == ")": result = calculate_parenthesis_func(stack[-1]) del stack[-1] stack[-1].append(result) else: stack[-1].append(int(inst)) debug(f"Stack before final calc: {stack}") res = calculate_parenthesis_func(stack[-1]) debug(f"Final result: {res}") return res
def __init__(self, blockr_domain, txd, unconfirmfun, confirmfun): threading.Thread.__init__(self) self.daemon = True self.blockr_domain = blockr_domain self.unconfirmfun = unconfirmfun self.confirmfun = confirmfun self.tx_output_set = set([(sv['script'], sv['value']) for sv in txd['outs']]) self.output_addresses = [ btc.script_to_address(scrval[0], common.get_p2pk_vbyte()) for scrval in self.tx_output_set ] common.debug('txoutset=' + pprint.pformat(self.tx_output_set)) common.debug('outaddrs=' + ','.join(self.output_addresses))
def location(self, loc): locs = [] locids = [] common.debug('Searching for location: %s' % loc, self.code()) url = self.LOCATION % ("\"" + loc + "\"") data = self._call(url) common.debug('Found location data: %s' % data, self.code()) if data is not None and "latitude" in data: self.coordinates(data["latitude"], data["longitude"]) location = loc locationid = str(self.latitude) + "," + str(self.longitude) locs.append(location) locids.append(str(locationid)) return locs, locids
def load_data(config: ValidatorConfig): identity_account_pubkey = rpc.load_identity_account_pubkey(config) default = [] tds_data = default tds_data = tds.load_tds_info(config, identity_account_pubkey) result = { 'identity_account_pubkey': identity_account_pubkey, 'tds_data': tds_data } debug(config, str(result)) return result
def path(params): global src_info global dst_info global net_info src_info = None dst_info = None net_info = None settings['debug'] = True BASE_DIR = os.path.dirname(os.path.dirname(__file__)) CUR_DIR = os.getcwd() if not re.search('/openstack_dashboard/don/', CUR_DIR): os.chdir(BASE_DIR + '/ovs') NEW_DIR = os.getcwd() debug(BASE_DIR + ':' + CUR_DIR + ':' + NEW_DIR) src_ip = params['src_ip'] dst_ip = params['dst_ip'] json_file = params['json_file'] router = params['router'] debug('Json_file: ' + json_file) info = load_json(json_file) qrouter = router_to_namespace(info, router) params['qrouter'] = qrouter src_info = get_port_info(info, src_ip) dst_info = get_port_info(info, dst_ip) if src_info is None: return "Source ip not found on the network" if dst_info is None: return "Destination ip not found on the network" if qrouter is None: return "No such router information found on the network" # src and dst are in the same network if src_info['tag'] == dst_info['tag']: path_same_network(params) else: status_update('The source and destination are in different networks') next_hop_list = get_next_hop(src_info, dst_info, qrouter, params) if len(next_hop_list) == 0: error('Could not find next hop list from %s to %s' % (src_ip, dst_ip)) path_same_network(params, next_hop_list) pass
def _setSlideshowCollection(self): common.debug("Starting slideshow collection") artistsArray = self.getArtistNames() artistsIndex = 0 for artist in artistsArray: if self._isPlaybackChanged(): common.debug( "Cancel slideshow collection due to the change of player content" ) break if artist is None or artist == '': continue artistsIndex += 1 common.debug("Collecting slideshow for artist [%s]" % artist) self.dir_cache = self._resdir(artist) common.trace("Cache directory for artist [%s]: %s" % (artist, self.dir_cache)) self._setSkinSlideshow(self.dir_show, self.dir_cache) if artistsIndex == 1: self._setSkinArtistBiografy(artist) self._setSkinArtistAlbumInfo(artist) self._setSkinArtistImages(artist) self._cache2show() self._setSkinSlideshow(self.dir_cache, self.dir_show) common.sleep() common.debug('Ended slideshow collection')
def workflow(self, trigger=False): common.debug( "Running slideshow workflow %s trigger for data collection" % ("with" if trigger else "without")) try: self._setInitProperties() self._setCleanedDirectory(self.dir_show) if trigger: self._setSlideshowCollection() self._setTrimmedCache() except BaseException as be: common.error("Error running slideshow workflow: %s" % str(be)) if common.istrace: traceback.print_exc()
def table(zones, idFld, output, exterior=True, selfrel=True): common.debug('running neighbour table', zones, idFld, output, exterior, selfrel) with common.PathManager(output) as pathman: idKeeper = common.IDFieldKeeper(zones, idFld) intIDFld = idKeeper.intIDField() if exterior: common.progress('mapping zone surroundings') buffer = pathman.tmpFC() arcpy.Buffer_analysis(zones, buffer, '50 Meters', dissolve_option='ALL') common.progress('creating exterior zone') erased = pathman.tmpFC() arcpy.Erase_analysis(buffer, zones, erased, TOLERANCE) common.progress('identifying exterior zone') common.calcField(erased, intIDFld, EXTERIOR_ID, int) # common.progress('eliminating sliver polygons') common.progress('merging exterior zone') jointo = pathman.tmpFC() arcpy.Merge_management([zones, erased], jointo) else: jointo = zones common.progress('finding neighbours') swm = pathman.tmpFile(ext='swm') arcpy.GenerateSpatialWeightsMatrix_stats(jointo, intIDFld, swm, 'CONTIGUITY_EDGES_CORNERS') common.progress('converting to neighbour table') tmpTable = pathman.tmpTable() arcpy.ConvertSpatialWeightsMatrixtoTable_stats(swm, tmpTable) fromFld, toFld = idKeeper.transform(tmpTable, [intIDFld, 'NID']) fm = arcpy.FieldMappings() fm.addFieldMap( common.fieldMap(tmpTable, fromFld, common.NEIGH_FROM_FLD, 'FIRST')) fm.addFieldMap( common.fieldMap(tmpTable, toFld, common.NEIGH_TO_FLD, 'FIRST')) if selfrel: query = common.safeQuery( "[{}] <> '{}'".format(fromFld, EXTERIOR_ID), tmpTable) else: query = common.safeQuery( "[{0}] <> [{1}] AND [{0}] <> '{2}'".format( fromFld, toFld, EXTERIOR_ID), tmpTable) arcpy.TableToTable_conversion(tmpTable, pathman.getLocation(), pathman.getOutputName(), query, fm) common.clearFields(output, [common.NEIGH_FROM_FLD, common.NEIGH_TO_FLD]) return output
def render_board(self, math_coords=False): """ Renders the data """ debug('CanvasRenderer.render_board() called') if not self.board: messagebox.showerror( 'No Board', 'No board has been selected, cannot render' ) self.clear() payload = self.board.grid row_range = range(0, self.board_height) # If we are drawing using mathematical coordinates (Y-axis reversed) if math_coords: row_range = range(self.board_height - 1, -1, -1) # Iterate through all nodes, create sprite coords and determine fill color for y in row_range: for x in range(len(payload[y])): draw_y = y if math_coords: draw_y = self.board_height - y coords = ( x * BOARD_CELL_SIZE + 1, draw_y * BOARD_CELL_SIZE + 1, x * BOARD_CELL_SIZE + BOARD_CELL_SIZE + 1, draw_y * BOARD_CELL_SIZE + BOARD_CELL_SIZE + 1, ) node = self.board.get_node(x, y) fill_color = '#FFFFFF' if not node.walkable: fill_color = '#000000' elif node.is_start: fill_color = '#4040FF' elif node.is_goal: fill_color = '#40FF40' self.canvas.create_rectangle( *coords, fill=fill_color )
def onGroupRemoved(self, response, gid, group): '''this method is called when the removeGroup soap request get a response''' common.debug('remove group ' + str(response.status)) if response.status[0] == 200: self.emit('group-removed', group) else: # TODO: change it to setGroup when it manages contacts self.contactManager.setGroup(gid, group) self.emit('user-list-change') self.emit( 'error', 'group-remove-error', _('Group could not be removed: %s') % common.parseSoapFault(response))
def md5_test(): debug("md5_test") f2 = "cc8acc06jw1eotnfkqq3vj20dc0dcq32.jpg" p = "./data/%s" % f2 print "p: %s" % p c = read_test(p) #print len(c) dcs = hashlib.md5(c).hexdigest() print "dcs = %s" % dcs cs = "cdff6831f0acaf23b0be001a59de0229" print "cs = %s" % cs if dcs == cs: print "==" else: print "!="
def slice_chipset(self): self.terrains = [] chipset = images.get_image(self.tileset) chipset_rect = chipset.get_rect() number_of_possible_slices = chipset_rect.width / self.tile_width for i in range(0, number_of_possible_slices): subsurface = chipset.subsurface(pygame.Rect( self.tile_width * i, 0, self.tile_width, chipset_rect.height )) tile_rect = subsurface.get_rect() scale = game.settings.get("screen")["scale"] subsurface = pygame.transform.scale(subsurface, (tile_rect.width * scale, tile_rect.height * scale)) self.terrains.append(subsurface) debug(self.terrains, "Created " + str(number_of_possible_slices) + " Tiles from " + self.tileset)
def render(self, *args, **kwargs): """ Renders the main content area, based on a provided render function """ if self.renderer: if isinstance(self.renderer, CanvasRenderer): self.renderer.render_board(*args, **kwargs) elif isinstance(self.renderer, GraphRenderer): self.renderer.render_graph(*args, **kwargs) debug('Main.render() called') else: messagebox.showerror('Missing renderer', 'Main.render() invoked without renderer set') log('Main.render() invoked without renderer set')
def addGroup(self, group): '''add a group to the group list''' if self.contactManager.getGroupId(group) != None: common.debug('Unable to add: Group "' + group \ + '" already exists') return name = group.replace(' ', '%20') soap.manager.do_request(self.proxy,\ 'http://www.msn.com/webservices/AddressBook/ABGroupAdd', 'contacts.msn.com', 443, '/abservice/abservice.asmx', soap.templates.addGroup % (group,), self.onGroupAdded, (group,))
def load_tds_info(config: ValidatorConfig, identity_account_pubkey: str): tds_data = tds_rpc_call(config, identity_account_pubkey) result = {} if tds_data != []: if 'tn_calculated_stats' in tds_data[0] and tds_data[0]['tn_calculated_stats'] is not None: result = { 'tds': tds_data[0]['tn_calculated_stats'], } if 'onboarding_number' in result['tds']: result['tds']['onboarding_number'] = tds_data[0]['onboarding_number'] result['tds']['onboarding_group'] = tds_data[0]['tds_onboarding_group'] debug(config, result) return result
def onUserUnblocked(self, response, email, stage): '''this method is called when the unblockUser soapRequest get a response''' common.debug('unblock user (stage ' + str(stage) + '): ' \ + str(response.status)) if response.status[0] == 200: if stage == 0: self.unblockUser(email, 1) self.emit('contact-attr-changed', email, 'block', False) else: self.contactManager.blockContact(email) contact = self.contactManager.getContact(email) self.emit('user-attr-changed', contact)
def changePersonalMessage(self, pm): '''change the personal message''' if self.personalMessage != pm: if len(pm) > 129: return oldPm = self.personalMessage self.personalMessage = pm self.updateUUX() if self.affinityCache != '': soap.requests.update_profile(self.proxy, self.affinityCache, \ self.rid, common.escape(self.nick), \ common.escape(self.personalMessage), self.onPmChanged, oldPm) self.emit('self-personal-message-changed', self.user, pm) else: common.debug("duplicate pm")
def step(self): self.steps += 1 self.grid += 1 for x in range(self.width): for y in range(self.height): if self.grid[x][y] > 9: self.flash(x, y) # all flashing done, set all -1s to 0 for x in range(self.width): for y in range(self.height): if self.grid[x][y] == -1: self.grid[x][y] = 0 debug(self.steps) debug(self.grid)
def part_2(): mask = FloatingMask() memory = {} for line in process(): if "mask" in line: mask_pattern = line.split("=")[-1].strip() elif "mem" in line: (m, data) = line.split("=") val = int(data) address = int(m.split("[")[-1].split("]")[0]) addresses = mask.apply(mask_pattern, int(address)) for add in addresses: memory[add] = val debug(f"Setting address {add} to {val}") return sum(memory.values())
def _LoadParameters(self): try: self.__params = dict( arg.split("=") for arg in sys.argv[1].split("&")) except: self.__params = {} common.debug("Loading parameters: %s" % str(self.__params)) self.movies = common.any2bool(self.__params.get("movies", "")) self.tvshows = common.any2bool(self.__params.get("tvshows", "")) self.episodes = common.any2bool(self.__params.get("episodes", "")) self.musicvideos = common.any2bool(self.__params.get( "musicvideos", "")) self.artists = common.any2bool(self.__params.get("artists", "")) self.albums = common.any2bool(self.__params.get("albums", "")) self.songs = common.any2bool(self.__params.get("songs", "")) self.actors = common.any2bool(self.__params.get("actors", ""))
def part_1(): input_data = InputData() input_data.parse() debug(f"fields: {input_data.fields}") debug(f"own: {input_data.own}") invalid_vals = [] for other in input_data.yield_others(): other.sort() for val in other: if not any(val in r for r in input_data.ranges): invalid_vals.append(val) debug(f"Invalid val: {val}") break debug(f"other: {other}") debug(f"Invalid vals: {invalid_vals}") return sum(invalid_vals)