rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
sock.send(msg) if i == 50: | if i != 50: sock.send(msg) else: | def tx(sock): for i in range(1, 101): msg = "test %s" % i sock.send(msg) if i == 50: sock.send('test LAST') sleep() sock.send('done DONE') |
api.sleep(0) | def test_025_accept_errors(self): api.kill(self.killer) listener = greensocket.socket() listener.bind(('localhost', 0)) # NOT calling listen, to trigger the error self.port = listener.getsockname()[1] self.killer = api.spawn( wsgi.server, listener, self.site, max_size=128, log=self.logfile) old_stderr = sys.stderr try:... | |
except SYSTEM_EXCEPTIONS: | except self.SYSTEM_EXCEPTIONS: | def remove_descriptor(self, fileno): for lcontainer in self.listeners.itervalues(): l_list = lcontainer.pop(fileno, None) for listener in l_list: try: listener.cb.delete() except SYSTEM_EXCEPTIONS: raise except: traceback.print_exc() |
"""Generate a new pool item. In order for the pool to function, either this method must be overriden in a subclass or pool must be created with `create`=callable argument. It accepts no arguments and returns a single instance of whatever thing the pool is supposed to contain. | """Generate a new pool item. In order for the pool to function, either this method must be overriden in a subclass or the pool must be constructed with the `create` argument. It accepts no arguments and returns a single instance of whatever thing the pool is supposed to contain. | def create(self): """Generate a new pool item. In order for the pool to function, either this method must be overriden in a subclass or pool must be created with `create`=callable argument. It accepts no arguments and returns a single instance of whatever thing the pool is supposed to contain. |
class test(unittest.TestCase): | def run_and_check(run_client): w = run_interaction(run_client=run_client) if w(): print pformat(gc.get_referrers(w())) for x in gc.get_referrers(w()): print pformat(x) for y in gc.get_referrers(x): print '-', pformat(y) raise AssertionError('server should be dead by now') | |
def test_clean_exit(self): run_and_check(True) run_and_check(True) | def test_clean_exit(): run_and_check(True) run_and_check(True) | def test_clean_exit(self): run_and_check(True) run_and_check(True) |
def test_timeout_exit(self): run_and_check(False) run_and_check(False) | def test_timeout_exit(): run_and_check(False) run_and_check(False) | def test_timeout_exit(self): run_and_check(False) run_and_check(False) |
e = esend(meth,*args,**kwargs) | my_thread = threading.currentThread() if my_thread in _threads: return meth(*args, **kwargs) e = esend(meth, *args, **kwargs) | def execute(meth,*args, **kwargs): """ Execute *meth* in a Python thread, blocking the current coroutine/ greenthread until the method completes. The primary use case for this is to wrap an object or module that is not amenable to monkeypatching or any of the other tricks that Eventlet uses to achieve cooperative yiel... |
_threads = {} | _threads = set() | def __nonzero__(self): return bool(self._obj) |
_threads[i] = threading.Thread(target=tworker) _threads[i].setDaemon(True) _threads[i].start() | t = threading.Thread(target=tworker) t.setDaemon(True) t.start() _threads.add(t) | def setup(): global _rfile, _wfile, _threads, _coro, _setup_already, _reqq, _rspq if _setup_already: return else: _setup_already = True try: _rpipe, _wpipe = os.pipe() _wfile = os.fdopen(_wpipe,"w",0) _rfile = os.fdopen(_rpipe,"r",0) ## Work whether or not wrap_pipe_with_coroutine_pipe was called if not isinstance(_rfi... |
length -= len(response[-1]) self.position += len(response[-1]) | last_read = len(response[-1]) if last_read == 0: break length -= last_read self.position += last_read | def _chunked_read(self, rfile, length=None): if self.wfile is not None: ## 100 Continue self.wfile.write(self.wfile_line) self.wfile = None self.wfile_line = None |
except ImportError: | except (ImportError, NotImplementedError): | def setup(): global _rfile, _wfile, _threads, _coro, _setup_already, _reqq, _rspq if _setup_already: return else: _setup_already = True try: _rpipe, _wpipe = os.pipe() _wfile = greenio.GreenPipe(_wpipe, 'wb', 0) _rfile = greenio.GreenPipe(_rpipe, 'rb', 0) except ImportError: # This is Windows compatibility -- use a soc... |
listener = eventlet.listen(('localhost', 7000)) | listener = eventlet.listen(('127.0.0.1', 7000)) | def dispatch(environ, start_response): """ This resolves to the web page or the websocket depending on the path.""" if environ['PATH_INFO'] == '/data': return handle(environ, start_response) else: start_response('200 OK', [('content-type', 'text/html')]) return [open(os.path.join( os.path.dirname(__file__), 'websocket.... |
DefaultErrorHandler(), HTTPBasicAuthHandler(passwordManager)) | DefaultErrorHandler(), ContextualBasicAuthHandler(passwordManager)) | def get(self, url, username=None, password=None, **kwargs): |
DefaultErrorHandler(), HTTPBasicAuthHandler(passwordManager)) | DefaultErrorHandler(), ContextualBasicAuthHandler(passwordManager)) | def delete(self, url, username=None, password=None, **kwargs): |
DefaultErrorHandler(), HTTPBasicAuthHandler(passwordManager)) | DefaultErrorHandler(), ContextualBasicAuthHandler(passwordManager)) | def put(self, url, payload, contentType, username=None, password=None, **kwargs): |
DefaultErrorHandler(), HTTPBasicAuthHandler(passwordManager)) | DefaultErrorHandler(), ContextualBasicAuthHandler(passwordManager)) | def post(self, url, payload, contentType, username=None, password=None, **kwargs): |
propertyValue = parsePropValue( node.getElementsByTagNameNS(CMIS_NS, 'value')[0].childNodes[0].data, node.localName) | valNodeList = node.getElementsByTagNameNS(CMIS_NS, 'value') if (len(valNodeList) == 1): propertyValue = parsePropValue(valNodeList[0]. childNodes[0].data, node.localName) else: propertyValue = [] for valNode in valNodeList: propertyValue.append(parsePropValue(valNode. childNodes[0].data, node.localName)) | def getProperties(self): |
if isinstance(propValue, CmisId): | propType = type(propValue) isList = False if (propType == list): propType = type(propValue[0]) isList = True if (propType == CmisId): | def _getEntryXmlDoc(self, properties=None, contentFile=None, contentType=None, contentEncoding=None): |
propValueStr = propValue elif isinstance(propValue, str): | if isList: propValueStrList = [] for val in propValue: propValueStrList.append(val) else: propValueStrList = [propValue] elif (propType == str): | def _getEntryXmlDoc(self, properties=None, contentFile=None, contentType=None, contentEncoding=None): |
propValueStr = propValue elif isinstance(propValue, datetime.datetime): | if isList: propValueStrList = [] for val in propValue: propValueStrList.append(val) else: propValueStrList = [propValue] elif (propType == datetime.datetime): | def _getEntryXmlDoc(self, properties=None, contentFile=None, contentType=None, contentEncoding=None): |
propValueStr = propValue.isoformat() elif isinstance(propValue, bool): | if isList: propValueStrList = [] for val in propValue: propValueStrList.append(val.isoformat()) else: propValueStrList = [propValue.isoformat()] elif (propType == bool): | def _getEntryXmlDoc(self, properties=None, contentFile=None, contentType=None, contentEncoding=None): |
propValueStr = str(propValue).lower() elif isinstance(propValue, int): | if isList: propValueStrList = [] for val in propValue: propValueStrList.append(str(val).lower()) else: propValueStrList = [str(propValue).lower()] elif (propType == int): | def _getEntryXmlDoc(self, properties=None, contentFile=None, contentType=None, contentEncoding=None): |
propValueStr = str(propValue) elif isinstance(propValue, float): | if isList: propValueStrList = [] for val in propValue: propValueStrList.append(str(val)) else: propValueStrList = [str(propValue)] elif (propType == float): | def _getEntryXmlDoc(self, properties=None, contentFile=None, contentType=None, contentEncoding=None): |
propValueStr = str(propValue) | if isList: propValueStrList = [] for val in propValue: propValueStrList.append(str(val)) else: propValueStrList = [str(propValue)] | def _getEntryXmlDoc(self, properties=None, contentFile=None, contentType=None, contentEncoding=None): |
valElement = entryXmlDoc.createElementNS(CMIS_NS, 'cmis:value') val = entryXmlDoc.createTextNode(propValueStr) valElement.appendChild(val) propElement.appendChild(valElement) | for val in propValueStrList: valElement = entryXmlDoc.createElementNS(CMIS_NS, 'cmis:value') valText = entryXmlDoc.createTextNode(val) valElement.appendChild(valText) propElement.appendChild(valElement) | def _getEntryXmlDoc(self, properties=None, contentFile=None, contentType=None, contentEncoding=None): |
url = url[:url.find("?")] | u = list(urlparse(url)) u[4] = '&'.join([p for p in u[4].split('&') if not p.startswith('depth=')]) url = urlunparse(u) | def getDescendantsLink(self): |
searchFolder = self._repo.getObjectByPath( \ "/".join([TEST_ROOT_PATH, testFolderName, parentFolderName, subFolderName]), \ | searchFolder = self._repo.getObjectByPath(subFolderPath, \ | def testPropertyFilter(self): '''Test the properties filter''' # names of folders and test docs testFolderName = self._testFolder.getName() parentFolderName = 'testGetObjectByPath folder' subFolderName = 'subfolder' |
print "%s" % (object) | def addObject(self, object): self.objects.append(object) | |
print "Received object %s" % object | def pushObject(self, object): print "Received object %s" % object """Objects are pushed here form the object editor implementation """ self.objectReceiver.addObject(object) #self.emit(self.objectReceived) | |
selected = rules.selectedIndexes()[0] selrow = selected.row() | row = 0 if len(rules.selectedIndexes())>0: selected = rules.selectedIndexes()[0] row = selected.row() | def handle_ruleadd(self): rules = self.main.listrules selected = rules.selectedIndexes()[0] selrow = selected.row() newrule = rule.Rule(name="new_rule") self.rulemod.addRuleBefore(0, newrule) |
self.rulemod.addRuleBefore(0, newrule) | self.rulemod.addRuleBefore(row, newrule) | def handle_ruleadd(self): rules = self.main.listrules selected = rules.selectedIndexes()[0] selrow = selected.row() newrule = rule.Rule(name="new_rule") self.rulemod.addRuleBefore(0, newrule) |
if index < 0 or index >= self.rowCount(): return self.rules.insert(index, rule) | if index == 0: self.rules.insert(index, rule) elif index < 0 or index >= self.rowCount(): return else: self.rules.insert(index, rule) | def addRuleBefore(self, index, rule): if index < 0 or index >= self.rowCount(): return self.rules.insert(index, rule) self.reset() |
m4 = multMatrix(rotMat, m4) | m4 = multMatrix(m4, rotMat) | def getAnkiSkeletonScript(skeleton, flipYZ): ftxt = "" # file text # write the file boneNames = skeleton.bones.keys() boneNames.sort() # the bones are written in alpabetical order ftxt += str(len(boneNames)) + "\n" for boneName in boneNames: bone = skeleton.bones[boneName] # name ftxt += "\"" + bone.name + "\"\n" ... |
ankiVerts[nid].boneIds = copy.copy(ankiVerts[cid].boneIds) ankiVerts[nid].weights = copy.copy(ankiVerts[cid].weights) | ankiVerts[nid].boneIds = deepcopy(ankiVerts[cid].boneIds) ankiVerts[nid].weights = deepcopy(ankiVerts[cid].weights) | def updateAnkiVertsWithBoneWeights(mesh, skeleton, ankiVerts): boneNames = skeleton.bones.keys() boneNames.sort() # init text ftxt = "" # link the vert groups to the bone ids vgroup2boneId = {} # we give the vgroup name and we get the bone's id in the skeleton vgroupNames = mesh.getVertGroupNames() for vgroupName ... |
print """-module(rabbit_framing). -include("rabbit_framing.hrl"). | module = "rabbit_framing_amqp_%d_%d" % (spec.major, spec.minor) if spec.revision != '0': module = "%s_%d" % (module, spec.revision) if module == "rabbit_framing_amqp_8_0": module = "rabbit_framing_amqp_0_8" print "-module(%s)." % module print """-include("rabbit_framing.hrl"). | def genAmqpException(c,v,cls): n = erlangConstantName(c) print 'amqp_exception(?%s) -> %s;' % \ (n, n.lower()) |
ipIsr.saturationCorrection(exposure, saturation, defaultFwhm, growSaturated = growSaturated) | exposure.writeFits('hack1.fits') ipIsr.saturationDetection(exposure, saturation, growSaturated = growSaturated, doMask = True, maskName='SAT') ipIsr.saturationInterpolation(exposure, defaultFwhm, maskName = 'SAT') exposure.writeFits('hack2.fits') | def testSaturation(self): saturation = 1000 saturationKeyword = self.policy.getString('saturationPolicy.saturationKeyword') growSaturated = self.policy.getInt('saturationPolicy.growSaturated') defaultFwhm = self.policy.getDouble('defaultFwhm') |
if (j == 4 or j == 16) and (i == 8 or i == 10): | if (i,j) in [(8,4),(8,16),(10,4),(10,16)]: self.assertEqual(mi.getMask().get(i,j) & bitmaskInterp, 0) self.assertEqual(mi.getMask().get(i,j) & bitmaskSat, 0) elif (j == 4 or j == 16) and (i == 8 or i == 10): | def testSaturation(self): saturation = 1000 saturationKeyword = self.policy.getString('saturationPolicy.saturationKeyword') growSaturated = self.policy.getInt('saturationPolicy.growSaturated') defaultFwhm = self.policy.getDouble('defaultFwhm') |
for i in range(10): satmask.set(int(i*satmask.getWidth()/10.), int(i*satmask.getHeight()/10.), satbmask) badmask.set(badmask.getWidth() - 1 - int(i*badmask.getWidth()/10.), badmask.getHeight() - 1 - int(i*badmask.getHeight()/10.), badbmask) mask |= satmask mask |= badmask | def setUp(self): darr = [] mi = afwImage.MaskedImageF(10,10) mi.set(110, 0x0, 1) self.bbox = afwImage.BBox(afwImage.PointI(0,0), 1, 10) self.dbox = afwImage.BBox(afwImage.PointI(1,0), 9, 10) mask = afwImage.MaskU(mi.getMask(), self.dbox) satmask = afwImage.MaskU(mask.getDimensions(),0x0) badmask = afwImage.MaskU(mask.g... | |
self.assertEqual(metadata.get('imageMin'), 0.) self.assertAlmostEqual(metadata.get('imageSigma'), 23.54591, 5) self.assertEqual(metadata.get('imageMax'), 81.0) | self.assertEqual(metadata.get('imageMin'), 2.) self.assertAlmostEqual(metadata.get('imageSigma'), 22.93223, 5) self.assertEqual(metadata.get('imageMax'), 79.0) | def testCcdSdqa(self): nsat = 0 exposure = afwImage.ExposureF(afwImage.MaskedImageF(self.mi, self.dbox)) ipIsr.calculateSdqaCcdRatings(exposure) metadata = exposure.getMetadata() self.assertEqual(metadata.get('imageClipMean4Sig3Pass'), 40.5) self.assertEqual(metadata.get('imageMedian'), 40.5) self.assertEqual(metadata.... |
float(metadata.get("MJD-OBS"))) print refcoord.getRa(afwCoord.DEGREES), refcoord.getDec(afwCoord.DEGREES) | epoch) | def convertImageForIsr(exposure, imsim=False): if not isinstance(exposure, afwImage.ExposureU): raise Exception("ipIsr.convertImageForIsr: Expecting Uint16 image. Got\ %s."%(exposure.__repr__())) newexposure = exposure.convertF() amp = cameraGeom.cast_Amp(exposure.getDetector()) mi = newexposure.getMaskedImage() var =... |
print nrefcoord.getRa(afwCoord.DEGREES), nrefcoord.getDec(afwCoord.DEGREES) wcs.setSkyOrigin(nrefcoord.getRa(afwCoord.DEGREES), nrefcoord.getDec(afwCoord.DEGREES)) newexposure.setWcs(wcs) | crval = afwGeom.PointD() crval.setX(nrefcoord.getRa(afwCoord.DEGREES)) crval.setY(nrefcoord.getDec(afwCoord.DEGREES)) newwcs = afwImage.Wcs(crval, wcs.getPixelOrigin(), wcs.getCDMatrix()) newexposure.setWcs(newwcs) | def convertImageForIsr(exposure, imsim=False): if not isinstance(exposure, afwImage.ExposureU): raise Exception("ipIsr.convertImageForIsr: Expecting Uint16 image. Got\ %s."%(exposure.__repr__())) newexposure = exposure.convertF() amp = cameraGeom.cast_Amp(exposure.getDetector()) mi = newexposure.getMaskedImage() var =... |
fileName = "../../afwdata/ImSim/imsim_%08d_%s_%s_C%02d_E000.fits.gz" % (self.frameId, raftId, sensorId, int(amp.getId().getSerial())) | ampTuple = amp.getId().getIndex() ampName = "C%d%d" % (ampTuple[1], ampTuple[0]) fileName = "%s/ImSim/processed/imsim_%08d_%s_%s_%s_E000.fits" % ( os.environ['AFWDATA_DIR'], self.frameId, raftId, sensorId, ampName) | def getFilename(self, ccd, amp, expType=None): """Return the filename of specified Ccd""" mat = re.search(r"^R:(\d),(\d)\s+S:(\d),(\d)\s*$", ccd.getId().getName()) if mat: raftId = "R%s%s" % (mat.group(1), mat.group(2)) sensorId = "S%s%s" % (mat.group(3), mat.group(4)) |
def foo(frameId=85751839, ccdName="R:2,3 S:1,1", geomPolicyFile="Full_STA_geom.paf", | def foo(frameId=85751839, ccdName="R:2,3 S:1,1", geomPolicyFile="tests/Full_STA_geom.paf", | def foo(frameId=85751839, ccdName="R:2,3 S:1,1", geomPolicyFile="Full_STA_geom.paf", isTrimmed=False, display=True): cif = ccdImageFactory(frameId) camera = getCamera(geomPolicyFile) raft = cameraGeomUtils.findRaft(camera, cameraGeomUtils.cameraGeom.Id(23,"R:2,3")) ccd = getCcd(raft, ccdName) if False: showAmps(camera,... |
foo() | foo(display=False) | def foo(frameId=85751839, ccdName="R:2,3 S:1,1", geomPolicyFile="Full_STA_geom.paf", isTrimmed=False, display=True): cif = ccdImageFactory(frameId) camera = getCamera(geomPolicyFile) raft = cameraGeomUtils.findRaft(camera, cameraGeomUtils.cameraGeom.Id(23,"R:2,3")) ccd = getCcd(raft, ccdName) if False: showAmps(camera,... |
imf = afwImage.ImageF(imagename) mymeta = afwImage.readMetadata(imagename) | mymeta = dafBase.PropertySet() imf = afwImage.ImageF(imagename, 0, mymeta) | def PersistImageU(imagename): imf = afwImage.ImageF(imagename) mymeta = afwImage.readMetadata(imagename) mask = afwImage.MaskU(imf.getDimensions()) mask.set(0) var = afwImage.ImageF(imf) mi = afwImage.makeMaskedImage(imf, mask, var) exp = afwImage.ExposureF(mi, afwImage.Wcs()) exp.setMetadata(mymeta) exp.writeFits("tes... |
"if ((([ENTRY]->data[[ENTRY]->offset_opcode] >> 3) & 0x7) == 2) msg.cpu->actv_state |= 2", | "if ((([ENTRY]->data[[ENTRY]->offset_opcode] >> 3) & 0x7) == 2) msg.cpu->intr_state |= 2", | def add_helper(l, flags, params): if "[ENTRY]" in params: flags.append("ENTRY") for x in l: name = reduce(lambda x,y: x.replace(y, "_"), "% ,", x.upper()) if "NO_OS" not in flags: name += "<[os]>" opcodes.append((x, flags, ["helper_%s(msg %s)"%(name, params and "," + params or "")])) |
("pop %"+x, ["ENTRY"], ["unsigned sel", "helper_POP<[os]>(msg, [ENTRY], &sel) || set_segment(msg, &msg.cpu->%s, sel)"%x, x == "ss" and "msg.cpu->actv_state |= 2" or ""]), | ("pop %"+x, ["ENTRY"], ["unsigned sel", "helper_POP<[os]>(msg, [ENTRY], &sel) || set_segment(msg, &msg.cpu->%s, sel)"%x, x == "ss" and "msg.cpu->intr_state |= 2" or ""]), | def add_helper(l, flags, params): if "[ENTRY]" in params: flags.append("ENTRY") for x in l: name = reduce(lambda x,y: x.replace(y, "_"), "% ,", x.upper()) if "NO_OS" not in flags: name += "<[os]>" opcodes.append((x, flags, ["helper_%s(msg %s)"%(name, params and "," + params or "")])) |
opcodes += [(x, [], ["cache->_fault = FAULT_%s"%(x.upper())]) for x in ["cpuid", "rdtsc", "rdmsr", "wrmsr"]] | opcodes += [(x, [], ["cache->send_message(CpuMessage::TYPE_%s)"%(x.upper())]) for x in ["cpuid", "rdtsc", "rdmsr", "wrmsr"]] | def add_helper(l, flags, params): if "[ENTRY]" in params: flags.append("ENTRY") for x in l: name = reduce(lambda x,y: x.replace(y, "_"), "% ,", x.upper()) if "NO_OS" not in flags: name += "<[os]>" opcodes.append((x, flags, ["cache->helper_%s(%s)"%(name, params or "")])) |
no_os = "BYTE" in flags or "NO_OS" in flags | no_os = ("BYTE" in flags or "NO_OS" in flags) and "HAS_OS" not in flags | def generate_functions(name, flags, snippet, enc, functions, l2): if not snippet: l2.append("UNIMPLEMENTED(this)") return if "ASM" in flags and not "asm volatile" in ";".join(snippet): snippet = ['asm volatile("'+ ";".join(snippet)+'")'] if "FPU" in flags: if "FPUNORESTORE" not in flags: snippet = ['fxrstor (%%eax... |
opcodes += [(x, [x[-1] == "b" and "BYTE"], [ | opcodes += [(x, [x[-1] == "b" and "BYTE", "HAS_OS"], [ | def print_code(code, functions): names = functions.keys() names.sort() for funcname in names: print """static void __attribute__((regparm(3))) %s(InstructionCache *cache, void *tmp_src, void *tmp_dst) { %s; }"""%(funcname, ";".join(functions[funcname])) print "int handle_code_byte(InstructionCacheEntry *entry, unsigne... |
out("\t%s = val;" % (r['set']['name'])) | target = r['set']['name'] | def writer_gen(r, out): if 'read-only' in r: return out("\nvoid %s_write(uint32_t val)\n{" % r['name']) if 'set' in r: out("\t%s = val;" % (r['set']['name'])) else: out("\t%s = val;" % r['name']) if 'callback' in r: out("\t%s()" % r['callback']) out("}") |
out("\t%s = val;" % r['name']) | target = r['name'] if 'w1c' in r: out("\t%s &= ~val;" % target) else: out("\t%s = val;" % target) | def writer_gen(r, out): if 'read-only' in r: return out("\nvoid %s_write(uint32_t val)\n{" % r['name']) if 'set' in r: out("\t%s = val;" % (r['set']['name'])) else: out("\t%s = val;" % r['name']) if 'callback' in r: out("\t%s()" % r['callback']) out("}") |
out("\t%s()" % r['callback']) | out("\t%s();" % r['callback']) | def writer_gen(r, out): if 'read-only' in r: return out("\nvoid %s_write(uint32_t val)\n{" % r['name']) if 'set' in r: out("\t%s = val;" % (r['set']['name'])) else: out("\t%s = val;" % r['name']) if 'callback' in r: out("\t%s()" % r['callback']) out("}") |
if "FPU" in flags: snippet = ["if (cache->_cpu->cr0 & 0xc) EXCEPTION(cache, 0x7, 0)", 'asm volatile("fxrstor (%%eax);'+ ";".join(snippet)+'; fxsave (%%eax);" : "+d"(tmp_src), "+c"(tmp_dst) : "a"(cache->_fpustate))'] | if "FPU" in flags: if "FPUNORESTORE" not in flags: snippet = ['fxrstor (%%eax)'] + snippet snippet = ['if (cache->_cpu->cr0 & 0xc) EXCEPTION(cache, 0x7, 0)', 'asm volatile("' + ';'.join(snippet)+'; fxsave (%%eax);" : "+d"(tmp_src), "+c"(tmp_dst) : "a"(cache->_fpustate))'] | def generate_functions(name, flags, snippet, enc, functions, l2): if not snippet: l2.append("UNIMPLEMENTED(this)") return if "ASM" in flags and not "asm volatile" in ";".join(snippet): snippet = ['asm volatile("'+ ";".join(snippet)+'")'] if "FPU" in flags: snippet = ["if (cache->_cpu->cr0 & 0xc) EXCEPTION(cache... |
opcodes += [(x, ["FPU", "NO_OS"], [x]) for x in ["fninit"]] | opcodes += [(x, ["FPU", "FPUNORESTORE", "NO_OS"], [x]) for x in ["fninit"]] | def add_helper(l, flags, params): for x in l: name = reduce(lambda x,y: x.replace(y, "_"), "% ,", x.upper()) if "NO_OS" not in flags: name += "<[os]>" opcodes.append((x, flags, ["cache->helper_%s(%s)"%(name, params or "")])) |
add_helper(["mov %cr0,%edx", "mov %edx,%cr0"], ["MODRM", "DROP1", "REGONLY", "NO_OS"], "") add_helper(["ltr", "lldt", "lmsw"], ["NO_OS", "OS1", "DIRECTION"], "*reinterpret_cast<unsigned short *>(tmp_src)") add_helper(["hlt", "sti", "cli", "clts", "int3", "into", "wbinvd", ... | add_helper(["mov %cr0,%edx", "mov %edx,%cr0"], ["MODRM", "DROP1", "REGONLY", "NO_OS", "CPL0"], "") add_helper(["ltr", "lldt"], ["NO_OS", "OS1", "DIRECTION"], "*reinterpret_cast<unsigned short *>(tmp_src)") add_helper(["lmsw"], ... | def add_helper(l, flags, params): for x in l: name = reduce(lambda x,y: x.replace(y, "_"), "% ,", x.upper()) if "NO_OS" not in flags: name += "<[os]>" opcodes.append((x, flags, ["cache->helper_%s(%s)"%(name, params or "")])) |
def App(tenv, name, SOURCES = [], INCLUDE = [], LIBS = ['nova'], | def App(tenv, name, SOURCES = [], INCLUDE = [], LIBS = [ 'string' ], | def App(tenv, name, SOURCES = [], INCLUDE = [], LIBS = ['nova'], LINKSCRIPT = None): env = LibEnv(tenv, INCLUDE) env = AppEnv(env, LIBS) if not LINKSCRIPT: LINKSCRIPT = "%s.ld" % name return env.Link(output + '/apps/%s.nul' % name, SOURCES, linkscript = LINKSCRIPT) |
"<p>GPS Time(Secs)", (entry.tm /100),\ | "<p>GPS Time(Secs)", (entry.tm /1000),\ | def write_flight_vectors(log_book,origin, filename) : print >> filename, """ <Folder> <open>0</open> <name>Pitch/Roll/Yaw""", print >> filename, "</name>" counter = 0 print >> filename, "<description>Model plane plotted for each second of flight</description>" for entry in log_book.entries : counter += 1 line1 = "%f," ... |
entry.pitch = (asin(entry.rmat7 / 16384.0) / (2*pi)) * 360 entry.roll = (asin(entry.rmat6 / 16385.0) / (2*pi)) * 360 | safe_rmat7 = entry.rmat7 if safe_rmat7 > 16384 : safe_rmat7 = 16384 print "Warning: rmat7 greater than abs(16384) at time of week ", entry.tm if safe_rmat7 < -16384 : safe_rmat7 = -16384 print "Warning: rmat7 greater than 16384 at time of week ", entry.tm safe_rmat6 = entry.rmat6 if safe_rmat6 > 16384 : safe_rmat6 = 16... | def calculate_headings_pitch_roll(log_book) : for entry in log_book.entries : entry.lon = entry.longitude / 10000000 # degrees entry.lat = entry.latitude / 10000000 # degrees entry.alt = entry.altitude / 100 # meters absolute # If using Ardustation, then roll and pitch already set from telemetry if log_book.... |
def write_placemark_preamble_auto(open_waypoint,current_waypoint,filename): | def write_placemark_preamble_auto(open_waypoint,current_waypoint,filename,log_book): | def write_placemark_preamble_auto(open_waypoint,current_waypoint,filename): waypoints_open = 6 # The no. of waypoints to enable "on" in GE # User can switch on other waypoints in places window of GE # Later print >> filename, """ <Placemark> <name>""", print >> filename, "Towards Waypoint: ", current_waypoint, print >... |
<tessellate>1</tessellate> <altitudeMode>absolute</altitudeMode> <coordinates>""" | <tessellate>1</tessellate>""" if log_book.ardustation_pos == "Recorded" : print >> filename, """ <altitudeMode>relativeToGround</altitudeMode>""" else: print >> filename, """ <altitudeMode>absolute</altitudeMode>""" print >> filename, """ <coordinates>""" | def write_placemark_preamble_auto(open_waypoint,current_waypoint,filename): waypoints_open = 6 # The no. of waypoints to enable "on" in GE # User can switch on other waypoints in places window of GE # Later print >> filename, """ <Placemark> <name>""", print >> filename, "Towards Waypoint: ", current_waypoint, print >... |
write_placemark_preamble_auto(open_waypoint,current_waypoint,filename) | write_placemark_preamble_auto(open_waypoint,current_waypoint,filename,log_book) | def write_flight_path(log_book,flight_origin, filename): write_flight_path_preamble(log_book,filename) write_T3_waypoints(filename,flight_origin,log_book) first_waypoint = True open_waypoint = True # We only open the first few waypoints in GE - to keep graphic clean max_waypoints_to_open = 9 print >> filename, ""... |
flight_pos = re.sub(".[tT][xX][tT]$",".kml", flight_log_name) | match = re.match(".[tT][xX][tT]$",flight_log_name) if match : flight_pos = re.sub(".[tT][xX][tT]$",".kml", flight_log_name) match = re.match(".log$",flight_log_name) if match : flight_pos = re.sub(".log",".kml", flight_log_name) else : flight_pos = re.sub("$",".kml", flight_log_name) | def create_kmz(flight_log_dir,flight_log_name): flight_log = os.path.join(flight_log_dir, flight_log_name) #flight telelemetry file must end in .txt or .TXT for this to work flight_pos = re.sub(".[tT][xX][tT]$",".kml", flight_log_name) flight_pos_kml = os.path.join(flight_log_dir, flight_pos) f = open(flight_log, 'r') ... |
match = re.match(".[tT][xX][tT]$",flight_log_name) if match : flight_kmz = re.sub(".[tT][xX][tT]$",".kmz", flight_log_name) match = re.match(".log$",line) if match : flight_kmz = re.sub(".log",".kmz", flight_log_name) else : flight_kmz = re.sub("$",".kmz", flight_log_name) | def create_kmz(flight_log_dir,flight_log_name): flight_log = os.path.join(flight_log_dir, flight_log_name) #flight telelemetry file must end in .txt or .TXT for this to work flight_pos = re.sub(".[tT][xX][tT]$",".kml", flight_log_name) flight_pos_kml = os.path.join(flight_log_dir, flight_pos) f = open(flight_log, 'r') ... | |
initLat = origin.latitude / 10000000 initLon = origin.longitude / 10000000 | initLat = origin.latitude / 10000000.0 initLon = origin.longitude / 10000000.0 | def write_T3_waypoints(filename,origin,log_book) : # note origin.latitude and origin.longitude are straight from log of telemetry # so they are expressed in degrees * 10,000,000 initLat = origin.latitude / 10000000 initLon = origin.longitude / 10000000 corner = 100 # easy way to describe location of waypoints, e.g. 1... |
wp_dist_in_lat = (corner * convert) wp_dist_in_lon = (corner * convert) / (acos(((initLat)/360)*2*pi)) | def write_T3_waypoints(filename,origin,log_book) : # note origin.latitude and origin.longitude are straight from log of telemetry # so they are expressed in degrees * 10,000,000 initLat = origin.latitude / 10000000 initLon = origin.longitude / 10000000 corner = 100 # easy way to describe location of waypoints, e.g. 1... | |
[((corner * convert)+initLat,((corner * convert) /(acos(((initLat) / 360)*2*pi))) + initLon), \ ((corner * convert)+initLat,((-corner * convert) /(acos(((initLat) / 360)*2*pi))) + initLon), \ ((-corner * convert)+initLat,((corner * convert) /(acos(((initLat) / 360)*2*pi))) + initLon), \ ((-corner * convert)+initLat,((-... | [((corner * convert)+initLat,((corner * convert) /(cos(((initLat) / 360)*2*pi))) + initLon), \ ((corner * convert)+initLat,((-corner * convert)/(cos(((initLat) / 360)*2*pi))) + initLon), \ ((-corner * convert)+initLat,((corner * convert)/(cos(((initLat) / 360)*2*pi))) + initLon), \ ((-corner * convert)+initLat,((-corne... | def write_T3_waypoints(filename,origin,log_book) : # note origin.latitude and origin.longitude are straight from log of telemetry # so they are expressed in degrees * 10,000,000 initLat = origin.latitude / 10000000 initLon = origin.longitude / 10000000 corner = 100 # easy way to describe location of waypoints, e.g. 1... |
<name>T3 Competition Course</name> | <name>T3 Fig 8 Course</name> | def write_T3_waypoints(filename,origin,log_book) : # note origin.latitude and origin.longitude are straight from log of telemetry # so they are expressed in degrees * 10,000,000 initLat = origin.latitude / 10000000 initLon = origin.longitude / 10000000 corner = 100 # easy way to describe location of waypoints, e.g. 1... |
match = re.match(".[tT][xX][tT]$",flight_log_name) | match = re.match("\.[tT][xX][tT]$",flight_log_name) | def create_kmz(flight_log_dir,flight_log_name): flight_log = os.path.join(flight_log_dir, flight_log_name) match = re.match(".[tT][xX][tT]$",flight_log_name) # match a .txt file if match : #flight telelemetry file must end in .txt or .TXT for this to work flight_pos = re.sub(".[tT][xX][tT]$",".kml", flight_log_name) ma... |
flight_pos = re.sub(".[tT][xX][tT]$",".kml", flight_log_name) match = re.match(".log$",flight_log_name) | flight_pos = re.sub("\.[tT][xX][tT]$",".kml", flight_log_name) match = re.match("\.log$",flight_log_name) | def create_kmz(flight_log_dir,flight_log_name): flight_log = os.path.join(flight_log_dir, flight_log_name) match = re.match(".[tT][xX][tT]$",flight_log_name) # match a .txt file if match : #flight telelemetry file must end in .txt or .TXT for this to work flight_pos = re.sub(".[tT][xX][tT]$",".kml", flight_log_name) ma... |
flight_pos = re.sub(".log",".kml", flight_log_name) | flight_pos = re.sub("\.log",".kml", flight_log_name) | def create_kmz(flight_log_dir,flight_log_name): flight_log = os.path.join(flight_log_dir, flight_log_name) match = re.match(".[tT][xX][tT]$",flight_log_name) # match a .txt file if match : #flight telelemetry file must end in .txt or .TXT for this to work flight_pos = re.sub(".[tT][xX][tT]$",".kml", flight_log_name) ma... |
flight_kmz = re.sub(".[tT][xX][tT]$",".kmz", flight_log_name) match = re.match(".log$",line) | flight_kmz = re.sub("\.[tT][xX][tT]$",".kmz", flight_log_name) match = re.match("\.log$",line) | def create_kmz(flight_log_dir,flight_log_name): flight_log = os.path.join(flight_log_dir, flight_log_name) match = re.match(".[tT][xX][tT]$",flight_log_name) # match a .txt file if match : #flight telelemetry file must end in .txt or .TXT for this to work flight_pos = re.sub(".[tT][xX][tT]$",".kml", flight_log_name) ma... |
flight_kmz = re.sub(".log",".kmz", flight_log_name) | flight_kmz = re.sub("\.log",".kmz", flight_log_name) | def create_kmz(flight_log_dir,flight_log_name): flight_log = os.path.join(flight_log_dir, flight_log_name) match = re.match(".[tT][xX][tT]$",flight_log_name) # match a .txt file if match : #flight telelemetry file must end in .txt or .TXT for this to work flight_pos = re.sub(".[tT][xX][tT]$",".kml", flight_log_name) ma... |
flight_kmz = re.sub(".[tT][xX][tT]$",".kmz", flight_log_name) | def create_kmz(flight_log_dir,flight_log_name): flight_log = os.path.join(flight_log_dir, flight_log_name) match = re.match(".[tT][xX][tT]$",flight_log_name) # match a .txt file if match : #flight telelemetry file must end in .txt or .TXT for this to work flight_pos = re.sub(".[tT][xX][tT]$",".kml", flight_log_name) ma... | |
flight_csv = re.sub(".[tT][xX][tT]$",".csv", flight_log_name) | match = re.match("\.[tT][xX][tT]$",flight_log_name) if match : flight_csv = re.sub("\.[tT][xX][tT]$",".csv", flight_log_name) match = re.match("\.log$",line) if match : flight_csv = re.sub("\.log",".csv", flight_log_name) else : flight_csv = re.sub("$",".csv", flight_log_name) | def create_kmz(flight_log_dir,flight_log_name): flight_log = os.path.join(flight_log_dir, flight_log_name) match = re.match(".[tT][xX][tT]$",flight_log_name) # match a .txt file if match : #flight telelemetry file must end in .txt or .TXT for this to work flight_pos = re.sub(".[tT][xX][tT]$",".kml", flight_log_name) ma... |
if entry.status == "1111" : | match = re.match("^111",entry.status) if match : | def write_flight_path(log_book,flight_origin, filename): write_flight_path_preamble(log_book,filename) write_T3_waypoints(filename,flight_origin,log_book) first_waypoint = True open_waypoint = True # We only open the first few waypoints in GE - to keep graphic clean max_waypoints_to_open = 9 print >> filename, ""... |
self.send_sockets.remove(sock) | self.recv_sockets.remove(sock) | def testing_thread(self): log.debug("TestThread: Starting test thread.") data_recv = {} while True: with self.send_recv_cond: # Wait on send_recv_cond to stall while we're not waiting on # test sockets. while len(self.recv_sockets) + len(self.send_sockets) == 0: log.debug("TestThread: waiting for new test sockets.") s... |
return None | raise nxdomain(name) | def _lookup(self, address, query, timeout): name = str(query.name) type = query.type cls = dns.IN |
if router.last_tested > 0: log.debug("%s: Already tested.", router.nickname) | def circuit_build_thread(self): log = get_logger("torbel.Circuits") log.debug("Starting circuit builder thread.") | |
router.last_tested = time.time() | router.last_tested = int(time.time()) | def circuit_build_thread(self): log = get_logger("torbel.Circuits") log.debug("Starting circuit builder thread.") |
self.resp = "" | def __init__(self, proxy_host, proxy_port): socket.socket.__init__(self, socket.AF_INET, socket.SOCK_STREAM) self.peer_host = None self.peer_port = None self.proxy_port = proxy_port self.proxy_host = proxy_host | |
resp = self.recv(8) (status,) = struct.unpack('xBxxxxxx', resp) if status == 0x5a: return True return False | try: self.resp += self.recv(8 - len(self.resp)) except socket.error, e: if e.errno == errno.EINTR: return self.SOCKS4_INCOMPLETE if len(self.resp) < 8: return self.SOCKS4_INCOMPLETE else: (status,) = struct.unpack('xBxxxxxx', self.resp) if status == 0x5a: return self.SOCKS4_CONNECTED else: return self.SOCKS4_FAILED | def complete_handshake(self): resp = self.recv(8) (status,) = struct.unpack('xBxxxxxx', resp) # 0x5A == success; 0x5B == failure/rejected if status == 0x5a: return True |
tests = {} results = [] | test_data = {} | def exit_test(self, router): tests = {} results = [] test_ports = [] recv_sockets = [] self.test_exit = router exit = router.router # FIXME |
if not exit.will_exit_to(config.test_host, port): results.append((port, EXIT_REJECTED)) else: | if exit.will_exit_to(config.test_host, port): | def exit_test(self, router): tests = {} results = [] test_ports = [] recv_sockets = [] self.test_exit = router exit = router.router # FIXME |
tests[port] = {"port": port, "data": '%08x' % random.randint(0, 0xffffffff)} | test_data[port] = '%08x' % random.randint(0, 0xffffffff) if len(test_ports) == 0: log.debug("%s: no testable ports.") router.last_tested = int(time.time()) return | def exit_test(self, router): tests = {} results = [] test_ports = [] recv_sockets = [] self.test_exit = router exit = router.router # FIXME |
try: pending_sockets = bind_list + send_sockets_pending log.debug("%s: Waiting on %d sockets", exit.nickname, len(pending_sockets)) while len(pending_sockets) > 0: ready, ignore, me = \ select.select(pending_sockets, [], [], 60) log.debug("%s: %d sockets are ready.", exit.nickname, len(ready)) for s in ready: if s in ... | pending_sockets = bind_list + send_sockets_pending while len(pending_sockets) > 0: ready, ignore, me = select.select(pending_sockets, [], [], 5) if len(ready) == 0: log.debug("%s: select() timeout (accept/SOCKS stage)!", exit.nickname) break for s in ready: if s in bind_list: pending_sockets.remove(s) recv_sock, ... | def exit_test(self, router): tests = {} results = [] test_ports = [] recv_sockets = [] self.test_exit = router exit = router.router # FIXME |
recv_sock, peer = s.accept() recv_sockets.append(recv_sock) ip, port = recv_sock.getpeername() log.debug("%s: accepted connection from %s on port %d.", exit.nickname, ip, port) | elif status == socks4socket.SOCKS4_INCOMPLETE: log.debug("Received partial SOCKS4 response.") elif status == socks4socket.SOCKS4_FAILED: log.debug("SOCKS4 connect failed! :(") pending_sockets.remove(s) router.failed_ports.append(s.getpeername()[1]) done = [] while(len(recv_sockets + send_sockets) > 0): read_l... | def exit_test(self, router): tests = {} results = [] test_ports = [] recv_sockets = [] self.test_exit = router exit = router.router # FIXME |
pending_sockets.remove(s) if s.complete_handshake(): log.debug("SOCKS4 connect successful!") send_sockets.append(s) else: log.debug("SOCKS4 connect failed! :(") done = [] while(len(tests) > 0): read_list, write_list, error = \ select.select(recv_sockets, send_sockets, [], 60) if read_list: for read_sock in read_list... | log.debug("%s: port %d test failed! Expected %s, got %s.", exit.nickname, port, data, data_received) router.failed_ports.append(port) recv_sockets.remove(read_sock) done.append(read_sock) if write_list: for write_sock in write_list: ip, port = write_sock.getpeername() log.debug("%s: writing test data to port %d.", ex... | def exit_test(self, router): tests = {} results = [] test_ports = [] recv_sockets = [] self.test_exit = router exit = router.router # FIXME |
exits = sorted(self.router_cache.values(), key = attrgetter("last_tested"))[0:3] | exits = sorted(self.router_cache.values(), key = attrgetter("last_tested"))[0:4] | def prepare_circuits(self): exits = sorted(self.router_cache.values(), key = attrgetter("last_tested"))[0:3] # Build test circuits. for exit in exits: exit.guard = self.guard_list.pop() exit.circuit = self.build_circuit(exit.guard, exit.router) self.pending_circuits[exit.circuit] = exit return exits |
if self.test_thread.is_alive(): | if self.test_thread.isAlive(): | def run_tests(self): """ Start the test thread. """ if self.test_thread: if self.test_thread.is_alive(): log.error("BUG: Test thread already running!") return self.circuit_thread.start() self.listen_thread.start() self.stream_thread.start() self.test_thread.start() |
return self.circuit_thread.is_alive() and \ self.listen_thread.is_alive() and \ self.stream_thread.is_alive() and \ self.test_thread.is_alive() | return self.circuit_thread.isAlive() and \ self.listen_thread.isAlive() and \ self.stream_thread.isAlive() and \ self.test_thread.isAlive() | def tests_running(self): """ Returns True if all threads associated with testing are alive. """ return self.circuit_thread.is_alive() and \ self.listen_thread.is_alive() and \ self.stream_thread.is_alive() and \ self.test_thread.is_alive() |
threading.current_thread().name = "Main" | threading.currentThread().name = "Main" | def usage(): print "Usage: %s [torhost [ctlport]]" % sys.argv[0] sys.exit(1) |
60.0 * (time.time() - self.tests_started) / self.tests_completed, router.nickname, len(router.working_ports), len(router.failed_ports) | self.tests_completed / ((time.time() - self.tests_started) / 60), router.nickname, len(router.working_ports), len(router.failed_ports)) | def completed_test(self, router): """ Close test circuit associated with router. Restore associated guard to guard_cache. """ self.close_test_circuit(router) self.tests_completed += 1 |
except TorCtlClosed: | except TorCtl.TorCtlClosed: | def stream_status_event(self, event): if event.status == "NEW": if event.target_host == config.test_host: portsep = event.source_addr.rfind(':') source_port = int(event.source_addr[portsep+1:]) # Check if this stream is one of ours (TODO: there's no # reason AFAIK that it shouldn't be one we initiated # if event.target... |
except ValueError, TypeError: | except (ValueError, TypeError): | def usage(): print "Usage: %s targets ip:port1[,port2,...] [ip2:port1[,port2,...]] [...]" % sys.argv[0] sys.exit(1) |
exit_list = ExitList(csv_file = "bel_export.csv") | exit_list = ExitList("bel_export.csv") | def usage(): print "Usage: %s targets ip:port1[,port2,...] [ip2:port1[,port2,...]] [...]" % sys.argv[0] sys.exit(1) |
log.debug("Established test circuit %d failed: %s", circ_id, event.reason) | log.verbose1("Established test circuit %d failed: %s", circ_id, event.reason) | def circ_failed(self, event): circ_id = event.circ_id retry = False |
self.conn.debug(open("TorCtlDebug-%d" % int(time.time()), "w+")) | self.conn.debug(open(config.torctl_debug_file, "w+")) | def start(self, tests = True, passphrase = config.control_password): """ Attempt to connect to the Tor control port with the given passphrase. """ # Initiaze tests first (bind() etc) so we can bork early without waiting # for torctl init stuff. self.tests_enabled = tests if self.tests_enabled: self.init_tests() |
self.scheduler.stop() | if self.scheduler: self.scheduler.stop() | def close(self): """ Close the connection to the Tor control port and end testing.. """ self.terminated = True if self.tests_enabled: self.scheduler.stop() log.info("Joining test threads.") # Don't try to join a thread if it hasn't been created. if self.schedule_thread and self.schedule_thread.isAlive(): self.schedule_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.