How to use ispackage method in Contexts

Best Python code snippet using Contexts

extract.py

Source:extract.py Github

copy

Full Screen

1import importlib2import os3import pkgutil4import typing5import pdocs.doc6class ExtractError(Exception):7 pass8def split_module_spec(spec: str) -> typing.Tuple[str, str]:9 """10 Splits a module specification into a base path (which may be empty), and a module name.11 Raises ExtactError if the spec is invalid.12 """13 if not spec:14 raise ExtractError("Empty module spec.")15 if (os.sep in spec) or (os.altsep and os.altsep in spec):16 dirname, fname = os.path.split(spec)17 if fname.endswith(".py"):18 mname, _ = os.path.splitext(fname)19 return dirname, mname20 else:21 if "." in fname:22 raise ExtractError(23 "Invalid module name {fname}. Mixing path and module specifications "24 "is not supported.".format(fname=fname)25 )26 return dirname, fname27 else:28 return "", spec29def load_module(basedir: str, module: str) -> typing.Tuple[typing.Any, bool]:30 """31 Returns a module object, and whether the module is a package or not.32 """33 ispackage = False34 if basedir:35 mods = module.split(".")36 dirname = os.path.join(basedir, *mods[:-1])37 modname = mods[-1]38 pkgloc = os.path.join(dirname, modname, "__init__.py")39 fileloc = os.path.join(dirname, modname + ".py")40 if os.path.exists(pkgloc):41 location, ispackage = pkgloc, True42 elif os.path.exists(fileloc):43 location, ispackage = fileloc, False44 else:45 raise ExtractError(46 "Module {module} not found in {basedir}".format(module=module, basedir=basedir)47 )48 ispec = importlib.util.spec_from_file_location(modname, location)49 mobj = importlib.util.module_from_spec(ispec)50 try:51 # This can literally raise anything52 ispec.loader.exec_module(mobj) # type: ignore53 except Exception as e:54 raise ExtractError("Error importing {location}: {e}".format(location=location, e=e))55 return mobj, ispackage56 else:57 try:58 # This can literally raise anything59 m = importlib.import_module(module)60 except ImportError:61 raise ExtractError("Module not found: {module}".format(module=module))62 except Exception as e:63 raise ExtractError("Error importing {module}: {e}".format(module=module, e=e))64 # This is the only case where we actually have to test whether we're a package65 if getattr(m, "__package__", False) and getattr(m, "__path__", False):66 ispackage = True67 return m, ispackage68def submodules(dname: typing.Optional[str], mname: str) -> typing.Sequence[str]:69 """70 Return a list of submodule names using a file path or import based name71 If dname is None or empty string, mname will be used as import name.72 Otherwise, the relative directory path at dname will be joined to73 package name mname, and used as the base path for searching.74 """75 if dname:76 return _submodules_from_pathing(dname, mname)77 else:78 return _submodules_from_import_name(mname)79def _submodules_from_import_name(mname: str) -> typing.Sequence[str]:80 """81 Return a list of fully qualified submodules within a package82 mname is an import based module name83 """84 loc = importlib.util.find_spec(mname).submodule_search_locations85 if loc is None:86 # Case of mname corresponding to a terminal module, and not a package87 # iter_modules returns everything it can find anywhere if loc is None,88 # which is not what we want89 return []90 as_imported = importlib.import_module(mname)91 if getattr(as_imported, "__path__", None):92 [loc.append(path) for path in as_imported.__path__ if path not in loc]93 ret = []94 for mi in pkgutil.iter_modules(loc, prefix=mname + "."):95 if isinstance(mi, tuple):96 # Python 3.5 compat97 ret.append(mi[1])98 else:99 ret.append(mi.name)100 ret.sort()101 return ret102def _submodules_from_pathing(dname: str, mname: str) -> typing.Sequence[str]:103 """104 Return a list of fully qualified submodules within a package, given a105 base directory and a fully qualified module name.106 dname is a directory file path, under which mname is stored,107 and mname is module to search for submodules from108 """109 loc = os.path.join(dname, *mname.split("."))110 ret = []111 for mi in pkgutil.iter_modules([loc], prefix=mname + "."):112 if isinstance(mi, tuple):113 # Python 3.5 compat114 ret.append(mi[1])115 else:116 ret.append(mi.name)117 ret.sort()118 return ret119def _extract_module(dname: str, mname: str, parent=None) -> typing.Any:120 m, pkg = load_module(dname, mname)121 mod = pdocs.doc.Module(mname, m, parent)122 if pkg:123 for submodule_full_name in submodules(dname, mname):124 if submodule_full_name.split(".")[-1].startswith("_"):125 continue126 mod.submodules.append(_extract_module(dname, submodule_full_name, parent=mod))127 return mod128def extract_module(spec: str):129 """130 Extracts and returns a module object. The spec argument can have the131 following forms:132 Simple module: "foo.bar"133 Module path: "./path/to/module"134 File path: "./path/to/file.py"135 This function always invalidates caches to enable hot load and reload.136 May raise ExtactError.137 """138 importlib.invalidate_caches()139 dname, mname = split_module_spec(spec)...

