rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
elif keys[pygame.K_s]:
if keys[pygame.K_s]:
def get_mx(self): '''Gets movement in the X direction (in [-1,1] for [left,right]).''' if self.js is None: keys = pygame.key.get_pressed() if keys[pygame.K_f]: return 1. elif keys[pygame.K_s]: return -1. else: return .0 else: return self.js.get_axis(0)
else: return .0
return .0
def get_mx(self): '''Gets movement in the X direction (in [-1,1] for [left,right]).''' if self.js is None: keys = pygame.key.get_pressed() if keys[pygame.K_f]: return 1. elif keys[pygame.K_s]: return -1. else: return .0 else: return self.js.get_axis(0)
elif keys[pygame.K_e]:
if keys[pygame.K_e]:
def get_my(self): '''Gets movement in the Y direction (in [-1,1] for [top,bottom]).''' if self.js is None: keys = pygame.key.get_pressed() if keys[pygame.K_d]: return 1. elif keys[pygame.K_e]: return -1. else: return .0 else: return self.js.get_axis(1)
else: return .0
return .0
def get_my(self): '''Gets movement in the Y direction (in [-1,1] for [top,bottom]).''' if self.js is None: keys = pygame.key.get_pressed() if keys[pygame.K_d]: return 1. elif keys[pygame.K_e]: return -1. else: return .0 else: return self.js.get_axis(1)
elif keys[pygame.K_j]:
if keys[pygame.K_j]:
def get_fx(self): '''Gets fire direction in X (in [-1,1] for [left,right]).''' if self.js is None: keys = pygame.key.get_pressed() if keys[pygame.K_l]: return 1. elif keys[pygame.K_j]: return -1. else: return .0 else: return self.js.get_axis(2)
else: return .0
return .0
def get_fx(self): '''Gets fire direction in X (in [-1,1] for [left,right]).''' if self.js is None: keys = pygame.key.get_pressed() if keys[pygame.K_l]: return 1. elif keys[pygame.K_j]: return -1. else: return .0 else: return self.js.get_axis(2)
elif keys[pygame.K_i]:
if keys[pygame.K_i]:
def get_fy(self): '''Gets fire direction in Y (in [-1,1] for [top,bottom]).''' if self.js is None: keys = pygame.key.get_pressed() if keys[pygame.K_k]: return 1. elif keys[pygame.K_i]: return -1. else: return .0 else: return self.js.get_axis(3)
else: return .0
return .0
def get_fy(self): '''Gets fire direction in Y (in [-1,1] for [top,bottom]).''' if self.js is None: keys = pygame.key.get_pressed() if keys[pygame.K_k]: return 1. elif keys[pygame.K_i]: return -1. else: return .0 else: return self.js.get_axis(3)
self.baddies = [] self.bullets = []
while len(self.baddies) > 0: del self.baddies[0] while len(self.bullets) > 0: del self.bullets[0]
def empty(self): self.baddies = [] self.bullets = []
Stats.get_stats().counts['num_bins'] = self.rows * self.cols Stats.get_stats().counts['baddies'] = len(self.baddies) Stats.get_stats().counts['bullets'] = len(self.bullets)
def tick(self): self.bins = [] for i in xrange(self.cols): self.bins.append([]) for j in xrange(self.rows): self.bins[i].append([])
Stats.get_stats().inc("_get_simple_bins_idxs")
def _get_simple_bins_idxs(self, obj): Stats.get_stats().inc("_get_simple_bins_idxs") pos = ( float(obj.pos[0]) / self.size[0] * self.cols, float(obj.pos[1]) / self.size[1] * self.rows ) bin_i = int(pos[0]) bin_j = int(pos[1]) i_pos = pos[0] - bin_i j_pos = pos[1] - bin_j
Stats.get_stats().inc("_get_bins_idxs")
def _get_bins_idxs(self, obj): Stats.get_stats().inc("_get_bins_idxs") pos = ( float(obj.pos[0]) / self.size[0] * self.cols, float(obj.pos[1]) / self.size[1] * self.rows ) bin_i = int(pos[0]) bin_j = int(pos[1]) i_pos = pos[0] - bin_i j_pos = pos[1] - bin_j
self.speed = 2 self.black = (0,0,0)
self.paused = False
def __init__(self, options): assert self.MAIN_OBJECT is None, "Another Main object is being created!"
self.fps = 30
self.fps = options.fps self.min_fps = options.min_fps if self.min_fps > self.fps: self.min_fps = self.fps
def __init__(self, options): assert self.MAIN_OBJECT is None, "Another Main object is being created!"
dw, dh, self.space.baddies),
0, self.height, self.space.baddies),
def __init__(self, options): assert self.MAIN_OBJECT is None, "Another Main object is being created!"
dw, self.height - dh, self.space.baddies),
self.width, 0, self.space.baddies),
def __init__(self, options): assert self.MAIN_OBJECT is None, "Another Main object is being created!"
self.width - dw, dh, self.space.baddies), SpawnPoint(self.screen, self.size, self.width - dw, self.height - dh, self.space.baddies) ] self.score = 0
self.width, self.height, self.space.baddies) ]
def __init__(self, options): assert self.MAIN_OBJECT is None, "Another Main object is being created!"
self.lev_i = 2
self.lev_i = 0
def __init__(self, options): assert self.MAIN_OBJECT is None, "Another Main object is being created!"
if self.fps_timer.get_fps() >= self.fps:
if self.fps_timer.get_fps() >= self.min_fps:
def run(self):
if self.fps_timer.get_fps() < self.fps:
if self.fps_timer.get_fps() < self.min_fps:
def run(self):
if self.player.exploding: if self.player.expl_prog >= 30: for s in self.spawn_points: s.clear() del self.player self.player = Player.spawn_at(self.screen, self.width / 2, self.height / 2) self.space.empty() self.score = 0 self.levels[self.lev_i].start() else: js_dx = self.user_input.get_mx() js_dy = self.user_input.ge...
if not self.paused: self.tick()
def run(self):
self.screen.fill(self.black)
self.screen.fill((0,0,0))
def run(self):
self.screen.blit(self.score_font.render('%d' % self.score,
self.screen.blit(self.score_font.render('%d' % self.player.score,
def run(self):
self.stats.reset()
def run(self):
op.set_defaults(config = '~/.linebattlesrc', input_type = 'none') op.add_option('-C', '--config', help="Use a different config file.") op.add_option('-j', '--input', dest='input_type', type='choice', choices=('none','keyboard','joystick'), help="Force use of the joystick.") op.add_option('-s', '--size', default='800x60...
op.set_defaults(size='800x600', fps=30, min_fps=25) op.add_option('-s', '--size', type='string',
def parse_args(): '''Parses the command line arguments and returns an option object.''' op = optparse.OptionParser() op.set_defaults(config = '~/.linebattlesrc', input_type = 'none') op.add_option('-C', '--config', help="Use a different config file.") op.add_option('-j', '--input', dest='input_type', type='choice', cho...
return self.js.get_axis(3)
return self.js.get_axis(2)
def get_fx(self): '''Gets fire direction in X (in [-1,1] for [left,right]).''' if self.js is None: keys = pygame.key.get_pressed() if keys[pygame.K_l]: return 1. elif keys[pygame.K_j]: return -1. else: return .0 else: return self.js.get_axis(3)
return self.js.get_axis(2)
return self.js.get_axis(3)
def get_fy(self): '''Gets fire direction in Y (in [-1,1] for [top,bottom]).''' if self.js is None: keys = pygame.key.get_pressed() if keys[pygame.K_k]: return 1. elif keys[pygame.K_i]: return -1. else: return .0 else: return self.js.get_axis(2)
size = width,height = 800,600
size = width,height = 480,320
def empty(l): ind = range(len(l)) ind.reverse() for i in ind: del l[i]
winner_pos = gameover_font.size('WINNER') winner_pos = (width - gameover_pos[0]) / 2, \ (height - gameover_pos[1]) / 2
winner_pos = winner_font.size('WINNER') winner_pos = (width - winner_pos[0]) / 2, \ (height - winner_pos[1]) / 2
def run(): pygame.init() screen = pygame.display.set_mode(size) ship = Player.spawn_at(screen, width/2, height/2) speed = 2 black = (0,0,0) fps_timer = pygame.time.Clock() # fonts score_font = pygame.font.SysFont('courier', 25, bold = True) debug_font = pygame.font.SysFont('arial', 8) gameover_font = pygame.font.Sys...
max_ships = 500
max_ships = 100
def run(): pygame.init() screen = pygame.display.set_mode(size) ship = Player.spawn_at(screen, width/2, height/2) speed = 2 black = (0,0,0) fps_timer = pygame.time.Clock() # fonts score_font = pygame.font.SysFont('courier', 25, bold = True) debug_font = pygame.font.SysFont('arial', 8) gameover_font = pygame.font.Sys...
if isinstance(that, Ship):
if isinstance(that, Ship) or isinstance(that, Upgrade):
def collides(self, that): if isinstance(that, Ship): return self._build_rect().colliderect(that._build_rect()) elif isinstance(that, Bullet): # Bullets vary greatly in how their collision detection # is meant to work. return that.collides(self) else: print 'Warning! Ship-%d collision detection??' % type(that) return Fa...
[ [ 0, -1], [ 2, -1], [ 0, -2], [-2, -1], [-2, 1], [ 0, 2], [ 2, 1], [ 0, 1] ],
( ( 0, -1), ( 2, -1), ( 0, -2), (-2, -1), (-2, 1), ( 0, 2), ( 2, 1), ( 0, 1) ),
def __init__(self, screen): Ship.__init__(self, screen, (200, 200, 255), [ [ 0, -1], [ 2, -1], [ 0, -2], [-2, -1], [-2, 1], [ 0, 2], [ 2, 1], [ 0, 1] ], size = 5) self.screen = screen self.reset()
print 'Warning: Baddie.tick() called'
assert False, "Can't make instances of this class."
def tick(self): '''Perform one frame of action.''' print 'Warning: Baddie.tick() called'
for i in xrange(-self.power, self.power + 1, 4): bullets.append(Bullet(self.screen, pos, traj + i / 100., self.side))
for i in xrange(-self.power, self.power + 1, 2): bullets.append(Bullet(self.screen, pos, traj + i / 50., self.side))
def fire(self, pos, traj): bullets = [] for i in xrange(-self.power, self.power + 1, 4): bullets.append(Bullet(self.screen, pos, traj + i / 100., self.side)) return bullets
if isinstance(baddie, Baddie):
if isinstance(baddie, Baddie) or isinstance(baddie, Upgrade):
def tick(self): self.bins = [] for i in xrange(self.cols): self.bins.append([]) for j in xrange(self.rows): self.bins[i].append([])
self.player.explode() break
if isinstance(b, Baddie) or isinstance(b, Bullet): self.player.explode() break elif isinstance(b, Upgrade): b.apply(self.player) self._remove_baddie(b) else: assert False, "Unrecognized type: %s" % str(type(b))
def tick(self): self.bins = [] for i in xrange(self.cols): self.bins.append([]) for j in xrange(self.rows): self.bins[i].append([])
if self.bins[i][j][b2].collides(self.bullets[b1]):
if not isinstance(self.bins[i][j][b2], Upgrade) and \ self.bins[i][j][b2].collides(self.bullets[b1]): if isinstance(self.bins[i][j][b2], Baddie): for u in self.bins[i][j][b2].upgrade(): self.baddies.append(u)
def tick(self): self.bins = [] for i in xrange(self.cols): self.bins.append([]) for j in xrange(self.rows): self.bins[i].append([])
if self.levels[self.lev_i].paused: if self.fps_timer.get_fps() >= self.min_fps: self.levels[self.lev_i].resume() else: if self.fps_timer.get_fps() < self.min_fps: self.levels[self.lev_i].pause()
if self.lev_i < len(self.levels): if self.levels[self.lev_i].paused: if self.fps_timer.get_fps() >= self.min_fps: self.levels[self.lev_i].resume() else: if self.fps_timer.get_fps() < self.min_fps: self.levels[self.lev_i].pause()
def run(self):
response.headers['Content-Type'] = 'application/json; charset=utf-8'
def info(self): """ To get (in JSON) the information about the available formats and CO. """ cmd = ['java', '-cp', self.jarPath, 'org.mapfish.print.ShellMapPrinter', '--config=' + self.configPath, '--clientConfig', '--verbose='+_getJavaLogLevel()] self._addCommonJavaParams(cmd) exe = Popen(cmd, stdout = PIPE, stderr = ...
fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
def command(self): """Main command to create a mapfish controller""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
if not config.has_section(name):
sectionName = self.args[0] if not config.has_section(sectionName):
def command(self): """Main command to create a mapfish controller""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
'There is no layer named %s in layers.ini' % name)
'There is no layer section named %s in layers.ini' % \ sectionName)
def command(self): """Main command to create a mapfish controller""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
singularName = config.get(name, 'singular') pluralName = config.get(name, 'plural') epsg = config.get(name, 'epsg')
singular = config.get(sectionName, 'singular') plural = config.get(sectionName, 'plural') epsg = config.get(sectionName, 'epsg') fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: singularName, singularDirectory = \ fileOp.parse_path_name_args(singular) pluralName, pluralDirectory =...
def command(self): """Main command to create a mapfish controller""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
if basePkg.lower() == name.lower():
if basePkg.lower() == pluralName.lower():
def command(self): """Main command to create a mapfish controller""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
name = name.replace('-', '_')
name = pluralName.replace('-', '_')
def command(self): """Main command to create a mapfish controller""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
fullName = os.path.join(directory, name)
fullName = os.path.join(pluralDirectory, name)
def command(self): """Main command to create a mapfish controller""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
fullModName = os.path.join(directory, name)
fullModName = os.path.join(pluralDirectory, name)
def command(self): """Main command to create a mapfish controller""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
modelTabObj = name + '_table'
def command(self): """Main command to create a mapfish controller""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
'modelTabObj': modelTabObj, 'basePkg': basePkg, 'epsg': epsg})
'basePkg': basePkg})
def command(self): """Main command to create a mapfish controller""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
dest=os.path.join('controllers', directory),
dest=os.path.join('controllers', pluralDirectory),
def command(self): """Main command to create a mapfish controller""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
command = 'map.resource("%s", "%s")\n' % \ (singularName, pluralName) resource_command += command
resource_command += 'map.resource("%s", "%s")\n' % \ (singularName, pluralName)
def command(self): """Main command to create a mapfish controller""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
def command(self): """Main command to create mapfish model""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
if not config.has_section(name):
sectionName = self.args[0] if not config.has_section(sectionName):
def command(self): """Main command to create mapfish model""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
'There is no layer named %s in layers.ini' % name)
'There is no layer section named %s in layers.ini' % \ sectionName)
def command(self): """Main command to create mapfish model""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
singularName = config.get(name, 'singular') table = config.get(name, 'table') epsg = config.get(name, 'epsg') geomColName = config.get(name, 'geomcolumn') if config.has_option(name, 'schema'): schema = config.get(name, 'schema')
singular = config.get(sectionName, 'singular') plural = config.get(sectionName, 'plural') table = config.get(sectionName, 'table') epsg = config.get(sectionName, 'epsg') geomColName = config.get(sectionName, 'geomcolumn') if config.has_option(sectionName, 'schema'): schema = config.get(sectionName, 'schema')
def command(self): """Main command to create mapfish model""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
basePkg = fileOp.find_dir('controllers', True)[0] if basePkg.lower() == name.lower():
basePkg = fileOp.find_dir('model', True)[0] if basePkg.lower() == pluralName.lower():
def command(self): """Main command to create mapfish model""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
'Your controller name should not be the same as '
'Your model name should not be the same as '
def command(self): """Main command to create mapfish model""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
name = name.replace('-', '_')
name = pluralName.replace('-', '_')
def command(self): """Main command to create mapfish model""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
dest=os.path.join('model', directory),
dest=os.path.join('model', pluralDirectory),
def command(self): """Main command to create mapfish model""" try: fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: name, directory = fileOp.parse_path_name_args(self.args[0]) except: raise BadCommand('No egg_info directory was found')
print 'Reading "%s", writing "%s".' % (sys.argv[1], sys.argv[2]) if os.path.isfile(read) and not os.path.isfile(write):
write = "".join(write.split(".")[:-1]) if "." in write else write print 'Reading "%s", writing "%s-*.csv".' % (read, write) if os.path.isfile(read) and not os.path.isfile(write + "-1.csv"):
def getargs(): """ get database file to read and csv file to write from commandline """ try: read = sys.argv[1] write = sys.argv[2] print 'Reading "%s", writing "%s".' % (sys.argv[1], sys.argv[2]) if os.path.isfile(read) and not os.path.isfile(write): r = sqlite3.connect(read) count = r.execute("select count() from tic...
elif count > 400: print "Sorry, %s tickets and Pivotal won't import more than 400..." % count sys.exit(42) w = open(write, "wb") return (r, w)
else: print "Converting %s tickets..." % count return (r, write)
def getargs(): """ get database file to read and csv file to write from commandline """ try: read = sys.argv[1] write = sys.argv[2] print 'Reading "%s", writing "%s".' % (sys.argv[1], sys.argv[2]) if os.path.isfile(read) and not os.path.isfile(write): r = sqlite3.connect(read) count = r.execute("select count() from tic...
target.write((u"Id,Story,Labels,Story Type,Estimate,Current State,Created at,Accepted at," u"Deadline,Requested By,Owned By,Description,Note,Note\n"))
intro = (u"Id,Story,Labels,Story Type,Estimate,Current State,Created at,Accepted at," u"Deadline,Requested By,Owned By,Description,Note,Note\n") file_count = 1 file_name = "%s-%s.csv" % (target, file_count) writer = open(file_name, "wb") writer.write(intro)
def write_csv(source, target): target.write((u"Id,Story,Labels,Story Type,Estimate,Current State,Created at,Accepted at," u"Deadline,Requested By,Owned By,Description,Note,Note\n")) line = (u"%(Id)s,%(Story)s,%(Labels)s,%(Story Type)s,%(Estimate)s,%(Current State)s," u"%(Created at)s,%(Accepted at)s,%(Deadline)s,%(Requ...
print "Writing..."
print "Writing tickets to %s ...\n" % file_name, line_count = 0
def write_csv(source, target): target.write((u"Id,Story,Labels,Story Type,Estimate,Current State,Created at,Accepted at," u"Deadline,Requested By,Owned By,Description,Note,Note\n")) line = (u"%(Id)s,%(Story)s,%(Labels)s,%(Story Type)s,%(Estimate)s,%(Current State)s," u"%(Created at)s,%(Accepted at)s,%(Deadline)s,%(Requ...
print "\tTicket %(Id)s: %(Story)s" % e
print "%(Id)s," % e,
def write_csv(source, target): target.write((u"Id,Story,Labels,Story Type,Estimate,Current State,Created at,Accepted at," u"Deadline,Requested By,Owned By,Description,Note,Note\n")) line = (u"%(Id)s,%(Story)s,%(Labels)s,%(Story Type)s,%(Estimate)s,%(Current State)s," u"%(Created at)s,%(Accepted at)s,%(Deadline)s,%(Requ...
target.write(csv_line.encode("utf-8"))
writer.write(csv_line.encode("utf-8")) writer.close()
def write_csv(source, target): target.write((u"Id,Story,Labels,Story Type,Estimate,Current State,Created at,Accepted at," u"Deadline,Requested By,Owned By,Description,Note,Note\n")) line = (u"%(Id)s,%(Story)s,%(Labels)s,%(Story Type)s,%(Estimate)s,%(Current State)s," u"%(Created at)s,%(Accepted at)s,%(Deadline)s,%(Requ...
target.close() print "Done!"
print "\n\nDone!"
def main(): """ run this thing """ db, target = getargs() source = read_database(db) write_csv(source, target) target.close() print "Done!"
attribute = doc.createAttribute (attr) attribute.value = value
for match in regex.finditer(attr): attr = attr[:match.start()] + "?" + attr[match.end():] for match in regex.finditer(value): value = value[:match.start()] + "?" + value[match.end():] attribute = doc.createAttribute (attr.encode("utf8")) attribute.value = value.encode("utf8")
def __createXMLElement (name, descr = None, attrs = {}): """ Create XML element with text descr and attributes attrs Keyword arguments: name -- Name of XML element descr -- content of textNode (default None) attrs -- attributes of element (default {}) Return created XML element """ doc = xml.dom.minidom.Document () ...
releaseArchHash = {"2.0" : 2, "2.1" : 4, "2.2": 6, "3.0" : 11, "3.1" : 12, "4.0" : 11}
releaseArchHash = {"2.0" : 2, "2.1" : 4, "2.2": 6, "3.0" : 11, "3.1" : 12, "4.0" : 11, "5.0": 12}
def __createXMLElement (name, descr = None, attrs = {}): """ Create XML element with text descr and attributes attrs Keyword arguments: name -- Name of XML element descr -- content of textNode (default None) attrs -- attributes of element (default {}) Return created XML element """ doc = xml.dom.minidom.Document () ...
rq.tstamp = time.strptime(tstamp_raw, '%d/%b/%Y:%H:%M:%S +0100')
tstamp_raw = tstamp_raw.split()[0] rq.tstamp = time.strptime(tstamp_raw, '%d/%b/%Y:%H:%M:%S')
def gen_processreqs(reqs, conf): """process a tuple of request data, and return the parsed in the form of a generator""" known = RingBuffer(conf['statsdupwindow']) for req in reqs: rq = Req() (ip, tstamp_raw, url, status, referer, ua, country) = req skip = False for r, mreg in conf['statsignoremask']: if r.match(url...
parser = OptionParser(version="wicd-curses-%s (using wicd %s)" % (CURSES_REV,daemon.Hello()))
parser = OptionParser(version="wicd-curses-%s (using wicd %s)" % (CURSES_REV,daemon.Hello()), prog="wicd-curses")
def setup_dbus(force=True): global bus, daemon, wireless, wired try: dbusmanager.connect_to_dbus() except DBusException: print >> sys.stderr, language['cannot_connect_to_daemon'] bus = dbusmanager.get_bus() dbus_ifaces = dbusmanager.get_dbus_ifaces() daemon = dbus_ifaces['daemon'] wireless = dbus_ifaces['wireless'] wir...
self.cbox.set_w(SelText(self.list[index]+self.DOWN_ARROW))
try: self.cbox.set_w(SelText(self.list[index]+self.DOWN_ARROW)) except AttributeError: self.cbox._w = SelText(self.list[index]+self.DOWN_ARROW)
def set_focus(self,index): self.focus = index self.cbox.set_w(SelText(self.list[index]+self.DOWN_ARROW)) if self.overlay: self.overlay._listbox.set_focus(index)
gobject.idle_add(self.status_bar.remove, 1, self.statusID)
gobject.idle_add(self.status_bar.remove_message, 1, self.statusID)
def _set_not_connecting_state(self): if self.connecting: if self.update_cb: gobject.source_remove(self.update_cb) self.update_cb = misc.timeout_add(2, self.update_statusbar) self.connecting = False if self.pulse_active: self.pulse_active = False gobject.idle_add(self.all_network_list.set_sensitive, True) gobject.idle_a...
gobject.idle_add(self.status_bar.remove, 1, self.statusID)
gobject.idle_add(self.status_bar.remove_message, 1, self.statusID)
def set_connecting_state(self, info): if not self.connecting: if self.update_cb: gobject.source_remove(self.update_cb) self.update_cb = misc.timeout_add(500, self.update_statusbar, milli=True) self.connecting = True if not self.pulse_active: self.pulse_active = True misc.timeout_add(100, self.pulse_progress_bar, milli=...
gobject.idle_add(self.status_bar.remove, 1, self.statusID)
gobject.idle_add(self.status_bar.remove_message, 1, self.statusID)
def setup_interface_for_connection(): cancel_button = self.wTree.get_object("cancel_button") cancel_button.set_sensitive(True) self.all_network_list.set_sensitive(False) if self.statusID: gobject.idle_add(self.status_bar.remove, 1, self.statusID) gobject.idle_add(self.set_status, language["disconnecting_active"]) gobje...
self.read(path)
try: self.read(path) except ParsingError, e: self.write() try: self.read(path) except ParsingError, p: import sys print "Could not start wicd: %s" % p.message sys.exit(1)
def __init__(self, path, debug=False, mark_whitespace="`'`"): RawConfigParser.__init__(self) self.config_file = path self.debug = debug self.mrk_ws = mark_whitespace self.read(path)
options.network_property = option.network_property.lower()
options.network_property = options.network_property.lower()
def is_valid_wired_network_profile(profile_name): if not profile_name in wired.GetWiredProfileList(): print 'Profile of that name does not exist.' sys.exit(5)
shutil.move(pofile, lang_identifier+'.po')
shutil.move(pofile, 'po/'+lang_identifier+'.po')
def run(self): import urllib, shutil if os.path.exists('translations'): shutil.rmtree('translations/') os.makedirs('translations') filename, headers = urllib.urlretrieve('http://wicd.sourceforge.net/translator/idlist/') id_file = open(filename, 'r') lines = id_file.readlines() # remove the \n from the end of lines, and...
'/LC_MESSAGES/wicd.mo ' + lang_identifier + '.po') os.remove(lang_identifier+'.po')
'/LC_MESSAGES/wicd.mo po/' + lang_identifier + '.po')
def run(self): import urllib, shutil if os.path.exists('translations'): shutil.rmtree('translations/') os.makedirs('translations') filename, headers = urllib.urlretrieve('http://wicd.sourceforge.net/translator/idlist/') id_file = open(filename, 'r') lines = id_file.readlines() # remove the \n from the end of lines, and...
gladefile = wpath.share + "wicd.glade"
gladefile = wpath.gtk + "wicd.glade"
def main (argv): """ Runs the script configuration dialog. """ if len(argv) < 2: print 'Network id to configure is missing, aborting.' sys.exit(1) network = argv[1] network_type = argv[2] script_info = get_script_info(network, network_type) gladefile = wpath.share + "wicd.glade" wTree = gtk.glade.XML(gladefile) dial...
if line.endswith("failing"):
if line.endswith("failing."):
def _parse_udhcpc(self, pipe): """ Determines if obtaining an IP using udhcpc succeeded.
'pre-disconnection', (mac, name)),
'pre-disconnection', mac, name),
def Disconnect(self, nettype, name, mac): """ Disconnect from the network. """ iface = self.iface # mac and name need to be strings if mac in (None, ''): mac = 'X' if name in (None, ''): name = 'X' misc.ExecuteScripts(wpath.predisconnectscripts, self.debug, extra_parameters=(nettype, name, mac)) if self.pre_disconnect_...
(mac, name)),
mac, name),
def Disconnect(self, nettype, name, mac): """ Disconnect from the network. """ iface = self.iface # mac and name need to be strings if mac in (None, ''): mac = 'X' if name in (None, ''): name = 'X' misc.ExecuteScripts(wpath.predisconnectscripts, self.debug, extra_parameters=(nettype, name, mac)) if self.pre_disconnect_...
cmd = ['iwconfig', self.iface, 'essid', essid] if self.verbose: print str(cmd) misc.Run(cmd)
self.SetEssid(essid)
def Associate(self, essid, channel=None, bssid=None): """ Associate with the specified wireless network.
def __init__(self, remote_hosts=(), **kwargs): super(ScannerManager, self).__init__(remote_hosts, **kwargs)
def __init__(self, **kwargs): super(ScannerManager, self).__init__(**kwargs) remote_hosts = kwargs.get('remote_host', tuple())
def __init__(self, remote_hosts=(), **kwargs): super(ScannerManager, self).__init__(remote_hosts, **kwargs) self._proxies = [] for host in remote_hosts: proxy = xmlrpclib.ServerProxy("http://%s/" % host, allow_none=True) self._proxies.append(proxy)
scanner_id = kwargs.get('scanner_id', None)
scanner_id = kwargs.get('id', None)
def __init__(self, **kwargs): # Different hosts can have the same id, so the host need to be part of # the scanner id scanner_id = kwargs.get('scanner_id', None) proxy = kwargs.get('proxy', None) remote_host = proxy._ServerProxy__host
remote_hosts = kwargs.get('remote_host', tuple())
remote_hosts = kwargs.get('remote_hosts', tuple())
def __init__(self, **kwargs): super(ScannerManager, self).__init__(**kwargs) remote_hosts = kwargs.get('remote_host', tuple())
logging.debug('Reloading remote device information')
logging.info('Reloading remote device information')
def _refresh(self): logging.debug('Reloading remote device information') self._devices = [] for proxy in self._proxies: # TODO: Redo it without accessing protected members remote_host = proxy._ServerProxy__host try: response = proxy.list_scanners() except socket.error: logging.error('Connection refused when trying to l...
scanner = Scanner(proxy, **scanner_info)
scanner_info.update({'proxy': proxy}) scanner = Scanner(**scanner_info)
def _refresh(self): logging.debug('Reloading remote device information') self._devices = [] for proxy in self._proxies: # TODO: Redo it without accessing protected members remote_host = proxy._ServerProxy__host try: response = proxy.list_scanners() except socket.error: logging.error('Connection refused when trying to l...
creds, netloc = netloc.split('@')
try: creds, netloc = netloc.split('@') except ValueError: creds, path = path.split('@')
def parse_swift_tokens(cls, parsed_uri): """ Parsing the swift uri is three phases: 1) urlparse to split the tokens 2) use RE to split on @ and / 3) reassemble authurl """ path = parsed_uri.path.lstrip('//') netloc = parsed_uri.netloc
packages=find_packages(exclude=['test', 'bin']),
packages=find_packages(exclude=['tests', 'bin']),
def run(self): if os.path.isdir('.bzr'): # We're in a bzr branch
scripts=[])
scripts=['bin/parallax-server', 'bin/teller-server'])
def run(self): if os.path.isdir('.bzr'): # We're in a bzr branch
print res.read()
def do_request(self, method, action, body=None, headers={}): """ Connects to the server and issues a request. Handles converting any returned HTTP error status codes to OpenStack/Glance exceptions and closing the server connection. Returns the result data, or raises an appropriate exception.
core_count = getCoreCount(log_entry['Resource_List.nodes'])
if log_entry.has_key('Resource_List.ncpus'): core_count = int(log_entry['Resource_List.ncpus']) elif log_entry.has_key('Resource_List.nodes'): core_count = getCoreCount(log_entry['Resource_List.nodes']) else: logging.warning('Missing processor count for entry: %s' % job_id)
def createUsageRecord(log_entry, hostname, user_map, vo_map, missing_user_mappings): """ Creates a Usage Record object given a Torque log entry. """ # extract data from the workload trace (log_entry) job_id = log_entry['jobid'] user_name = log_entry['user'] queue = log_entry['queue'] account = log...
if prefix.startswith(os.path.join(RELOCATE or '', 'etc')):
if prefix.startswith(os.path.join(RELOCATE or '/', 'etc')):
def finalize_options(self): install_data.finalize_options(self)
logging.warning('Missing processor count for entry: %s' % job_id) hosts = list(set([hc.split('/')[0] for hc in log_entry['exec_host'].split('+')]))
logging.warning('Missing processor count for entry: %s (will guess from host list)' % job_id) core_count = len(hosts)
def createUsageRecord(log_entry, hostname, user_map, vo_map, missing_user_mappings): """ Creates a Usage Record object given a Torque log entry. """ # extract data from the workload trace (log_entry) job_id = log_entry['jobid'] user_name = log_entry['user'] queue = log_entry['queue'] account = log...
ur.project = account
ur.project_name = account
def createUsageRecord(log_entry, hostname, user_map, vo_map, missing_user_mappings): """ Creates a Usage Record object given a Torque log entry. """ # extract data from the workload trace (log_entry) job_id = log_entry['jobid'] user_name = log_entry['user'] queue = log_entry['queue'] account = log...
def test_recount(self): import sys x = serek.deserialize('i:1234567;') y = 1234568 self.assertEquals(sys.getrefcount(x), sys.getrefcount(y)) x = serek.deserialize('a:2:{i:11223344;s:3:"abc";i:22334455;s:4:"qwerty";}') y = {33445566: "cba", 44556677: "ytreqw"} self.assertEquals(sys.getrefcount(x), sys.getrefcount(y...
def test_recount(self): # this test might give false-negatives under rare circumstances, when there happen to exist # extra references somwehere in the Python VM to object used in this test import sys
print 'builder', self.builder_file, self.builder_path
def _load_builder(self): print 'builder', self.builder_file, self.builder_path
print type
def _load_builder(self): print 'builder', self.builder_file, self.builder_path
>>> data = GObjectUserDataProxy()
>>> data = GObjectUserDataProxy(w)
def run_in_window(target, on_destroy=gtk.main_quit): """Run a widget, or a delegate in a Window """ w = _get_in_window(target) if on_destroy: w.connect('destroy', on_destroy) w.resize(500, 400) w.move(100, 100) w.show_all() gtk.main()