rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if len(event.data) > 3:
if len(event.data) > self._ignoreLength:
def onEvent(self, event): try: if not event.client: return elif event.client.cid == None: return elif event.client.maxLevel > self._maxLevel: return elif not event.client.connected: return if len(event.data) > 3: if event.type == b3.events.EVT_CLIENT_SAY or \ event.type == b3.events.EVT_CLIENT_TEAM_SAY: raw = ' ' + eve...
if not self.replay: self.input.seek(0, os.SEEK_END)
def run(self): """Main worker thread for B3""" self.bot('Start reading...') self.screen.write('Startup Complete : Let\'s get to work!\n\n') self.screen.write('(Please check %s in the B3 root directory for more detailed info)\n' % self.config.getpath('b3', 'logfile')) #self.screen.flush()
return b3.events.Event(b3.events.EVT_CLIENT_TEAMKILL, (100, None, None), attacker, victim)
return b3.events.Event(b3.events.EVT_CLIENT_KILL_TEAM, (100, None, None), attacker, victim)
def OnPlayerKill(self, action, data): #player.onKill: ['Juxta', '6blBaJlblu'] if not len(data) == 2: return None attacker = self.getClient(data[0]) if not attacker: self.debug('No attacker') return None
packet = self._packetReader.getPacket()
try: packet = self._packetReader.getPacket() except IncompletePacket: pass
def readBfbc2Event(self): # Wait for packet from server try: packet = self._packetReader.getPacket() while packet is None: try: data = self._serverSocket.recv(1024) if not data: break self._packetReader.append(data) packet = self._packetReader.getPacket() except IncompletePacket: pass except socket.timeout: pass except...
plist = self.getPlayerList(maxRetries=4)
plist = self.getPlayerList()
def sync(self): plist = self.getPlayerList(maxRetries=4) mlist = {}
if plugin != self and plugin.config.has_option('commands', command):
if plugin.config and plugin != self and plugin.config.has_option('commands', command):
def registerCommand(self, plugin, command, level, handler, alias=None, secretLevel=None): if not handler: self.error('Command "%s" registration failed, no handler' % command) return False
def OnSay(self, action, data, match=None): msg = string.split(data, ': ', 1) if not len(msg) == 2: return None client = self.getByCidOrJoinPlayer(msg[0]) return b3.events.Event(b3.events.EVT_CLIENT_SAY, msg[1], client)
def OnItem(self, action, data, match=None): #Item: 0 pickup_money (5) picked up ($25) #Item: 0 weapon_schofield bought ($18/$20) #Item: 0 weapon_remington58 (7) picked up cid, item = string.split(data, ' ', 1) client = self.getByCidOrJoinPlayer(cid) if client: if 'pickup_money' in item: rePickup_money = re.compile(r"^p...
print 'created : %s' % self def __del__(self): print 'destroyed : %s' % self
def __init__(self, **kwargs): self._pluginData = {} self.state = b3.STATE_UNKNOWN self._data = {}
if words and len(words) == 1: return b3.cvar.Cvar(cvarName, value=words[0])
if words: if len(words) == 0: return b3.cvar.Cvar(cvarName, value=None) else: return b3.cvar.Cvar(cvarName, value=words[0])
def getCvar(self, cvarName): if cvarName not in self._gameServerVars: self.warning('unknown cvar \'%s\'' % cvarName) return None try: words = self.write(('vars.%s' % cvarName,)) except Bfbc2CommandFailedError, err: self.error(err) return self.debug('Get cvar %s = %s', cvarName, words) if words and len(words) == 1: re...
if int(version[1]) < BUILD_NUMBER_R9:
if int(version[1]) < BUILD_NUMBER_R9_PRERELEASE2:
def startup(self): # add specific events self.Events.createEvent('EVT_CLIENT_SQUAD_CHANGE', 'Client Squad Change') self.Events.createEvent('EVT_PUNKBUSTER_SCHEDULED_TASK', 'PunkBuster scheduled task') self.Events.createEvent('EVT_PUNKBUSTER_LOST_PLAYER', 'PunkBuster client connection lost') # create the 'Server' clie...
client.squad = data[2]
client.squad = int(data[2])
def OnPlayerTeamchange(self, action, data): """ player.onTeamChange <soldier name: player name> <team: Team ID> <squad: Squad ID> Effect: Player might have changed team """ client = self.getClient(data[0]) if client: client.team = self.getTeam(data[1]) # .team setter will send team change event client.squad = data[2]
if self.changeMap_targetLevel is not None: if self.game.mapName != self.changeMap_targetLevel: self.debug("try one more time to change to map %s" % self.changeMap_targetLevel) self.changeMap_targetLevel = None self.write(('admin.runNextLevel', )) return else: self.debug("succesfully change to map %s" % self.changeMa...
self.game.startRound() return b3.events.Event(b3.events.EVT_GAME_ROUND_START, self.game)
def OnServerLevelstarted(self, action, data): """When the level finished loading and started""" if self.changeMap_targetLevel is not None: if self.game.mapName != self.changeMap_targetLevel: # doh! the server just switched map sides instead of changing map !!! DICE please do something :) # try again self.debug("try one...
return self.getEasyName(levelnames[int(nextLevelIndex) % len(levelnames)])
if levelnames[nextLevelIndex] == self.getMap(): nextLevelIndex = (nextLevelIndex+1)%len(levelnames) return nextLevelIndex
def getNextMap(self): """Return the name of the next map """ [nextLevelIndex] = self.write(('mapList.nextLevelIndex',)) levelnames = self.write(('mapList.list',)) return self.getEasyName(levelnames[int(nextLevelIndex) % len(levelnames)])
return 'Arica Harbor'
return 'Africa Harbor'
def getEasyName(self, mapname): """ Change levelname to real name """ if mapname.startswith('Levels/MP_001'): return 'Panama Canal' elif mapname.startswith('Levels/MP_002'): return 'Valparaiso'
"""Load the next level. If the current game mod plays each level twice
"""Load the next map (not level). If the current game mod plays each level twice
def rotateMap(self): """Load the next level. If the current game mod plays each level twice to get teams the chance to play both sides, then this rotate a second time to really switch to the next level""" [nextLevelIndex] = self.write(('mapList.nextLevelIndex',)) levelnames = self.write(('mapList.list',)) self.changeMa...
time to really switch to the next level""" [nextLevelIndex] = self.write(('mapList.nextLevelIndex',)) levelnames = self.write(('mapList.list',)) self.changeMap_targetLevel = levelnames[int(nextLevelIndex) % len(levelnames)] self.write(('admin.runNextLevel',))
time to really switch to the next map""" nextIndex = self.getNextMapIndex() if nextIndex == -1: self.write(('admin.runNextLevel',)) else: self.write(('mapList.nextLevelIndex', nextIndex)) self.write(('admin.runNextLevel',))
def rotateMap(self): """Load the next level. If the current game mod plays each level twice to get teams the chance to play both sides, then this rotate a second time to really switch to the next level""" [nextLevelIndex] = self.write(('mapList.nextLevelIndex',)) levelnames = self.write(('mapList.list',)) self.changeMa...
"""Change to the given map/level If map is of the form 'Levels/MP_001' and 'Levels/MP_001' is a supported level for the current game mod, then this level is loaded. In other cases, this method assumes it is given a 'easy map name' (like 'Port Valdez') and it will do its best to find the level name that seems to be fo...
"""Change to the given map 1) determine the level name If map is of the form 'Levels/MP_001' and 'Levels/MP_001' is a supported level for the current game mod, then this level is loaded. In other cases, this method assumes it is given a 'easy map name' (like 'Port Valdez') and it will do its best to find the level na...
def changeMap(self, map): """Change to the given map/level If map is of the form 'Levels/MP_001' and 'Levels/MP_001' is a supported level for the current game mod, then this level is loaded. In other cases, this method assumes it is given a 'easy map name' (like 'Port Valdez') and it will do its best to find the leve...
self.changeMap_backupMapList = self.write(('mapList.list',)) self.changeMap_restoreMapListOnNextLevel = True self.changeMap_targetLevel = map self.write(('mapList.clear',)) self.write(('mapList.append', map)) self.write(('mapList.save',))
def changeMap(self, map): """Change to the given map/level If map is of the form 'Levels/MP_001' and 'Levels/MP_001' is a supported level for the current game mod, then this level is loaded. In other cases, this method assumes it is given a 'easy map name' (like 'Port Valdez') and it will do its best to find the leve...
self.changeMap_tries = 1
self.write(('mapList.nextLevelIndex', nextIndex))
def changeMap(self, map): """Change to the given map/level If map is of the form 'Levels/MP_001' and 'Levels/MP_001' is a supported level for the current game mod, then this level is loaded. In other cases, this method assumes it is given a 'easy map name' (like 'Port Valdez') and it will do its best to find the leve...
def restoreMapList(self, list): self.write(('mapList.clear',)) for l in list: self.write(('mapList.append', l)) self.write(('mapList.save',))
def restoreMapList(self, list): self.write(('mapList.clear',)) for l in list: self.write(('mapList.append', l)) self.write(('mapList.save',))
if mapname == 'Levels/MP_001': return ('Panama Canal')
if mapname.startswith('Levels/MP_001'): return 'Panama Canal'
def getEasyName(self, mapname): """ Change levelname to real name """ if mapname == 'Levels/MP_001': return ('Panama Canal') elif mapname == 'Levels/MP_002': return ('Valparaiso')
elif mapname == 'Levels/MP_002': return ('Valparaiso') elif mapname == 'Levels/MP_003': return ('Laguna Alta') elif mapname == 'Levels/MP_004': return ('Isla Inocentes') elif mapname == 'Levels/MP_005': return ('Atacama Desert') elif mapname == 'Levels/MP_006': return ('Arica Harbor') elif mapname == 'Levels/MP_00...
elif mapname.startswith('Levels/MP_002'): return 'Valparaiso' elif mapname.startswith('Levels/MP_003'): return 'Laguna Alta' elif mapname.startswith('Levels/MP_004'): return 'Isla Inocentes' elif mapname.startswith('Levels/MP_005'): return 'Atacama Desert' elif mapname.startswith('Levels/MP_006'): return 'Arica Har...
def getEasyName(self, mapname): """ Change levelname to real name """ if mapname == 'Levels/MP_001': return ('Panama Canal') elif mapname == 'Levels/MP_002': return ('Valparaiso')
for index in range(0,len(data)): mapList[index] = self.getEasyName(data[index]) return mapList
for map in data: mapList.append(self.getEasyName(map)) return mapList
def getMaps(self): """Return the map list TODO""" data = self.write(('mapList.list',)) mapList = [] for index in range(0,len(data)): mapList[index] = self.getEasyName(data[index]) return mapList
self.PunkBuster = PunkBuster(self)
self.debug('punkbuster enabled in config') self.PunkBuster = Bfbc2PunkBuster(self)
def startup(self): # add specific events self.Events.createEvent('EVT_PUNKBUSTER_SCHEDULED_TASK', 'PunkBuster scheduled task') self.Events.createEvent('EVT_PUNKBUSTER_LOST_PLAYER', 'PunkBuster client connection lost') if self.config.has_option('server', 'punkbuster') and self.config.getboolean('server', 'punkbuster')...
if self.PunkBuster: self.PunkBuster.send('pb_sv_list')
def startup(self): # add specific events self.Events.createEvent('EVT_PUNKBUSTER_SCHEDULED_TASK', 'PunkBuster scheduled task') self.Events.createEvent('EVT_PUNKBUSTER_LOST_PLAYER', 'PunkBuster client connection lost') if self.config.has_option('server', 'punkbuster') and self.config.getboolean('server', 'punkbuster')...
client = client = self.storage.getClientsMatching( {'pbid': match.group('pbuid')} )
matchingClients = self.storage.getClientsMatching( {'pbid': match.group('pbuid')} ) if matchingClients and len(matchingClients) == 0: client = matchingClients[0]
def OnPBLostConnection(self, match, data): """PB notifies us it lost track of a player. This is the only change we have to save the ip of clients. This event is triggered after the OnPlayerLeave, so normaly the client is not connected. Anyway our task here is to save data into db not to connect/disconnect the client ""...
self.debug('PlayerInfoBlock: %s' % pib)
if len(pib) == 0: self.debug('no such client found') return None
def getClient(self, cid): """Get a connected client from storage or create it B3 CID <--> BFBC2 character name B3 GUID <--> BFBC2 EA_guid """ # try to get the client from the storage of already authed clients client = self.clients.getByCID(cid) if not client: if cid == 'Server': return self.clients.newClient('Serve...
messagequeue = None messagehandler = None
def length(self): if self.value == None: return 0
self.messagequeue = Queue.Queue() self.messagehandler = threading.Thread(target=self.messagequeueworker) self.messagehandler.setDaemon(True) self.messagehandler.start()
def __init__(self, **kwargs): self._pluginData = {} self.state = b3.STATE_UNKNOWN self._data = {} self.messagequeue = Queue.Queue() self.messagehandler = threading.Thread(target=self.messagequeueworker) self.messagehandler.setDaemon(True) self.messagehandler.start()
def messagequeueworker(self): while True: msg = self.messagequeue.get() for line in self.console.getWrap(msg, self.console._settings['line_length'], self.console._settings['min_wrap_length']): self.console.message(self, line) time.sleep(self.console._settings['message_delay']) self.messagequeue.task_done()
def messagequeueworker(self): while True: msg = self.messagequeue.get() for line in self.console.getWrap(msg, self.console._settings['line_length'], self.console._settings['min_wrap_length']): self.console.message(self, line) time.sleep(self.console._settings['message_delay']) self.messagequeue.task_done()
self.messagequeue.put(msg)
self.console.message(self, msg)
def message(self, msg): self.messagequeue.put(msg)
if self.getB3Path() != "":
elif self.getB3Path() != "":
def __init__(self, config=None): if config: self._config = config if self.getB3Path() != "": self._config = self.getB3Path() + "\\conf\\b3.xml" print self._config self.introduction() self.clearscreen() self._outputFile = self.raw_default("Location and name of the configfile", self._config) #Creating Backup self.backupF...
admin.message('^3Unbaned^7: %s^7: %s' % (client.exactName, result))
admin.message('^3Unbanned^7: %s^7: %s' % (client.exactName, result))
def unban(self, client, reason='', admin=None, silent=False, *kwargs): if self.PunkBuster: if client.pbid: result = self.PunkBuster.unBanGUID(client)
admin.message('%s^7 un-banned but has no punkbuster id' % client.exactName)
admin.message('%s^7 unbanned but has no punkbuster id' % client.exactName)
def unban(self, client, reason='', admin=None, silent=False, *kwargs): if self.PunkBuster: if client.pbid: result = self.PunkBuster.unBanGUID(client)
admin.message('^3Unbaned^7: %s^7. You may need to manually remove the user from the game\'s ban file.' % client.exactName)
admin.message('^3Unbanned^7: %s^7. You may need to manually remove the user from the game\'s ban file.' % client.exactName)
def unban(self, client, reason='', admin=None, silent=False, *kwargs): if self.PunkBuster: if client.pbid: result = self.PunkBuster.unBanGUID(client)
if cid == 0 and (not client or client.name != name):
if not client or client.name != name:
def OnSay(self, action, data, match=None): #3:53 say: 8 denzel: lol if match is None: return name = self.stripColors(match.group('name')) cid = int(match.group('cid')) client = self.getByCidOrJoinPlayer(match.group('cid'))
if cid == 0 and (not client or client.name != name):
if not client or client.name != name:
def OnSayteam(self, action, data, match=None): #2:28 sayteam: 12 New_UrT_Player_v4.1: wokele if match is None: return name = self.stripColors(match.group('name')) cid = int(match.group('cid')) client = self.getByCidOrJoinPlayer(match.group('cid'))
if cid == 0 and (not client or client.name != name):
if not client or client.name != name:
def OnSaytell(self, action, data, match=None): #5:39 saytell: 15 16 repelSteeltje: nno #5:39 saytell: 15 15 repelSteeltje: nno
def getWrap(self, text, length=100, minWrapLen=100):
def getWrap(self, text, length=SAY_LINE_MAX_LENGTH, minWrapLen=SAY_LINE_MAX_LENGTH):
def getWrap(self, text, length=100, minWrapLen=100): """Returns a sequence of lines for text that fits within the limits """ if not text: return [] maxLength = int(length) if len(text) <= maxLength: return [text] else: lines = [text[:maxLength]] remaining = text[maxLength:] while len(remaining) > 0: lines.append(rema...
self._xlrstatstables = [self.playerstats_table, self.weaponstats_table, self.weaponusage_table, self.bodyparts_table, self.playerbody_table, self.opponents_table, self.mapstats_table, self.playermaps_table, self.actionstats_table, self.playeractions_table]
def startup(self):
display: none; }
def getHtml(self): cssstyle = """ #b3commands { border-collapse: collapse; } #b3commands th, #b3commands td { font-family: arial; border: 2px solid black; padding: 5px; } #b3commands th { font-weight: bold; background-color: lightgray; text-transform: capitalize; } #b3commands td { font-size: 12px; }
background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAACWCAIAAAB7I84mAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAINJREFUeNrEklEOwBAQRGcb56iPnsGRe6Gex0qJSHZbBGlSP5PHzBDQdR4AyDkXxRDS2CDFgOi1tjoZKQv05LRllZCJvujU53zQYuBfSzl1O6dvcMKiqqctheqv0gmMxMdJVzed5etTj2TZQKDVUtu2Vh1CEMLeJ%2FFZmFnQbm2UW4ABAG%2FHF...
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAACWCAYAAAAfduJyAAAAAXNSR0IArs4c6QAAAAZiS0dEAIcAiACHZn+LRgAAAAlwSFlzAAALEgAACxIB0t1+/AAAAAd0SU1FB9oCGRQCLt1vun0AAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAqklEQVQoz3WSwRXDMAhDv7RKZ8jIXagL0QMxNo5zgycBQsDv+wmu6woLMBKWhIEWUYBGypJyKBOWRirAgbDFjd7TRo...
def getHtml(self): cssstyle = """ #b3commands { border-collapse: collapse; } #b3commands th, #b3commands td { font-family: arial; border: 2px solid black; padding: 5px; } #b3commands th { font-weight: bold; background-color: lightgray; text-transform: capitalize; } #b3commands td { font-size: 12px; }
background: url("data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%03%B6%00%00%00%96%08%06%00%00%00%EA%BE%143%00%00%00%04sBIT%08%08%08%08%7C%08d%88%00%00%00%09pHYs%00%00%0B%12%00%00%0B%12%01%D2%DD~%FC%00%00%00%18tEXtSoftware%00Adobe%20FireworksO%B3%1FN%00%00%04%11tEXtXML%3Acom.adobe.xmp%00%3C%3Fxpacket%20begin%3D...
def getHtml(self): cssstyle = """ #b3commands { border-collapse: collapse; } #b3commands th, #b3commands td { font-family: arial; border: 2px solid black; padding: 5px; } #b3commands th { font-weight: bold; background-color: lightgray; text-transform: capitalize; } #b3commands td { font-size: 12px; }
background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAAZCAIAAACUxWgrAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADlJREFUeNpi/P//PwMDAxMDGLC8fv4cRDEyMoIoBgjFiJViAulhYULhESHHhKoSG4ViLdRlUAogwADulwZZy1%2BP%2BAAAAABJRU5ErkJggg%3D%3D") repeat-x scroll 0 0
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAAZCAIAAACUxWgrAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADlJREFUeNpi/P//PwMDAxMDGLC8fv4cRDEyMoIoBgjFiJViAulhYULhESHHhKoSG4ViLdRlUAogwADulwZZy1%2BP%2BAAAAABJRU5ErkJggg%3D%3D) repeat-x scroll 0 0
def getHtml(self): cssstyle = """ #b3commands { border-collapse: collapse; } #b3commands th, #b3commands td { font-family: arial; border: 2px solid black; padding: 5px; } #b3commands th { font-weight: bold; background-color: lightgray; text-transform: capitalize; } #b3commands td { font-size: 12px; }
//]]>
def getHtml(self): cssstyle = """ #b3commands { border-collapse: collapse; } #b3commands th, #b3commands td { font-family: arial; border: 2px solid black; padding: 5px; } #b3commands th { font-weight: bold; background-color: lightgray; text-transform: capitalize; } #b3commands td { font-size: 12px; }
<a title="go to BigBrotherBot website" href="http://www.bigbrotherbot.com/forums/index.php"></a>
<a title="go to BigBrotherBot website" href="http://www.bigbrotherbot.com/forums/index.php"> <img src='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEARwBHAAD/2wBDAAcFBQYFBAcGBQYIBwcIChELCgkJChUPEAwRGBUaGRgVGBcbHichGx0lHRcYIi4iJSgpKywrGiAvMy8qMicqKyr/2wBDAQcICAoJChQLCxQqHBgcKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKi...
def getHtml(self): cssstyle = """ #b3commands { border-collapse: collapse; } #b3commands th, #b3commands td { font-family: arial; border: 2px solid black; padding: 5px; } #b3commands th { font-weight: bold; background-color: lightgray; text-transform: capitalize; } #b3commands td { font-size: 12px; }
<tr><th>plugin</th><th>min level</th><th>max level</th><th>command</th><th>alias</th><th>description</th></tr>
<tr> <th class="b3Plugin">plugin</th> <th class="b3MinLevel">min level</th> <th class="b3MaxLevel">max level</th> <th class="b3Name">command</th> <th class="b3Alias">alias</th> <th class="b3Desc">description</th> </tr>
def getHtmlTable(self): text = """ <table id="b3commands"> <thead> <tr><th>plugin</th><th>min level</th><th>max level</th><th>command</th><th>alias</th><th>description</th></tr> </thead> <tbody> %(commandsTablerow)s </tbody> </table> """ def friendlyLevel(level): try: intlevel = int(level) if intlevel <= 0: return '<s...
alphabet1 = range(ord(u'а'), ord(u'я')) alphabet2 = range(ord(u'А'), ord(u'Я')) uni = False for i in text: letter = ord(i) if letter in alphabet1 or letter in alphabet2: uni = True return uni
try: text.encode(CHARSET) return True except UnicodeEncodeError: return False
def isunicode(text): # FIXME: rewrite this stupid hack to support other languages alphabet1 = range(ord(u'а'), ord(u'я')) alphabet2 = range(ord(u'А'), ord(u'Я')) uni = False for i in text: letter = ord(i) if letter in alphabet1 or letter in alphabet2: uni = True return uni
try: id3 = mutagen.id3.ID3(tmp_filename) tags = id3.pprint() del id3
converted = False while not converted: try: id3 = mutagen.id3.ID3(tmp_filename) tags = id3.pprint() del id3
def do_GET(self): if self.path.find('?') != -1: path = self.path.split('?',1)[0] else: path = self.path if path[0] == '/': path = path[1:] # TODO: process 404 and other errors
if not isunicode(tags): os.system("mid3iconv -q -e%s --remove-v1 '%s'" % (CHARSET, tmp_filename)) except Exception as text: print(text)
if not isunicode(tags): os.system("mid3iconv -q -e%s --remove-v1 '%s'" % (CHARSET, tmp_filename)) converted = True except EOFError: buf = f.read(BUFSIZE) tmp = open(tmp_filename, "ab") tmp.write(buf) tmp.close() except Exception as text: converted = True print(text)
def do_GET(self): if self.path.find('?') != -1: path = self.path.split('?',1)[0] else: path = self.path if path[0] == '/': path = path[1:] # TODO: process 404 and other errors
buf = tmp.read(BUFSIZE)
buf = tmp.read()
def do_GET(self): if self.path.find('?') != -1: path = self.path.split('?',1)[0] else: path = self.path if path[0] == '/': path = path[1:] # TODO: process 404 and other errors
shit = list(re.search(r"& for i in range(len(shit)): shit[i] = int(shit[i]) - 48
def anti_obusfaction(text): shit = list(re.search(r"&#([0-9]{2}?);", text).groups()) for i in range(len(shit)): shit[i] = int(shit[i]) - 48 # replacing "&#[two digits number];" with "[number - 48]" out = "" i = 0 while i < len(text): if i + 3 < len(text) and text[i] == "&" and text[i+1] == "#": for j in str(shit.pop(0...
if i + 3 < len(text) and text[i] == "&" and text[i+1] == " for j in str(shit.pop(0)): out += j
if i + 3 < len(text) and text[i:i+2] == "& number = int(text[i+2:i+4]) - 48 out += str(number)
def anti_obusfaction(text): shit = list(re.search(r"&#([0-9]{2}?);", text).groups()) for i in range(len(shit)): shit[i] = int(shit[i]) - 48 # replacing "&#[two digits number];" with "[number - 48]" out = "" i = 0 while i < len(text): if i + 3 < len(text) and text[i] == "&" and text[i+1] == "#": for j in str(shit.pop(0...
print(anti_obusfaction(get_page()))
print(anti_obusfaction(request_text()))
def anti_obusfaction(text): shit = list(re.search(r"&#([0-9]{2}?);", text).groups()) for i in range(len(shit)): shit[i] = int(shit[i]) - 48 # replacing "&#[two digits number];" with "[number - 48]" out = "" i = 0 while i < len(text): if i + 3 < len(text) and text[i] == "&" and text[i+1] == "#": for j in str(shit.pop(0...
self.wfile.write(tmp.read(BUFSIZE))
buf = tmp.read(BUFSIZE) self.wfile.write(buf)
def do_GET(self): if self.path.find('?') != -1: path = self.path.split('?',1)[0] else: path = self.path if path[0] == '/': path = path[1:] print(path)
while True: self.wfile.write(f.read(BUFSIZE))
while len(buf) > 0: buf = f.read(BUFSIZE) self.wfile.write(buf)
def do_GET(self): if self.path.find('?') != -1: path = self.path.split('?',1)[0] else: path = self.path if path[0] == '/': path = path[1:] print(path)
server = http.server.HTTPServer((HOST, PORT), ServerHandler) try: server.serve_forever() except Exception as text: print(text)
while True: try: server = http.server.HTTPServer((HOST, PORT), ServerHandler) server.serve_forever() except Exception as text: server.close() print(text)
def daemonize(): #os.chdir("/") #os.umask(0) #os.setsid() pid = os.fork() if pid > 0: sys.exit(0) # exit second parent #sys.stdin.close() #sys.stdout.close() #sys.stderr.close() log = open(LOG, "a+") ##os.dup2(log.fileno(), sys.stdin.fileno()) os.dup2(log.fileno(), sys.stdout.fileno()) os.dup2(log.fileno(), sys.stder...
time.sleep(1./float(MAXSPEED/BUFSIZE))
pause = 1./float(MAXSPEED/BUFSIZE) - (end - start) time.sleep(pause)
def do_GET(self): if self.path.find('?') != -1: path = self.path.split('?',1)[0] else: path = self.path if path[0] == '/': path = path[1:]
page = page.decode("cp1251").split("\n") return page[page.index("<LI class=\"first\">Сейчас: <b>") + 1]
lines = page.decode("cp1251").split("\n") return lines[lines.index("<LI class=\"first\">Сейчас: <b>") + 1]
def request_text(): page = urllib.request.urlopen("http://www.novgorod.ru/temperature/").read() page = page.decode("cp1251").split("\n") return page[page.index("<LI class=\"first\">Сейчас: <b>") + 1]
buf = tmp.read()
buf = tmp.read(BUFSIZE)
def do_GET(self): if self.path.find('?') != -1: path = self.path.split('?',1)[0] else: path = self.path if path[0] == '/': path = path[1:] # TODO: process 404 and other errors
return ( name == 'embedded_data' or name == 'embedded_data_byte' )
return ( name == 'embedded_data' or name == 'embedded_data_byte' or name == 'VendorUnique')
def isEmbedded(self, name): return ( name == 'embedded_data' or name == 'embedded_data_byte' )
searchstr = "=" + str(self.saved_ubyte)
searchstr = "=" + str(self.saved_value)
def Tag_attr_ubyte(self): new_tag = unpack('B', self.data[self.index])[0]
if ( self.unpack_string == 'B' and size == 1 ): self.saved_ubyte = self.unpack(self.unpack_string, self.data[self.index:self.index+size])[0]
if (( self.unpack_string == 'B' and size == 1 ) or \ ( self.unpack_string == 'I' and size == 4 )): self.saved_value = self.unpack(self.unpack_string, self.data[self.index:self.index+size])[0]
def singleValueType(self): if ( self.Tag_ubyte() or self.Tag_uint16() or self.Tag_uint32() or \ self.Tag_sint16() or self.Tag_sint32() or self.Tag_real32() ): size = self.size_of_element if ( self.unpack_string == 'f' ): print "%f" % self.unpack(self.unpack_string, self.data[self.index:self.index+size]), else: print "%...
Read in a header in some CBF format from a string representing the binary stuff
Read in a header in some CBF format from a string representing binary stuff
def _readheader(self, inStream): """ Read in a header in some CBF format from a string representing the binary stuff @param inStream: the binary image (without any CIF decorators) @type inStream: python string. """ sep = "\r\n" iSepPos = inStream.find(sep) if iSepPos < 0 or iSepPos > 80: sep = "\n" #switch back to unix...
Analyze a stream of char with any length of exception (2,4, or 8 bytes integers)
Analyze a stream of char with any length of exception: 2, 4, or 8 bytes integers
def analyse(stream): """ Analyze a stream of char with any length of exception (2,4, or 8 bytes integers)
This is the CIF class, it represents the CIF dictionnary as a a python dictionnary thus inherits from the dict built in class.
This is the CIF class, it represents the CIF dictionary; and as a a python dictionary thus inherits from the dict built in class.
def read(self, fname): """ Read in header into self.header and the data into self.data """ self.filename = fname self.header = {} self.resetvals() self.cif.loadCIF(fname, _bKeepComment=True)
self._parseCIF(open(_strFilename, "r").read())
self._parseCIF(open(_strFilename, "rb").read())
def loadCIF(self, _strFilename, _bKeepComment=False): """Load the CIF file and returns the CIF dictionnary into the object @param _strFilename: the name of the file to open @type _strFilename: string @param _strFilename: the name of the file to open @type _strFilename: string @return the """ if not os.path.isfile(_st...
lLinesRead = open(_strFilename, "r").readlines()
lLinesRead = open(_strFilename, "rb").readlines()
def _readCIF(_strFilename): """ -Check if the filename containing the CIF data exists -read the cif file -removes the comments @param _strFilename: the name of the CIF file @type _strFilename: string @return: a string containing the raw data @rtype: string """ if not os.path.isfile(_strFilename): print "I cannot find ...
sText += sLine[:iPos] + "\n"
sText += sLine[:iPos] + os.linesep
def _readCIF(_strFilename): """ -Check if the filename containing the CIF data exists -read the cif file -removes the comments @param _strFilename: the name of the CIF file @type _strFilename: string @return: a string containing the raw data @rtype: string """ if not os.path.isfile(_strFilename): print "I cannot find ...
print "Warning, this line is too long and could cause problems in PreQuest\n", sLine
print("Warning, this line is too long and could cause problems in PreQuest", os.linesep, sLine)
def _readCIF(_strFilename): """ -Check if the filename containing the CIF data exists -read the cif file -removes the comments @param _strFilename: the name of the CIF file @type _strFilename: string @return: a string containing the raw data @rtype: string """ if not os.path.isfile(_strFilename): print "I cannot find ...
print "Warning, this line is too long and could cause problems in PreQuest\n", sLine
print("Warning, this line is too long and could cause problems in PreQues", os.linesep, sLine)
def _readCIF(_strFilename): """ -Check if the filename containing the CIF data exists -read the cif file -removes the comments @param _strFilename: the name of the CIF file @type _strFilename: string @return: a string containing the raw data @rtype: string """ if not os.path.isfile(_strFilename): print "I cannot find ...
@return: Nothing, the data are incorporated at the CIF object dictionnary @rtype: dictionnary
@return: Nothing, the data are incorporated at the CIF object dictionary @rtype: dictionary
def _parseCIF(self, sText): """ -Parses the text of a CIF file -Cut it in fields -Find all the loops and process -Find all the keys and values @param sText: the content of the CIF-file @type sText: string @return: Nothing, the data are incorporated at the CIF object dictionnary @rtype: dictionnary """ loopidx = [] loo...
@return: the list of loop dictionnaries, the length of the data extracted from the lFields and the list of all the keys of the loop. @rtype: tupple
@return: the list of loop dictionaries, the length of the data extracted from the lFields and the list of all the keys of the loop. @rtype: tuple
def _analyseOneLoop(lFields, iStart): """Processes one loop in the data extraction of the CIF file @param lFields: list of all the words contained in the cif file @type lFields: list @param iStart: the starting index corresponding to the "loop_" key @type iStart: integer @return: the list of loop dictionnaries, the len...
print "Error during the opening of file for write : %s" % _strFilename
print("Error during the opening of file for write: %s" % _strFilename)
def saveCIF(self, _strFilename="test.cif"): """Transforms the CIF object in string then write it into the given file @param _strFilename: the of the file to be written @type param: string """
print "Error during the closing of file for write : %s" % _strFilename
print("Error during the closing of file for write: %s" % _strFilename)
def saveCIF(self, _strFilename="test.cif"): """Transforms the CIF object in string then write it into the given file @param _strFilename: the of the file to be written @type param: string """
@param _strFilename: the name of the filename to be apppended in the header of the CIF file
@param _strFilename: the name of the filename to be appended in the header of the CIF file
def _cif2str(self, _strFilename): """converts a cif dictionnary to a string according to the CIF syntax @param _strFilename: the name of the filename to be apppended in the header of the CIF file @type _strFilename: string @return : a sting that corresponds to the content of the CIF-file. @rtype: string """ sCifText = ...
sCifText += "data_%s\n" % t
sCifText += "data_%s%s" % (t, os.linesep)
def _cif2str(self, _strFilename): """converts a cif dictionnary to a string according to the CIF syntax @param _strFilename: the name of the filename to be apppended in the header of the CIF file @type _strFilename: string @return : a sting that corresponds to the content of the CIF-file. @rtype: string """ sCifText = ...
sLine = "%s \n;\n %s \n;\n" % (sKey, sValue)
sLine = "%s %s;%s %s %s;%s" % (sKey, os.linesep, os.linesep, sValue, os.linesep, os.linesep)
def _cif2str(self, _strFilename): """converts a cif dictionnary to a string according to the CIF syntax @param _strFilename: the name of the filename to be apppended in the header of the CIF file @type _strFilename: string @return : a sting that corresponds to the content of the CIF-file. @rtype: string """ sCifText = ...
sLine = "%s\n '%s' \n" % (sKey, sValue)
sLine = "%s %s '%s' %s" % (sKey, os.linesep, sValue, os.linesep)
def _cif2str(self, _strFilename): """converts a cif dictionnary to a string according to the CIF syntax @param _strFilename: the name of the filename to be apppended in the header of the CIF file @type _strFilename: string @return : a sting that corresponds to the content of the CIF-file. @rtype: string """ sCifText = ...
sLine = "%s %s \n" % (sKey, sValue)
sLine = "%s %s %s" % (sKey, sValue, os.linesep)
def _cif2str(self, _strFilename): """converts a cif dictionnary to a string according to the CIF syntax @param _strFilename: the name of the filename to be apppended in the header of the CIF file @type _strFilename: string @return : a sting that corresponds to the content of the CIF-file. @rtype: string """ sCifText = ...
sLine = "%s\n %s \n" % (sKey, sValue)
sLine = "%s %s %s %s" % (sKey, os.linesep, sValue, os.linesep)
def _cif2str(self, _strFilename): """converts a cif dictionnary to a string according to the CIF syntax @param _strFilename: the name of the filename to be apppended in the header of the CIF file @type _strFilename: string @return : a sting that corresponds to the content of the CIF-file. @rtype: string """ sCifText = ...
sCifText += "loop_ \n"
sCifText += "loop_ " + os.linesep
def _cif2str(self, _strFilename): """converts a cif dictionnary to a string according to the CIF syntax @param _strFilename: the name of the filename to be apppended in the header of the CIF file @type _strFilename: string @return : a sting that corresponds to the content of the CIF-file. @rtype: string """ sCifText = ...
sCifText += " %s \n" % sKey
sCifText += " %s %s" % (sKey, os.linesep)
def _cif2str(self, _strFilename): """converts a cif dictionnary to a string according to the CIF syntax @param _strFilename: the name of the filename to be apppended in the header of the CIF file @type _strFilename: string @return : a sting that corresponds to the content of the CIF-file. @rtype: string """ sCifText = ...
sLine += "\n; %s \n;\n" % (sRawValue)
sLine += "%s; %s %s;%s" % (os.linesep, sRawValue, os.linesep, os.linesep)
def _cif2str(self, _strFilename): """converts a cif dictionnary to a string according to the CIF syntax @param _strFilename: the name of the filename to be apppended in the header of the CIF file @type _strFilename: string @return : a sting that corresponds to the content of the CIF-file. @rtype: string """ sCifText = ...
sCifText += sLine + " \n"
sCifText += sLine + " " + os.linesep
def _cif2str(self, _strFilename): """converts a cif dictionnary to a string according to the CIF syntax @param _strFilename: the name of the filename to be apppended in the header of the CIF file @type _strFilename: string @return : a sting that corresponds to the content of the CIF-file. @rtype: string """ sCifText = ...
sCifText += sLine + " \n" sCifText += "\n"
sCifText += sLine + " " + os.linesep sCifText += os.linesep
def _cif2str(self, _strFilename): """converts a cif dictionnary to a string according to the CIF syntax @param _strFilename: the name of the filename to be apppended in the header of the CIF file @type _strFilename: string @return : a sting that corresponds to the content of the CIF-file. @rtype: string """ sCifText = ...
@param cif: CIF dictionnary @return: True if the key exists in the CIF dictionnary and is non empty
@param cif: CIF dictionary @return: True if the key exists in the CIF dictionary and is non empty
def exists(self, sKey): """ Check if the key exists in the CIF and is non empty. @param sKey: CIF key @type sKey: string @param cif: CIF dictionnary @return: True if the key exists in the CIF dictionnary and is non empty @rtype: boolean """ bExists = False if self.has_key(sKey): if len(self[sKey]) >= 1: if self[sKey][0...
Check if the key exists in the CIF dictionnary.
Check if the key exists in the CIF dictionary.
def existsInLoop(self, sKey): """ Check if the key exists in the CIF dictionnary. @param sKey: CIF key @type sKey: string @param cif: CIF dictionnary @return: True if the key exists in the CIF dictionnary and is non empty @rtype: boolean """ if not self.exists("loop_"): return False bExists = False if not bExists: for ...
@param cif: CIF dictionnary @return: True if the key exists in the CIF dictionnary and is non empty
@param cif: CIF dictionary @return: True if the key exists in the CIF dictionary and is non empty
def existsInLoop(self, sKey): """ Check if the key exists in the CIF dictionnary. @param sKey: CIF key @type sKey: string @param cif: CIF dictionnary @return: True if the key exists in the CIF dictionnary and is non empty @rtype: boolean """ if not self.exists("loop_"): return False bExists = False if not bExists: for ...
"""Load the powder diffraction CHIPLOT file and returns the pd_CIF dictionnary in the object
""" Load the powder diffraction CHIPLOT file and returns the pd_CIF dictionary in the object
def loadCHIPLOT(self, _strFilename): """Load the powder diffraction CHIPLOT file and returns the pd_CIF dictionnary in the object @param _strFilename: the name of the file to open @type _strFilename: string @return: the CIF object corresponding to the powder diffraction @rtype: dictionnary """ if not os.path.isfile(_s...
@rtype: dictionnary
@rtype: dictionary
def loadCHIPLOT(self, _strFilename): """Load the powder diffraction CHIPLOT file and returns the pd_CIF dictionnary in the object @param _strFilename: the name of the file to open @type _strFilename: string @return: the CIF object corresponding to the powder diffraction @rtype: dictionnary """ if not os.path.isfile(_s...
print line
def _readheader(self, infile): """ Parser based approach Gets all entries """
if self.header.has_key("Size"): if self.bpp*self.dim1*self.dim2 != int(self.header["Size"]): logging.warning("Size mismatch on reading edf file " + \ fname + " " + self.header["Size"])
def read(self, fname): """ Read in header into self.header and the data into self.data """ self.header = {} self.resetvals() infile = self._open(fname,"rb") self._readheader(infile) # Compute image size try: self.dim1 = int(self.header['Dim_1']) self.dim2 = int(self.header['Dim_2']) except: raise Exception("EDF file"...
logging.warning("Read too many bytes, got "+str(len(block))+\
padded = False nbytesread = len(block) if self.header.has_key("EDF_BinarySize"): if int( self.header["EDF_BinarySize"] ) == nbytesread: padded = True if self.header.has_key("Size"): if int( self.header["Size"] ) == nbytesread: padded = True if padded: block = block[:expected_size] if self.header.has_key("EDF_BlockBound...
def read(self, fname): """ Read in header into self.header and the data into self.data """ self.header = {} self.resetvals() infile = self._open(fname,"rb") self._readheader(infile) # Compute image size try: self.dim1 = int(self.header['Dim_1']) self.dim2 = int(self.header['Dim_2']) except: raise Exception("EDF file"...
self.assertEquals(opens.OrderDirection, "desc")
self.assertEquals(opens.OrderDirection, "asc")
def test_opens(self): min_date = "2010-01-01" self.campaign.stub_request("campaign_opens.json") opens = self.campaign.opens(min_date) self.assertEquals(len(opens.Results), 5) self.assertEquals(opens.Results[0].EmailAddress, "subs+6576576576@example.com") self.assertEquals(opens.Results[0].ListID, "512a3bc577a58fdf689c6...
self.assertEquals(clicks.OrderDirection, "desc")
self.assertEquals(clicks.OrderDirection, "asc")
def test_clicks(self): min_date = "2010-01-01" self.campaign.stub_request("campaign_clicks.json") clicks = self.campaign.clicks(min_date) self.assertEquals(len(clicks.Results), 3) self.assertEquals(clicks.Results[0].EmailAddress, "subs+6576576576@example.com") self.assertEquals(clicks.Results[0].URL, "http://video.goog...
self.assertEquals(unsubscribes.OrderDirection, "desc")
self.assertEquals(unsubscribes.OrderDirection, "asc")
def test_unsubscribes(self): min_date = "2010-01-01" self.campaign.stub_request("campaign_unsubscribes.json") unsubscribes = self.campaign.unsubscribes(min_date) self.assertEquals(len(unsubscribes.Results), 1) self.assertEquals(unsubscribes.Results[0].EmailAddress, "subs+6576576576@example.com") self.assertEquals(unsub...
self.list_id = "98y2e98y289dh89h938389" self.segment = Segment(self.list_id)
self.segment_id = "98y2e98y289dh89h938389" self.segment = Segment(self.segment_id)
def setUp(self): self.list_id = "98y2e98y289dh89h938389" self.segment = Segment(self.list_id)
def getLoadDeps(clsDepsObj): result = set(clsDepsObj.data['require']) ignores = map(attrgetter("name"), clsDepsObj.data['ignore']) optionals = map(attrgetter("name"), clsDepsObj.data['optional']) requires = map(attrgetter("name"), clsDepsObj.data['require']) uses = map(attrgetter("name"), clsDepsObj.data['us...
def dependencies(self, variants):
if self.id == 'qx.xml.Document': pass
def getNodeDeps(node, inFunction=True): ltime = rtime = [] # distinction is in the depsItems that populate this array self._analyzeClassDepsNode(node, ltime, rtime, inFunction, variants, recurse=False) return ltime