Full Screen

Full Screen

select_test_classes.py

Source:select_test_classes.py Github

copy

Full Screen

1import json2import csv3import operator4import sys5def nearestFromAvg(a, b):6 global avg7 return abs(avg - a) - abs(avg - b)8def getKeyByValue(dict, searchValue, alreadySelected):9 for key, value in dict.iteritems():10 if value == searchValue and not key == alreadySelected:11 return key12def buildCmd(project, testClass, suffix):13 print testClass14 cmd = "/usr/bin/time -o ${HOME}/time/" + project + " -v" \15 " ${HOME}/jdk1.8.0_121/jre/bin/java -Xms16G -Xmx32G" \16 " -jar target/dspot-experiment-1.0.0-jar-with-dependencies.jar" \17 " --path-to-propeties src/main/resources/" + project + ".properties" \18 " --amplifiers MethodAdd:TestDataMutator:StatementAdderOnAssert" \19 " --iteration 3" \20 " --output-path " + project + "_" + suffix + \21 " --maven-home /home/spirals/danglot/apache-maven-3.3.9/" \22 " -t " + testClass + \23 " -m ${HOME}/" + project + "_mutant/mutations.csv"24 print cmd25 return cmd26def select(project, excludedClasses=[], isPackage=False):27 global avg28 path = "/home/spirals/danglot/" + project + "_mutant/mutations.csv"29 print path30 with open(path, 'rb') as csvfile:31 mutations_csv = csv.reader(csvfile, delimiter=',', quotechar='|')32 scorePerClass = {}33 nbTotalKilled = 034 for row in mutations_csv:35 if row[-2] == 'KILLED':36 killer = row[-1]37 if "(" in killer: # normal case38 killer = killer[killer.find("(") + 1:killer.find(")")]39 elif killer[:len(killer) / 2] == killer[1 + len(killer) / 2:]: # full qualified name is repeated40 print killer41 killer = killer[:len(killer) / 2]42 else: # only the full qualified is printed43 print killer44 if scorePerClass.has_key(killer):45 scorePerClass[killer] = scorePerClass[killer] + 146 else:47 scorePerClass[killer] = 148 nbTotalKilled = nbTotalKilled + 149 if isPackage:50 for key in scorePerClass.keys():51 if key.startswith(excludedClasses[0]):52 del scorePerClass[key]53 else:54 if excludedClasses:55 for excludedClass in excludedClasses:56 if excludedClass in scorePerClass:57 del scorePerClass[excludedClass]58 avg = nbTotalKilled / len(scorePerClass)59 max1 = max(scorePerClass.iteritems(), key=operator.itemgetter(1))60 del scorePerClass[max1[0]]61 max2 = max(scorePerClass.iteritems(), key=operator.itemgetter(1))62 del scorePerClass[max2[0]]63 min1 = min(scorePerClass.iteritems(), key=operator.itemgetter(1))64 del scorePerClass[min1[0]]65 min2 = min(scorePerClass.iteritems(), key=operator.itemgetter(1))66 del scorePerClass[min2[0]]67 tmp = sorted(scorePerClass.values(), cmp=nearestFromAvg)68 avg1 = getKeyByValue(scorePerClass, tmp[0], None), tmp[0]69 avg2 = getKeyByValue(scorePerClass, tmp[1], avg1[0]), tmp[1]70 print max1[0], max2[0]71 print min1[0], min2[0]72 print avg1[0], avg2[0]73 return max1, max2, min1, min2, avg1, avg274def getCmd(project, excludedClasses=[], isPackage=False):75 max1, max2, min1, min2, avg1, avg2 = select(project, excludedClasses, isPackage)76 return buildCmd(project, max1[0], "max1"), buildCmd(project, max2[0], "max2"), buildCmd(project, min1[0], "min1"), \77 buildCmd(project, min2[0], "min2"), buildCmd(project, avg1[0], "avg1"), buildCmd(project, avg2[0], "avg2")78avg = 079if __name__ == '__main__':80 project = sys.argv[1]81 pathDataset = sys.argv[2]82 print project83 print pathDataset84 with open(pathDataset + "/properties_rates.json") as data_file:85 properties_rates = json.load(data_file)86 print select(project, properties_rates[project]["excludedClasses"].split(":"), properties_rates[project]["isPackage"])...

