rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
def _parse_request(self):
self.ready = True def read_request_line(self):
def parse_request(self): """Parse the next HTTP request start-line and message-headers.""" self.rfile = SizeCheckWrapper(self.conn.rfile, self.server.max_request_header_size) try: self._parse_request() except MaxSizeExceeded: self.simple_response("413 Request Entity Too Large", "The headers sent with the request exceed...
self.simple_response(400, "HTTP requires CRLF terminators")
self.simple_response("400 Bad Request", "HTTP requires CRLF terminators")
def _parse_request(self): # HTTP/1.1 connections are persistent by default. If a client # requests a page, then idles (leaves the connection open), # then rfile.readline() will raise socket.error("timed out"). # Note that it does this based on the value given to settimeout(), # and doesn't need the client to request or...
self.simple_response(400, "Malformed Request-Line")
self.simple_response("400 Bad Request", "Malformed Request-Line")
def _parse_request(self): # HTTP/1.1 connections are persistent by default. If a client # requests a page, then idles (leaves the connection open), # then rfile.readline() will raise socket.error("timed out"). # Note that it does this based on the value given to settimeout(), # and doesn't need the client to request or...
self.ready = True
def _parse_request(self): # HTTP/1.1 connections are persistent by default. If a client # requests a page, then idles (leaves the connection open), # then rfile.readline() will raise socket.error("timed out"). # Note that it does this based on the value given to settimeout(), # and doesn't need the client to request or...
buf = [self.server.protocol + " " + status + CRLF, "Content-Length: %s\r\n" % len(msg),
buf = ["Content-Length: %s\r\n" % len(msg),
def simple_response(self, status, msg=""): """Write a simple response back to the client.""" status = str(status) buf = [self.server.protocol + " " + status + CRLF, "Content-Length: %s\r\n" % len(msg), "Content-Type: text/plain\r\n"] if status[:3] == "413" and self.response_protocol == 'HTTP/1.1': # Request Entity Too...
if status[:3] == "413" and self.response_protocol == 'HTTP/1.1':
if status[:3] in ("413", "414"):
def simple_response(self, status, msg=""): """Write a simple response back to the client.""" status = str(status) buf = [self.server.protocol + " " + status + CRLF, "Content-Length: %s\r\n" % len(msg), "Content-Type: text/plain\r\n"] if status[:3] == "413" and self.response_protocol == 'HTTP/1.1': # Request Entity Too...
buf.append("Connection: close\r\n")
if self.response_protocol == 'HTTP/1.1': buf.append("Connection: close\r\n") else: status = "400 Bad Request"
def simple_response(self, status, msg=""): """Write a simple response back to the client.""" status = str(status) buf = [self.server.protocol + " " + status + CRLF, "Content-Length: %s\r\n" % len(msg), "Content-Type: text/plain\r\n"] if status[:3] == "413" and self.response_protocol == 'HTTP/1.1': # Request Entity Too...
self.conn.wfile.sendall("".join(buf))
self.conn.wfile.sendall(status_line + "".join(buf))
def simple_response(self, status, msg=""): """Write a simple response back to the client.""" status = str(status) buf = [self.server.protocol + " " + status + CRLF, "Content-Length: %s\r\n" % len(msg), "Content-Type: text/plain\r\n"] if status[:3] == "413" and self.response_protocol == 'HTTP/1.1': # Request Entity Too...
self.simple_response("413 Request Entity Too Large")
self.simple_response("413 Request Entity Too Large", "The headers sent with the request exceed the maximum " "allowed bytes.")
def parse_request(self): """Parse the next HTTP request start-line and message-headers.""" self.rfile = SizeCheckWrapper(self.conn.rfile, self.server.max_request_header_size) try: self._parse_request() except MaxSizeExceeded: self.simple_response("413 Request Entity Too Large") return
self.simple_response("413 Request Entity Too Large")
self.simple_response("413 Request Entity Too Large", "The entity sent with the request exceeds the maximum " "allowed bytes.")
def _parse_request(self): # HTTP/1.1 connections are persistent by default. If a client # requests a page, then idles (leaves the connection open), # then rfile.readline() will raise socket.error("timed out"). # Note that it does this based on the value given to settimeout(), # and doesn't need the client to request or...
self.simple_response("413 Request Entity Too Large")
self.simple_response("413 Request Entity Too Large", "The entity sent with the request exceeds the maximum " "allowed bytes.")
def respond(self): """Call the gateway and write its iterable output.""" mrbs = self.server.max_request_body_size if self.chunked_read: self.rfile = ChunkedRFile(self.conn.rfile, mrbs) else: cl = int(self.inheaders.get("Content-Length", 0)) if mrbs and mrbs < cl: if not self.sent_headers: self.simple_response("413 Requ...
rbufsize = -1
rbufsize = DEFAULT_BUFFER_SIZE wbufsize = DEFAULT_BUFFER_SIZE
def readline(self, size=-1): data = self._rbuf if size < 0: # Read until \n or EOF, whichever comes first if self._rbufsize <= 1: # Speed up unbuffered case assert data == "" buffers = [] while data != "\n": data = self.recv(1) if not data: break buffers.append(data) return "".join(buffers) nl = data.find('\n') if nl >...
self.wfile = makefile(sock, "wb", -1)
self.wfile = makefile(sock, "wb", self.wbufsize)
def __init__(self, server, sock, makefile=CP_fileobject): self.server = server self.socket = sock self.rfile = makefile(sock, "rb", self.rbufsize) self.wfile = makefile(sock, "wb", -1)
self.wfile = CP_fileobject(self.socket._sock, "wb", -1)
self.wfile = CP_fileobject(self.socket._sock, "wb", self.wbufsize)
def communicate(self): """Read each request and respond appropriately.""" request_seen = False try: while True: # (re)set req to None so that if something goes wrong in # the RequestHandlerClass constructor, the error doesn't # get written to the previous request. req = None req = self.RequestHandlerClass(self.server, ...
* ``makefile(sock, mode='r', bufsize=-1) -> socket file object``
* ``makefile(sock, mode='r', bufsize=DEFAULT_BUFFER_SIZE) -> socket file object``
def prevent_socket_inheritance(sock): """Mark the given socket fd as non-inheritable (POSIX).""" fd = sock.fileno() old_flags = fcntl.fcntl(fd, fcntl.F_GETFD) fcntl.fcntl(fd, fcntl.F_SETFD, old_flags | fcntl.FD_CLOEXEC)
def makefile(self, sock, mode='r', bufsize=-1):
def makefile(self, sock, mode='r', bufsize=DEFAULT_BUFFER_SIZE):
def makefile(self, sock, mode='r', bufsize=-1): raise NotImplemented
wfile = CP_fileobject(s, "wb", -1)
wfile = CP_fileobject(s, "wb", DEFAULT_BUFFER_SIZE)
def tick(self): """Accept a new connection and put it on the Queue.""" try: s, addr = self.socket.accept() if not self.ready: return prevent_socket_inheritance(s) if hasattr(s, 'settimeout'): s.settimeout(self.timeout) makefile = CP_fileobject ssl_env = {} # if ssl cert and key are set, we try to be a secure HTTP ser...
self.read_request_headers()
success = self.read_request_headers()
def parse_request(self): """Parse the next HTTP request start-line and message-headers.""" self.rfile = SizeCheckWrapper(self.conn.rfile, self.server.max_request_header_size) try: self.read_request_line() except MaxSizeExceeded: self.simple_response("414 Request-URI Too Long", "The Request-URI sent with the request exc...
return
return False
def read_request_headers(self): # then all the http headers try: read_headers(self.rfile, self.inheaders) except ValueError, ex: self.simple_response("400 Bad Request", ex.args[0]) return mrbs = self.server.max_request_body_size if mrbs and int(self.inheaders.get("Content-Length", 0)) > mrbs: self.simple_response("41...
self.chunked_read = False
def read_request_headers(self): # then all the http headers try: read_headers(self.rfile, self.inheaders) except ValueError, ex: self.simple_response("400 Bad Request", ex.args[0]) return mrbs = self.server.max_request_body_size if mrbs and int(self.inheaders.get("Content-Length", 0)) > mrbs: self.simple_response("41...
if self.status == constants.TANKDEAD: self.dead_timer -= dt if self.dead_timer <= 0: self.team.respawn(self,not self.spawned) self.spawned = True return
def update(self, dt): '''update tank's position, status, etc.'''
if tank.status == 'DEAD':
if tank.status == constants.TANKDEAD:
def bzrc_occgrid(self, args): """occupancy grid Request an occupancy grid.
self.team.map.dropFlag(self.flag)
self.team.map.returnFlag(self.flag)
def kill(self): '''destroy the tank''' self.status = constants.TANKDEAD self.dead_timer = config['respawn_time'] self.team.score.score_tank(self) if self.flag: self.team.map.dropFlag(self.flag) self.flag = None for shot in self.shots: shot.kill() self.shots = []
if not self.flag and collide.dist(self.pos, self.team.base.center) < self.team.base.radius: self.pos[0] += 1
basedist = collide.dist(self.pos, self.team.base.center) if basedist < self.team.base.radius: angle = math.atan2(self.team.base.center[1]-self.pos[1], self.team.base.center[0]-self.pos[0]) + math.pi self.pos = [math.cos(angle) * self.team.base.radius + self.team.base.pos[0], math.sin(angle) * self.team.base.radius + se...
def update_goals(self, dt): '''update the velocities to match the goals''' if not self.flag and collide.dist(self.pos, self.team.base.center) < self.team.base.radius: self.pos[0] += 1 self.hspeed += self.accelx self.vspeed += self.accely max = 30 if collide.dist((0,0),(self.hspeed, self.vspeed)) > max: dr = math.atan2(...
else:
elif tank.status != constants.TANKDEAD and self.status != constants.TANKDEAD:
def collide_tank(self, tank): if tank.team == self.team: if tank.status == constants.TANKDEAD: self.team.respawn(tank) else: base = self.team.map.closest_base(self.pos) if not base:return if base.team == tank.team: self.kill() elif base.team == self.team: tank.kill()
def setaccely(self, speed): '''set the goal speed''' self.accely = speed def setaccelx(self, angvel): '''set the goal angular velocity''' self.accelx = angvel
def setaccelx(self, accelx): '''set the goal x accelleration''' self.accelx = accelx def setaccely(self, accely): '''set the goal y accelleration''' self.accely = accely
def setaccely(self, speed): '''set the goal speed''' self.accely = speed
if size[0] < 0 or size[1] < 0: print pos, size
def read_occgrid(self): pos = tuple(int(a) for a in self.expect('at')[0].split(',')) size = tuple(int(a) for a in self.expect('size')[0].split('x')) if size[0] < 0 or size[1] < 0: print pos, size grid = numpy.zeros(size) for x in range(size[0]): line = self.read_arr() for y in range(size[1]): if line[0] == '1': grid[x,...
line = self.read_arr()
line = self.read_arr()[0]
def read_occgrid(self): pos = tuple(int(a) for a in self.expect('at')[0].split(',')) size = tuple(int(a) for a in self.expect('size')[0].split('x')) if size[0] < 0 or size[1] < 0: print pos, size grid = numpy.zeros(size) for x in range(size[0]): line = self.read_arr() for y in range(size[1]): if line[0] == '1': grid[x,...
if line[0] == '1':
if line[y] == '1':
def read_occgrid(self): pos = tuple(int(a) for a in self.expect('at')[0].split(',')) size = tuple(int(a) for a in self.expect('size')[0].split('x')) if size[0] < 0 or size[1] < 0: print pos, size grid = numpy.zeros(size) for x in range(size[0]): line = self.read_arr() for y in range(size[1]): if line[0] == '1': grid[x,...
self.team.map.returnFlag(self.flag)
self.team.map.dropFlag(self.flag)
def kill(self): '''destroy the tank''' self.status = constants.TANKDEAD self.dead_timer = config['respawn_time'] self.team.score.score_tank(self) if self.flag: self.team.map.returnFlag(self.flag) self.flag = None for shot in self.shots: shot.kill() self.shots = []
self.obstacles = [Box(item) for item in config.config.world.boxes] self.bases = dict((item.color, Base(item)) for item in config.config.world.bases)
self.obstacles = [Box(item) for item in config.world.boxes] self.build_truegrid() self.bases = dict((item.color, Base(item)) for item in config.world.bases)
def __init__(self, game): self.game = game
if self.timespent > config.config['time_limit']:
if self.timespent > config['time_limit']:
def update(self, dt): '''update the teams''' self.timespent += dt if self.timespent > config.config['time_limit']: self.end_game = True return for team in self.teams.values(): team.update(dt)
ntanks = config.config[self.color+'_tanks']
ntanks = config[self.color+'_tanks']
def __init__(self, map, color, base): self.color = color self.map = map ntanks = config.config[self.color+'_tanks'] if ntanks is None: ntanks = config.config['default_tanks']
ntanks = config.config['default_tanks'] Tcls = (SeppiTank, GoodrichTank)[bool(config.config['freeze_tag'])]
ntanks = config['default_tanks'] Tcls = (SeppiTank, GoodrichTank)[bool(config['freeze_tag'])]
def __init__(self, map, color, base): self.color = color self.map = map ntanks = config.config[self.color+'_tanks'] if ntanks is None: ntanks = config.config['default_tanks']
self.posnoise = config.config[self.color+'_posnoise']
self.posnoise = config[self.color+'_posnoise']
def __init__(self, map, color, base): self.color = color self.map = map ntanks = config.config[self.color+'_tanks'] if ntanks is None: ntanks = config.config['default_tanks']
self.posnoise = config.config['default_posnoise'] self.angnoise = config.config[self.color+'_angnoise']
self.posnoise = config['default_posnoise'] self.angnoise = config[self.color+'_angnoise']
def __init__(self, map, color, base): self.color = color self.map = map ntanks = config.config[self.color+'_tanks'] if ntanks is None: ntanks = config.config['default_tanks']
self.angnoise = config.config['default_angnoise'] self.velnoise = config.config[self.color+'_velnoise']
self.angnoise = config['default_angnoise'] self.velnoise = config[self.color+'_velnoise']
def __init__(self, map, color, base): self.color = color self.map = map ntanks = config.config[self.color+'_tanks'] if ntanks is None: ntanks = config.config['default_tanks']
self.velnoise = config.config['default_velnoise']
self.velnoise = config['default_velnoise']
def __init__(self, map, color, base): self.color = color self.map = map ntanks = config.config[self.color+'_tanks'] if ntanks is None: ntanks = config.config['default_tanks']
if not config.config['freeze_tag']:
if not config['freeze_tag']:
def respawn(self, tank, first=True): '''respawn a dead tank''' tank.status = constants.TANKALIVE if tank.pos != constants.DEADZONE: return if not config.config['freeze_tag']: tank.rot = random.uniform(0, 2*math.pi) pos = self.spawn_position() for i in xrange(1000): if self.check_position(pos, constants.TANKRADIUS): bre...
if point[0]-radius<-config.config.world.size[0]/2 or\ point[1]-radius<-config.config.world.size[1]/2 or\ point[0]+radius>config.config.world.size[0]/2 or \ point[1]+radius>config.config.world.size[1]/2:
if point[0]-radius<-config.world.size[0]/2 or\ point[1]-radius<-config.world.size[1]/2 or\ point[0]+radius>config.world.size[0]/2 or \ point[1]+radius>config.world.size[1]/2:
def check_position(self, point, radius): '''check a position to see if it is safe to spawn a tank there''' for o in self._obstacles: if collide.poly2circle(o.shape, (point, radius)): return False for shot in self.map.shots(): if collide.circle2circle((point, radius), (shot.pos, constants.SHOTRADIUS)): return False for ...
if config.config['freeze_tag']:
if config['freeze_tag']:
def shoot(self, tankid): '''tell a tank to shoot''' if config.config['freeze_tag']: raise GoodrichException,'No shooting in this game' return self.tank(tankid).shoot()
self.dead_timer = config.config['respawn_time']
self.dead_timer = config['respawn_time']
def kill(self): '''destroy the tank''' self.status = constants.TANKDEAD self.dead_timer = config.config['respawn_time'] self.team.score.score_tank(self) if self.flag: self.team.map.dropFlag(self.flag) self.flag = None for shot in self.shots: shot.kill() self.shots = []
if pos[0]-radius<-config.config.world.size[0]/2 or\ pos[1]-radius<-config.config.world.size[1]/2 or\ pos[0]+radius>config.config.world.size[0]/2 or \ pos[1]+radius>config.config.world.size[1]/2:
if pos[0]-radius<-config.world.size[0]/2 or\ pos[1]-radius<-config.world.size[1]/2 or\ pos[0]+radius>config.world.size[0]/2 or \ pos[1]+radius>config.world.size[1]/2:
def collision_at(self, pos): for obs in self.team.map.obstacles: if collide.poly2circle(obs.shape, ((pos),constants.TANKRADIUS)): return True for tank in self.team.map.tanks(): if tank is self:continue if collide.circle2circle((tank.pos, constants.TANKRADIUS), (pos, constants.TANKRADIUS)): self.collide_tank(tank) retur...
len(self.shots) >= config.config['max_shots']:
len(self.shots) >= config['max_shots']:
def shoot(self): '''tell the tank to shoot''' if self.reloadtimer > 0 or \ len(self.shots) >= config.config['max_shots']: return False shot = Shot(self) self.shots.insert(0, shot) self.team.map.inbox.append(shot) self.reloadtimer = constants.RELOADTIME return True
if tank.team == self.team and not config.config['friendly_fire']:
if tank.team == self.team and not config['friendly_fire']:
def check_collisions(self): for obs in self.team.map.obstacles: if collide.poly2circle(obs.shape, ((self.pos),constants.SHOTRADIUS)): return self.kill() for tank in self.team.map.tanks(): if self in tank.shots:continue if collide.circle2circle((tank.pos, constants.TANKRADIUS), (self.pos, constants.SHOTRADIUS)): if tank...
if self.pos[0]<-config.config.world.size[0]/2 or\ self.pos[1]<-config.config.world.size[1]/2 or\ self.pos[0]>config.config.world.size[0]/2 or \ self.pos[1]>config.config.world.size[1]/2:
if self.pos[0]<-config.world.size[0]/2 or\ self.pos[1]<-config.world.size[1]/2 or\ self.pos[0]>config.world.size[0]/2 or \ self.pos[1]>config.world.size[1]/2:
def check_collisions(self): for obs in self.team.map.obstacles: if collide.poly2circle(obs.shape, ((self.pos),constants.SHOTRADIUS)): return self.kill() for tank in self.team.map.tanks(): if self in tank.shots:continue if collide.circle2circle((tank.pos, constants.TANKRADIUS), (self.pos, constants.SHOTRADIUS)): if tank...
if tank.team == self.team and not config.config['friendly_fire']:
if tank.team == self.team and not config['friendly_fire']:
def check_line(self, p1, p2): for obs in self.team.map.obstacles: if collide.rect2line(obs.rect, (p1,p2)): return self.kill() for tank in self.team.map.tanks(): if collide.circle2line((tank.pos, constants.TANKRADIUS + constants.SHOTRADIUS), (p1,p2)): if tank.team == self.team and not config.config['friendly_fire']: con...
if self.pos[0]<-config.config.world.size[0]/2 or\ self.pos[1]<-config.config.world.size[1]/2 or\ self.pos[0]>config.config.world.size[0]/2 or \ self.pos[1]>config.config.world.size[1]/2:
if self.pos[0]<-config.world.size[0]/2 or\ self.pos[1]<-config.world.size[1]/2 or\ self.pos[0]>config.world.size[0]/2 or \ self.pos[1]>config.world.size[1]/2:
def check_line(self, p1, p2): for obs in self.team.map.obstacles: if collide.rect2line(obs.rect, (p1,p2)): return self.kill() for tank in self.team.map.tanks(): if collide.circle2line((tank.pos, constants.TANKRADIUS + constants.SHOTRADIUS), (p1,p2)): if tank.team == self.team and not config.config['friendly_fire']: con...
self.shape = scale_rotate_poly(poly, 1, item.rot)
self.shape = list(scale_rotate_poly(poly, 1, item.rot))
def __init__(self, item): self.color = item.color self.center = self.pos = item.pos.asList() self.size = tuple(x*2 for x in item.size.asList()) self.radius = math.sqrt((self.size[0]/2)**2 + (self.size[1]/2)**2) poly = tuple(convertBoxtoPoly(item.pos,self.size)) self.rect = (item.pos[0]-self.size[0]/2, item.pos[1]-self....
self.shape = scale_rotate_poly(self.shape, (self.radius + padding)/float(self.radius), 0)
self.shape = list(scale_rotate_poly(self.shape, (self.radius + padding)/float(self.radius), 0))
def pad(self, padding): self.shape = scale_rotate_poly(self.shape, (self.radius + padding)/float(self.radius), 0)
if config.config['freeze_tag'] and not first:
if tank.pos != constants.DEADZONE:
def respawn(self, tank, first=True): '''respawn a dead tank''' tank.status = constants.TANKALIVE if config.config['freeze_tag'] and not first: return if not config.config['freeze_tag']: tank.rot = random.uniform(0, 2*math.pi) pos = self.spawn_position() for i in xrange(1000): if self.check_position(pos, constants.TANKR...
self.pos = [0,0]
self.pos = constants.DEADZONE
def __init__(self, team, tankid): self.team = team self.pos = [0,0] self.rot = 0 self.angvel = 0 self.callsign = self.team.color + str(tankid) self.status = constants.TANKDEAD self.shots = [] self.reloadtimer = 0 self.dead_timer = -1 self.flag = None self.spawned = False
self.dead_timer -= dt if self.dead_timer <= 0: self.team.respawn(self,not self.spawned) self.spawned = True
def update(self, dt): '''update the tank's position, status, velocities''' if self.status == constants.TANKDEAD: self.dead_timer -= dt if self.dead_timer <= 0: self.team.respawn(self,not self.spawned) self.spawned = True return
for shot in self.shots: shot.update(dt) if self.reloadtimer > 0: self.reloadtimer -= dt
def update(self, dt): '''update the tank's position, status, velocities''' if self.status == constants.TANKDEAD: self.dead_timer -= dt if self.dead_timer <= 0: self.team.respawn(self,not self.spawned) self.spawned = True return
if pos[0]<-config.config.world.size[0]/2 or\ pos[1]<-config.config.world.size[1]/2 or\ pos[0]>config.config.world.size[0]/2 or \ pos[1]>config.config.world.size[1]/2:
radius = constants.TANKRADIUS if pos[0]-radius<-config.config.world.size[0]/2 or\ pos[1]-radius<-config.config.world.size[1]/2 or\ pos[0]+radius>config.config.world.size[0]/2 or \ pos[1]+radius>config.config.world.size[1]/2:
def collision_at(self, pos): for obs in self.team.map.obstacles: if collide.poly2circle(obs.shape, ((pos),constants.TANKRADIUS)): return True for tank in self.team.map.tanks(): if tank is self:continue if collide.circle2circle((tank.pos, constants.TANKRADIUS), (pos, constants.TANKRADIUS)): self.collide_tank(tank) retur...
help='can you grab your own flag')
help='enables grabbing your own flag')
def parse_cli_args(self, args): p = optparse.OptionParser()
help='allow friendly fire')
help="don't die on friendly fire")
def parse_cli_args(self, args): p = optparse.OptionParser()
if collide.rect2circle(obs.rect, ((self.pos),constants.SHOTRADIUS)):
if collide.poly2circle(obs.shape, ((self.pos),constants.SHOTRADIUS)):
def check_collisions(self): for obs in self.team.map.obstacles: if collide.rect2circle(obs.rect, ((self.pos),constants.SHOTRADIUS)): return self.kill() for tank in self.team.map.tanks(): if collide.circle2circle((tank.pos, constants.TANKRADIUS), (self.pos, constants.SHOTRADIUS)): if tank.team == self.team and not confi...
zip(line[2:10:2], line[3:10:2])]
zip(rest[2:10:2], rest[3:10:2])]
def read_teams(self): self.expect('begin')
zip(line[::2], line[1::2])]
zip(rest[::2], rest[1::2])]
def read_obstacles(self): self.expect('begin')
if self.pos == constants.DEADZONE:
if (self.pos == constants.DEADZONE and self.status != constants.TANKDEAD):
def update(self, dt): '''update the tank's position, status, velocities'''
layermap=QgsMapLayerRegistry.instance().mapLayers()
self.layermap=QgsMapLayerRegistry.instance().mapLayers()
def run(self): # create and show a configuration dialog or something similar flags = Qt.WindowTitleHint | Qt.WindowSystemMenuHint | Qt.WindowMaximizeButtonHint # QgisGui.ModalDialogFlags self.pluginGui = ui_Control(self.iface.mainWindow())
for (name,layer) in sorted(layermap.iteritems()):
for (name,layer) in sorted(self.layermap.iteritems()):
def run(self): # create and show a configuration dialog or something similar flags = Qt.WindowTitleHint | Qt.WindowSystemMenuHint | Qt.WindowMaximizeButtonHint # QgisGui.ModalDialogFlags self.pluginGui = ui_Control(self.iface.mainWindow())
appscript.app(terminal_program).activate()
limit = 100 app = appscript.app(terminal_program) while limit > 0: limit -= 1 app.activate() if app.frontmost(): return
def activate_terminal(): terminal_program = os.environ.get("VIMPDBHOOK_TERMINAL_APP", "iTerm") appscript.app(terminal_program).activate()
self.column_headers=[ 'Time','H_vsm','m','Mmass','X','Y','Tsample']
self.column_headers=[ 'Time','H_vsm','m','Mvol','Mmass','X','Y','Tsample']
def __parse_VSMdata(self): self.data=numpy.genfromtxt(self.filename,dtype='float',skip_header=6) self.column_headers=[ 'Time','H_vsm','m','Mmass','X','Y','Tsample']
column_data=numpy.atleast_2d(column_data) self.data=numpy.insert(self.data,index, column_data,1) return True
if isinstance(column_data, numpy.ndarray): column_data=numpy.atleast_2d(column_data) self.data=numpy.insert(self.data,index, column_data,1) elif callable(column_data): new_data=map(column_data, self) new_data=numpy.array(new_data) numpy_data=numpy.atleast_2d(new_data) self.data=numpy.insert(self.data,index, numpy_data,...
def add_column(self,column_data,column_header='', index=None): """Appends a column of data or inserts a column to a datafile""" if index is None: index=len(self.column_headers) else: index=self.find_col(index) self.column_headers.insert(index, column_header) # The following 2 lines make the array we are adding a # [1,...
ylabel=self.column_headers[y_column]
ylabel=self.column_headers[column_y]
def plot_xy(self,column_x, column_y,title='',save_filename='',show_plot=True): """plot_xy(x column, y column/s, title,save filename, show plot=True) Makes and X-Y plot of the specified data.""" column_x=self.find_col(column_x) column_y=self.find_col(column_y) x=self.column(column_x) y=self.column(column_y) if show_plo...
return popt, pconv
return popt, pcov
def curve_fit(self, func, xcol, ycol, p0=None, sigma=None, bounds=lambda x, y: True ): """General curve fitting function passed through from numpy AnalysisFile.Curve_fit(fitting function, x-column,y_column, initial parameters=None, weighting=None, bounds function) The fitting function should have prototype y=f(x,p[0...
shp=(-1, len(row)-1)
shp=(-1, maxcol-1)
def __parse_data(self): """Internal function to parse the tab deliminated text file """ reader = csv.reader(open(self.filename, "rb"), delimiter='\t', quoting=csv.QUOTE_NONE) row=reader.next() assert row[0]=="TDI Format 1.5" # Bail out if not the correct format self.data=numpy.array([]) headers = row[1:len(row)] for ro...
elif isinstance(value, flot):
elif isinstance(value, float):
def __setitem__(self, name, value): # writing the metadata neans doing something sensible with the type hints if isinstance(value,bool): self.typehint[name]="Boolean" elif isinstance(value, int): self.typehint[name]="I32" elif isinstance(value, flot): self.typehint[name]="Double Float" else: self.typehint[name]="String...
if other.shape[1]!=self.data.shape[1]:
if len(self.data)==0: t=numpy.atleast_2d(other) c=numpy.shape(t)[1] self.column_headers=map(lambda x:"Column_"+str(x), range(c)) newdata=deepcopy(self) newdata.data=t return newdata elif len(numpy.shape(other))==1: if numpy.shape(other)[0]==numpy.shape(self.data)[1]: newdata=deepcopy(self) newdata.data=numpy.append(sel...
def __add__(self, other): #Overload the + operator to add data file rows if isinstance(other, numpy.ndarray): if other.shape[1]!=self.data.shape[1]: # DataFile + array with correct number of columns newdata=deepcopy(self) newdata.data=numpy.append(self.data, other, 0) return newdata else: return NotImplemented elif isi...
def max(self, column): """FInd maximum value and index in a column of data AnalysisFile.max(column) """ col=self.find_col(column) return self.data[:, col].max(), self.data[:, col].argmax() def min(self, column): """FInd minimum value and index in a column of data AnalysisFile.min(column) """ col=self.find_col(column...
def curve_fit(self, func, xcol, ycol, p0=None, sigma=None, bounds=lambda x, y: True ): """General curve fitting function passed through from numpy AnalysisFile.Curve_fit(fitting function, x-column,y_column, initial parameters=None, weighting=None, bounds function) The fitting function should have prototype y=f(x,p[0...
class DataFile:
class DataFile(object):
def __parseFolder(self): path="C:/Documents and Settings/pymn/workspace/Stonerlab/src/folder/run1" # insert the path to the directory of interest dirList=os.listdir(path) for fname in dirList: print(fname)
elif self.__typeFloat.find('t')>-1:
elif self.__typeFloat.find(t)>-1:
def __parse_metadata(self, key, value): """Parse the metadata string, removing the type hints into a separate dictionary from the metadata Uses the typehint to set the type correctly in the dictionary """ m=self.__regexGetType.search(key) k= m.group(1) t= m.group(2) if self.__typeInteger.find(t)>-1: value = int(value)...
elif self.__typeBoolean.find('t')>-1:
elif self.__typeBoolean.find(t)>-1:
def __parse_metadata(self, key, value): """Parse the metadata string, removing the type hints into a separate dictionary from the metadata Uses the typehint to set the type correctly in the dictionary """ m=self.__regexGetType.search(key) k= m.group(1) t= m.group(2) if self.__typeInteger.find(t)>-1: value = int(value)...
self.__parse_metadata(row[0].split('=')[0], row[0].split('=')[1])
md=row[0].split('=') self.__parse_metadata(md[0], md[1])
def __parse_data(self): """Internal function to parse the tab deliminated text file """ reader = csv.reader(open(self.filename, "rb"), delimiter='\t', quoting=csv.QUOTE_NONE) row=reader.next() assert row[0]=="TDI Format 1.5" # Bail out if not the correct format self.data=numpy.array([]) headers = row[1:len(row)] maxcol...
request_uri = wsgi_request_uri( environ )
request_uri = sub( r'([^:])/+', r'\1/', sub( r'(\?|
def application( environ, start_response ): global request_method, request_uri, request_uri_parts, post_data, __start_response request_method = environ[ 'REQUEST_METHOD' ] request_uri = wsgi_request_uri( environ ) request_uri_parts = request_uri.rstrip( '/' ).split( '/' )[ 3 : ] post_data = FieldStorage( fp = environ[ ...
_context = self.context req = _context.request_uri_parts[ 0 ]
req = self.context.request_uri_parts[ 0 ]
def __call__( self ): _context = self.context req = _context.request_uri_parts[ 0 ] if req == 'metadata': return _context.response( 200, resources.load_metadata(), 'application/vnd.google-earth.kml+xml' ) else: return _context.response( 200, resources.load_image( int( req ) ), 'image/jpeg' )
return _context.response( 200, resources.load_metadata(), 'application/vnd.google-earth.kml+xml' )
return self.context.response( 200, resources.load_metadata(), 'application/vnd.google-earth.kml+xml' )
def __call__( self ): _context = self.context req = _context.request_uri_parts[ 0 ] if req == 'metadata': return _context.response( 200, resources.load_metadata(), 'application/vnd.google-earth.kml+xml' ) else: return _context.response( 200, resources.load_image( int( req ) ), 'image/jpeg' )
return _context.response( 200, resources.load_image( int( req ) ), 'image/jpeg' )
return self.context.response( 200, resources.load_image( int( req ) ), 'image/jpeg' )
def __call__( self ): _context = self.context req = _context.request_uri_parts[ 0 ] if req == 'metadata': return _context.response( 200, resources.load_metadata(), 'application/vnd.google-earth.kml+xml' ) else: return _context.response( 200, resources.load_image( int( req ) ), 'image/jpeg' )
return response( 400, 'No application specified in "map" (uri {0})'.format( request_uri( environ ) ) ) if not rup and not request_uri( environ ).endswith( '/' ): return response( 400, 'Missing trailing / for "{0}" (uri {1})'.format( app, request_uri( environ ) ) )
return response( 400, 'No application specified in "map" (uri {0})'.format( request_uri ) ) if not rup and not request_uri.endswith( '/' ): return response( 400, 'Missing trailing / for "{0}" (uri {1})'.format( app, request_uri ) )
def handle_map(): rup = request_uri_parts try: app = rup.pop( 0 ) except IndexError: return response( 400, 'No application specified in "map" (uri {0})'.format( request_uri( environ ) ) ) if not rup and not request_uri( environ ).endswith( '/' ): return response( 400, 'Missing trailing / for "{0}" (uri {1})'.format( ap...
return static( path.join( 'map', app, *res ) )
return static( '/'.join( [ app ] + res ) )
def handle_map(): rup = request_uri_parts try: app = rup.pop( 0 ) except IndexError: return response( 400, 'No application specified in "map" (uri {0})'.format( request_uri( environ ) ) ) if not rup and not request_uri( environ ).endswith( '/' ): return response( 400, 'Missing trailing / for "{0}" (uri {1})'.format( ap...
def application( _environ, _start_response ): global environ, start_response, request_method, request_uri_parts, post_data, request_uri, stop environ = _environ start_response = _start_response
def application( environ, start_response ): global __start_response, request_method, request_uri_parts, post_data, request_uri, stop __start_response = start_response
def application( _environ, _start_response ): global environ, start_response, request_method, request_uri_parts, post_data, request_uri, stop environ = _environ start_response = _start_response request_method = environ[ 'REQUEST_METHOD' ] request_uri = wsgi_request_uri( environ ) request_uri_parts = request_uri.rstrip(...
return response( 400, 'No application specified (uri {0})'.format( request_uri( environ ) ) )
return response( 400, 'No application specified (uri {0})'.format( request_uri ) )
def application( _environ, _start_response ): global environ, start_response, request_method, request_uri_parts, post_data, request_uri, stop environ = _environ start_response = _start_response request_method = environ[ 'REQUEST_METHOD' ] request_uri = wsgi_request_uri( environ ) request_uri_parts = request_uri.rstrip(...
return static( path.join( *request_uri_parts ) )
return static( '/'.join( request_uri_parts ) )
def application( _environ, _start_response ): global environ, start_response, request_method, request_uri_parts, post_data, request_uri, stop environ = _environ start_response = _start_response request_method = environ[ 'REQUEST_METHOD' ] request_uri = wsgi_request_uri( environ ) request_uri_parts = request_uri.rstrip(...
start_response( '{0} {1}'.format( status, HTTP_CODES[ status ] ), [ ( 'Content-type', content_type ) ] )
__start_response( '{0} {1}'.format( status, HTTP_CODES[ status ] ), [ ( 'Content-type', content_type ) ] )
def response( status = 200, data = '', content_type = 'text/plain; charset=utf-8' ): start_response( '{0} {1}'.format( status, HTTP_CODES[ status ] ), [ ( 'Content-type', content_type ) ] ) if isinstance( data, str ): data = [ data ] return data
firstTwo = atomSiteType[:2]
symLength = min(len(atomSiteType),2) firstTwo = atomSiteType[:symLength]
def getAtomSymbol(self, values): try: atomSiteType = values['_atom_site_type_symbol'] # have to add this in at the start for inelastic Atoms to get all inferred properties except: try: atomSiteType = values['_atom_site_label'] # have to add this in at the start for inelastic Atoms to get all inferred properties except:...
for i in range(2):
for i in range(symLength):
def getAtomSymbol(self, values): try: atomSiteType = values['_atom_site_type_symbol'] # have to add this in at the start for inelastic Atoms to get all inferred properties except: try: atomSiteType = values['_atom_site_label'] # have to add this in at the start for inelastic Atoms to get all inferred properties except:...
assert stru.getChemicalFormula()=='C2'
assert stru.getChemicalFormula()=='C_2'
def testChemicalFormulaPositionsSymbols(self): at1 = Atom('C', [0.333333333333333, 0.666666666666667, 0]) at2 = Atom('C', [0.666666666666667, 0.333333333333333, 0]) #at3 = Atom('H', [0, 0, 0]) stru = Structure( [ at1, at2], lattice=Lattice(3.8, 3.8, 5.6, 90, 90, 120) ) assert stru.getChemicalFormula()=='C2' #self.asse...
print "here's the lattice", stru.lattice.base
def testChemicalFormulaPositionsSymbols(self): at1 = Atom('C', [0.333333333333333, 0.666666666666667, 0]) at2 = Atom('C', [0.666666666666667, 0.333333333333333, 0]) #at3 = Atom('H', [0, 0, 0]) stru = Structure( [ at1, at2], lattice=Lattice(3.8, 3.8, 5.6, 90, 90, 120) ) assert stru.getChemicalFormula()=='C2' #self.asse...
self.assertEqual("Pb2+1", labels[0]) self.assertEqual("Pb2+4", labels[3])
def test_getLabels(self): """check Structure.getLabels() """ self.assertEqual(["C1", "C2"], self.stru.getLabels()) pbtefile = os.path.join(testdata_dir, 'PbTe.cif') self.stru.read(pbtefile, format='cif') labels = self.stru.getLabels() self.assertEqual("Pb2+1", labels[0]) self.assertEqual("Pb2+4", labels[3]) self.assert...
print badAtomPos,badSymOp
def test_symConsistent(self): result = self.stru2.symConsistent() assert result[0] is True self.stru3.sg = 225 result,badAtomPos,badSymOp = self.stru3.symConsistent() assert result is False print badAtomPos,badSymOp
print 'PbTe 225' print self.stru2.primitive_unitcell print 'graphite' print self.stru3.primitive_unitcell print
""
def test_PrimCellFind(self): print 'PbTe 225' print self.stru2.primitive_unitcell print 'graphite' print self.stru3.primitive_unitcell print
print self.stru2.getChemicalFormula() print print self.stru3.getChemicalFormula() print
""
def test_species(self): print self.stru2.getChemicalFormula() print print self.stru3.getChemicalFormula() print
atom = self.__class__( atype=inventory.element, xyz=inventory.xyz, label=inventory.label, occupancy=inventory.occupancy)
atom = self.__class__(atype=inventory.element)
def __restoreFromInventory__(self, inventory): # create a new atom with new propties atom = self.__class__( atype=inventory.element, xyz=inventory.xyz, label=inventory.label, occupancy=inventory.occupancy) # and use the copy constructer to reinitilize myself self.__init__(atom) return
application = webapp.WSGIApplication([('/', MainHandler)], debug=True)
application = webapp.WSGIApplication([('/', Vimm), ('/vimmwebgl', VimmWebgl), ('/vimmplugin', VimmPlugin)], debug=True)
def main(): application = webapp.WSGIApplication([('/', MainHandler)], debug=True) wsgiref.handlers.CGIHandler().run(application)
self.eau = ExpandAsymmetricUnit(self.spacegroup, corepos, coreUijs)
self.eau = ExpandAsymmetricUnit(self.spacegroup, corepos, coreUijs, eps = 0.001)
def _expandAsymmetricUnit(self): """Perform symmetry expansion of self.stru using self.spacegroup. This method updates data in stru and eau.
return abs(numpy.linalg.det(self._lattice))
return abs(numpy.linalg.det(self.base))
def getVolume(self): """ Returns the volume of the unit cell: |det(a1, a2, a3)|. Uses Numpy.linalg.""" return abs(numpy.linalg.det(self._lattice))
import os.path tailname = os.path.basename(filename) tailbase = os.path.splitext(tailname)[0] self.description = tailbase
self.generateDescription()
def read(self, filename, format='auto'): """Load structure from a file, any original data may become lost.
return chemFormRaw.trim()
return chemFormRaw.strip()
def getChemicalFormula(self): atoms = self counts = {} for atom in atoms: e = atom.symbol if e in counts: counts[e]+=1 else: counts[e]=1 continue elems = counts.keys() elems.sort() chemFormRaw = ''.join( '%s_%s ' % (e, counts[e]) for e in elems ) return chemFormRaw.trim()