Full Screen

Full Screen

WindowModuleUtil.py

Source:WindowModuleUtil.py Github

copy

Full Screen

1#!/usr/bin/env python2"""Utilities to find and load TUI windows modules.32005-08-08 ROwen42006-10-25 ROwen Minor clarifications of logFunc in a doc string.52011-06-16 ROwen Ditched obsolete "except (SystemExit, KeyboardInterrupt): raise" code62011-09-09 ROwen Modified to restore working directory.7 Modified to run paths through normpath to make the code more robust.8"""9import os10import sys11import traceback12import RO.Constants13import RO.OS14def findWindowsModules(15 path,16 isPackage = False,17 loadFirst = None,18):19 """Iterator: recursively find TUI "window modules" in a given path20 and return the associated module name.21 22 Window modules are files whose name ends in 'Window.py'.23 24 Does NOT verify that the module is actually part of a valid package.25 To load these modules YOU must make sure that:26 - There are no missing __init__.py files in the directory hierarchy.27 - The the path is on the python path.28 29 Warning: temporarily changes the current working directory.30 31 Inputs:32 - path root of path to search33 - isPackage the path is a package; the final directory34 should be included as part of the name of any module loaded.35 - loadFirst name of subdir to load first;36 """37 try:38 currDir = os.getcwd()39 os.chdir(path)40 windowModulePathList = RO.OS.findFiles(os.curdir, "*Window.py")41 finally:42 os.chdir(currDir)43 windowModulePathList = [os.path.normpath(wmPath) for wmPath in windowModulePathList]44 if loadFirst and windowModulePathList:45 # rearrange so modules in specified subdir come first46 # use decorate/sort/undecorate pattern47 decList = [(not wmPath.startswith(loadFirst), wmPath) for wmPath in windowModulePathList]48 decList.sort()49 windowModulePathList = zip(*decList)[1]50 for windowModulePath in windowModulePathList:51 # generate the module name:52 # <rootmodulename>.subdir1.subdir2...lastsubdir.<modulename>53 pathNoExt = os.path.splitext(windowModulePath)[0]54 pathList = RO.OS.splitPath(pathNoExt)55 # avoid hidden files56 if pathList[-1].startswith("."):57 continue58 if isPackage:59 pkgName = os.path.basename(path)60 pathList.insert(0, pkgName)61 moduleName = ".".join(pathList)62 yield moduleName63def loadWindows(64 path,65 tlSet,66 isPackage = False,67 loadFirst = None,68 logFunc = None,69):70 """Automatically load all windows in any subdirectory of the path.71 The path is assumed to be on the python path (sys.path).72 Windows have a name that ends in 'Window.py'.73 74 Inputs:75 - path root of path to search76 - tlSet toplevel set (see RO.Wdg.Toplevel)77 - isPackage the path is a package; the final directory78 should be included as part of the name of any module loaded.79 - loadFirst name of subdir to load first;80 - logFunc function for logging messages or None of no logging wanted;81 logFunc must take two arguments:82 - the text to log83 - severity (by name): one of the RO.Constant.sev constants,84 defaulting to RO.Constants.sevNormal.85 86 Raises RuntimeError if loadFirst is specified and no modules are found.87 """88 if logFunc:89 logFunc("Searching for additions in %r" % (path,))90 for moduleName in findWindowsModules(91 path = path,92 isPackage = isPackage,93 loadFirst = loadFirst,94 ):95 # import the module96 try:97 module = __import__(moduleName, globals(), locals(), "addWindow")98 module.addWindow(tlSet)99 if logFunc:100 logFunc("Added %r" % (moduleName,))101 except Exception as e:102 errMsg = "%s.addWindow failed: %s" % (moduleName, e)103 if logFunc:104 logFunc(errMsg, severity=RO.Constants.sevError)105 sys.stderr.write(errMsg + "\n")...

Full Screen

Full Screen

main.py

Source:main.py Github

copy

Full Screen

1from flask import Flask, request2from multiprocessing import Process3import RPi.GPIO as GPIO4#Alexa5from flask_ask import Ask, statement6import spidev7import time8#Twilio9from twilio.twiml.messaging_response import MessagingResponse10from .notifications import send_sms11from .notifications import send_email12# for testing purposes13def default(a, b):14 return a + b15def createSPI(bus, device):16 spi = spidev.SpiDev()17 spi.open(bus, device)18 spi.max_speed_hz = 100000019 spi.mode = 020 return spi21def requestButton():22 GPIO.setwarnings(False)23 GPIO.setmode(GPIO.BCM)24 GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)25 while (True):26 input = GPIO.input(21)27 if input == False:28 print("Button Pressed")29 send_sms.sendSMS(30 '+19098272197', '+12058329927',31 "Request to open R'Mailbox: Reply with Y/y or N/n.")32 time.sleep(1)33def packageNotify():34 mailNotification = 135 while (True):36 atmegaSPI = createSPI(0, 0)37 #SPI Command to Atmega38 Send_Status = 0x1039 atmegaSPI.xfer([Send_Status])40 isPackage = atmegaSPI.readbytes(1)[0]41 print("Package Status", isPackage)42 atmegaSPI.close()43 if isPackage:44 print("Package detected")45 if mailNotification == 1:46 mailNotification = 047 print("Sending package notification")48 send_sms.sendSMS(49 '+19098272197', '+12058329927',50 "You have received a new package! The RMailbox will keep it safe until you retrieve it."51 )52 send_email.sendEmail()53 elif not isPackage:54 print("No package")55 if mailNotification != 1:56 mailNotification = 157 else:58 print("Unknown signal")59 time.sleep(3)60app = Flask(__name__)61ask = Ask(app, '/')62@app.route("/sms", methods=['GET', 'POST'])63def sms_reply():64 # Get message body of incoming message65 body = request.values.get('Body', None)66 # Start Response67 resp = MessagingResponse()68 # Determine Correct Response69 if body == 'Y' or body == 'y':70 atmegaSPI = createSPI(0, 0)71 print('Unlocking door')72 #SPI Command to Atmega73 Unlock_Door = 0x2074 atmegaSPI.xfer([Unlock_Door])75 atmegaResponse = atmegaSPI.readbytes(1)[0]76 print(hex(atmegaResponse))77 atmegaSPI.close()78 resp.message("Access granted to R'Mailbox.")79 elif body == 'N' or body == 'n':80 resp.message("Access denied to R'Mailbox.")81 else:82 resp.message("Please respond with Y/y or N/n")83 return str(resp)84@ask.intent('IRIntent')85def isMail():86 atmegaSPI = createSPI(0, 0)87 #SPI Command to Atmega88 Send_Status = 0x1089 atmegaSPI.xfer([Send_Status])90 isPackage = atmegaSPI.readbytes(1)[0]91 print("Current Package Status: ", isPackage)92 atmegaSPI.close()93 if isPackage:94 return statement('You have mail')95 return statement('There is currently no mail')96if __name__ == '__main__':97 try:98 flaskServer = Process(target=app.run, kwargs=dict(debug=True))99 requestOpen = Process(target=requestButton)100 #notifications = Process(target=packageNotify)101 #http://jhshi.me/2015/12/27/handle-keyboardinterrupt-in-python-multiprocessing/index.html#.XtBUiDpKj-g102 #Fixes errors on keyboard interrupts103 flaskServer.daemon = True104 requestOpen.daemon = True105 #notifications.daemon = True106 flaskServer.start()107 requestOpen.start()108 #notifications.start()109 notifications = packageNotify()110 except KeyboardInterrupt:111 flaskServer.terminate()112 requestOpen.terminate()113 #notifications.terminate()...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Contexts automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful