Best Python code snippet using localstack_python
components.py
Source:components.py  
...45    def __init__(self):46        self._dict_data = None47    def keys(self):48        if self._dict_data is None:49            self._dict_data = self._build_dict()50        return self._dict_data.keys()51    def items(self):52        if self._dict_data is None:53            self._dict_data = self._build_dict()54        return self._dict_data.items()55    def values(self):56        if self._dict_data is None:57            self._dict_data = self._build_dict()58        return self._dict_data.values()59    def has_key(self, key):60        if self._dict_data is None:61            self._dict_data = self._build_dict()62        return self._dict_data.has_key(key)63    def __len__(self):64        if self._dict_data is None:65            self._dict_data = self._build_dict()66        return len(self._dict_data)67    def __getattr__(self, attr):68        if self._dict_data is not None and self._dict_data.has_key(attr):69            return self._dict_data[attr]70        return self._get_one(attr)71    def __getitem__(self, item):72        if self._dict_data is not None and self._dict_data.has_key(item):73            return self._dict_data[item]74        return self._get_one(item)75_constants_by_iid_map = {}76class _Interface:77    # An interface object.78    def __init__(self, name, iid):79        # Bypass self.__setattr__ when initializing attributes.80        d = self.__dict__81        d['_iidobj_'] = iid # Allows the C++ framework to treat this as a native IID.82        d['name'] = name83    def __cmp__(self, other):84        this_iid = self._iidobj_85        other_iid = getattr(other, "_iidobj_", other)86        return cmp(this_iid, other_iid)87    def __hash__(self):88        return hash(self._iidobj_)89    def __str__(self):90        return str(self._iidobj_)91    def __getitem__(self, item):92        raise TypeError, "components.interface objects are not subscriptable"93    def __setitem__(self, item, value):94        raise TypeError, "components.interface objects are not subscriptable"95    def __setattr__(self, attr, value):96        raise AttributeError, "Can not set attributes on components.Interface objects"97    def __getattr__(self, attr):98        # Support constants as attributes.99        c = _constants_by_iid_map.get(self._iidobj_)100        if c is None:101            c = {}102            i = xpt.Interface(self._iidobj_)103            for c_ob in i.constants:104                c[c_ob.name] = c_ob.value105            _constants_by_iid_map[self._iidobj_] = c106        if c.has_key(attr):107            return c[attr]108        raise AttributeError, "'%s' interfaces do not define a constant '%s'" % (self.name, attr)109class _Interfaces(_ComponentCollection):110    def _get_one(self, name):111        try:112            item = interfaceInfoManager.GetInfoForName(name)113        except xpcom.COMException, why:114            # Present a better exception message, and give a more useful error code.115            import nsError116            raise xpcom.COMException(nsError.NS_ERROR_NO_INTERFACE, "The interface '%s' does not exist" % (name,))117        return _Interface(item.GetName(), item.GetIID())118    def _build_dict(self):119        ret = {}120        enum = interfaceInfoManager.EnumerateInterfaces()121        while not enum.IsDone():122            # Call the Python-specific FetchBlock, to keep the loop in C.123            items = enum.FetchBlock(500, _xpcom.IID_nsIInterfaceInfo)124            # This shouldnt be necessary, but appears to be so!125            for item in items:126                ret[item.GetName()] = _Interface(item.GetName(), item.GetIID())127        return ret128# And the actual object people use.129interfaces = _Interfaces()130del _Interfaces # Keep our namespace clean.131#################################################132class _Class:133    def __init__(self, contractid):134        self.contractid = contractid135    def __getattr__(self, attr):136        if attr == "clsid":137            rc = manager.contractIDToClassID(self.contractid)138            # stash it away - it can never change!139            self.clsid = rc140            return rc141        raise AttributeError, "%s class has no attribute '%s'" % (self.contractid, attr)142    def createInstance(self, iid = None):143        import xpcom.client144        try:145            return xpcom.client.Component(self.contractid, _get_good_iid(iid))146        except xpcom.COMException, details:147            import nsError148            # Handle "no such component" in a cleaner way for the user.149            if details.errno == nsError.NS_ERROR_FACTORY_NOT_REGISTERED:150                raise xpcom.COMException(details.errno, "No such component '%s'" % (self.contractid,))151            raise # Any other exception reraise.152    def getService(self, iid = None):153        return serviceManager.getServiceByContractID(self.contractid, _get_good_iid(iid))154class _Classes(_ComponentCollection):155    def __init__(self):156        _ComponentCollection.__init__(self)157    def _get_one(self, name):158        # XXX - Need to check the contractid is valid!159        return _Class(name)160    def _build_dict(self):161        ret = {}162        enum = manager.EnumerateContractIDs()163        while not enum.IsDone():164            # Call the Python-specific FetchBlock, to keep the loop in C.165            items = enum.FetchBlock(500)166            for item in items:167                name = str(item)168                ret[name] = _Class(name)169        return ret170classes = _Classes()171del _Classes172del _ComponentCollection173# The ID function174ID = _xpcom.IID...yumHelper.py
Source:yumHelper.py  
...13        self.yb.preconf.errorlevel = 014        self.yb.verbose_logger = logging.getLogger()15        self.yb.doTsSetup()16        self.yb.doRpmDBSetup()17    def _build_dict(self, po):18        pkg_list = []19        for p in po:20            pkg_list.append(21                {22                    'name': p.name,23                    'version': p.version,24                    'release': p.release,25                    'epoch': p.epoch,26                    'arch': p.arch,27                    'provider': 'yum',28                    'ensure': '%s-%s' % (p.version, p.release)29                }30            )31        return pkg_list32    def install(self, package):33        try:34            p = self.yb.install(pattern=package)35            self.yb.buildTransaction()36            self.yb.processTransaction(rpmDisplay=NoOutputCallBack())37            if p:38                p_dict = {'status': self._build_dict(p)[0]}39            else:40                p_dict = { 'msg': 'already installed and latest version',41                           'status': {} }42        except yum.Errors.InstallError as e:43            p_dict = {'msg': str(e),44                      'status': [] }45        finally:46            self.yb.closeRpmDB()47        return json.dumps(p_dict, sort_keys=True)48    def remove(self, package):49        try:50            p = self.yb.remove(name=package)51            self.yb.buildTransaction()52            self.yb.processTransaction(rpmDisplay=NoOutputCallBack())53            if p:54                p_dict = {'status': self._build_dict(p)[0]}55            else:56                p_dict = { 'msg': 'Package not installed',57                           'status': {} }58        except yum.Errors.InstallError as e:59            p_dict = {'msg': str(e),60                      'status': [] }61        finally:62            self.yb.closeRpmDB()63        return json.dumps(p_dict, sort_keys=True)64    def update(self, package):65        pkg_list = []66        try:67            if package is "*":68                p = self.yb.update()69            else:70                p = self.yb.update(name=package)71            self.yb.buildTransaction()72            self.yb.processTransaction(rpmDisplay=NoOutputCallBack())73            if len(p) > 1:74                p_dict = { 'status': self._build_dict(p)[0] }75            else:76                p_dict = { 'status': 'Everything is up to date' }77        except yum.Errors.InstallError as e:78            p_dict = {'msg': str(e),79                      'status': 'Failed' }80        finally:81            self.yb.closeRpmDB()82        return json.dumps(p_dict, sort_keys=True)83    def status(self, package):84        try:85            p = self.yb.rpmdb.searchNevra(name=package)86            if p:87                p_dict = self._build_dict(p)[0]88            else:89                p_dict = { 'status': 'Not installed' }90        except yum.Errors.InstallError as e:91            p_dict = {'msg': str(e),92                      'status': 'Failed' }93        finally:94            self.yb.closeRpmDB()95        return json.dumps(p_dict, sort_keys=True)96    def search(self, package):97        try:98            packages = self.yb.pkgSack.matchPackageNames([package])99            if packages[0] or packages[1]:100                p_dict = {}101                p_dict['status'] = { "available_packages" : self._build_dict(packages[0] + packages[1]) }102                p_dict['status']["package_count"] = "%s packages found" % (len(p_dict['status']['available_packages'])) 103            else:104                p_dict = { 'msg': 'Package not found', 'status': {'available_packages': []} }105        finally:106            self.yb.closeRpmDB()107        return json.dumps(p_dict, sort_keys=True)108def parse_options():109    parser = OptionParser()110    parser.add_option('-i', '--install', type="string", dest="install",111                     help="Install package")112    parser.add_option('-r', '--remove', type="string", dest="remove",113                     help="Remove package")114    parser.add_option('-s', '--status', type="string", dest="status",115                     help="Status of package")...build_data.py
Source:build_data.py  
1# Copyright 2005 Google Inc.2# All Rights Reserved.3#4# Author: roth@google.com (Mark D. Roth), dgreiman@google.com (Douglas Greiman)5"""Access to google3 build data"""6import cStringIO7import time8from google3.pyglib import resources9# Global data10_build_dict = None11def _ParseBuildData(filename):12  """Read build data from external file.13  Uses default values if build data file not available.14  Returns dictionary of build data info15  """16  # Start with empty defaults17  build_data = {18    'BUILDINFO' : '',19    'BUILDLABEL' : '',20    'BUILDTOOL' : '',21    'CHANGELIST' : '-1',22    'CLIENTNAME' : '',23    'CLIENTSTATUS' : '-2',24    'DEPOTPATH' : '',25    'PAROPTIONS' : '',26    'PLATFORM' : '',27    'TARGET' : '',28    'TIMESTAMP' : '',29    }30  # Read generated build info if available31  try:32    build_data_str = resources.GetResource(filename)33    # Parse as key/value pairs34    for line in build_data_str.splitlines():35      # Skip comments, blanks, and syntax errors36      if line.startswith('#') or not line.strip() or ':' not in line:37        continue38      key, value = line.split(':',1)39      build_data[key] = value40  except IOError:41    pass  # Build data not available42  return build_data43def _InitBuildData():44  """Read build data from external file, if not already read."""45  global _build_dict46  if not _build_dict:47    _build_dict = _ParseBuildData('google3/pyglib/build_data.txt')48def BuildInfo():49  """Return user, host, and directory of builder, as string"""50  _InitBuildData()51  return _build_dict.get('BUILDINFO', '')52def BuildLabel():53  """Return build label (passed to make-{opt,dbg} -l) as string"""54  _InitBuildData()55  return _build_dict.get('BUILDLABEL', '')56def BuildTool():57  """Return the build tool as string if we know it"""58  _InitBuildData()59  return _build_dict.get('BUILDTOOL', '')60def Changelist():61  """Return client workspace changelist, as int"""62  _InitBuildData()63  cl = _build_dict.get('CHANGELIST', '')64  try:65    changelist = int(cl.strip())66  except ValueError:67    changelist = -168  return changelist69def ClientInfo():70  """Return Perforce client changelist and status as descriptive string"""71  _InitBuildData()72  info = ''73  cl = Changelist()74  if cl == -1:75    info = ''76  elif cl == 0:77    info = 'unknown changelist'78  else:79    cs = ClientStatus()80    dp = DepotPath()81    if cs == 1:82      status_info = ' in a mint client based on %s' % dp83    elif cs == 0:84      status_info = ' in a modified client based on %s' % dp85    else:86      status_info = ' possibly in a modified client'87    info = 'changelist %d%s' % (cl, status_info)88  return info89def ClientName():90  """Return Perforce client name, as string"""91  _InitBuildData()92  return _build_dict.get('CLIENTNAME', '')93def ClientStatus():94  """Return Perforce client status, as int"""95  _InitBuildData()96  tmp_str = _build_dict.get('CLIENTSTATUS', '')97  try:98    status = int(tmp_str.strip())99  except ValueError:100    status = -1101  return status102def DepotPath():103  """Return Perforce depot path, as string"""104  _InitBuildData()105  return _build_dict.get('DEPOTPATH', '')106def ParOptions():107  """Return list of autopar options, as string"""108  _InitBuildData()109  return _build_dict.get('PAROPTIONS', '')110def Platform():111  """Return google platform as string"""112  _InitBuildData()113  return _build_dict.get('PLATFORM', '')114def Target():115  """Return build target as string"""116  _InitBuildData()117  return _build_dict.get('TARGET', '')118def Timestamp():119  """Return timestamp in seconds since epoch, as int"""120  _InitBuildData()121  ts = _build_dict.get('TIMESTAMP', '')122  try:123    timestamp = int(ts.strip())124  except ValueError:125    timestamp = -1126  return timestamp127def BuildData():128  """Return all build data as a nicely formatted string."""129  _InitBuildData()130  buf = cStringIO.StringIO()131  timestamp = Timestamp()132  buf.write('Built on %s (%d)\n' %133            (time.asctime(time.localtime(timestamp)), timestamp))134  buf.write('Built by %s\n' % BuildInfo())135  buf.write('Built as %s\n' % Target())136  clientinfo = ClientInfo()137  if clientinfo:138    buf.write('Built from %s\n' % clientinfo)139  buildlabel = BuildLabel()140  if buildlabel:141    buf.write('Build label: %s\n' % buildlabel)142  buf.write('Build platform: %s\n' % Platform())143  buildtool = BuildTool()144  if buildtool:145    buf.write('Build tool: %s\n' % buildtool)146  paropts = ParOptions()147  if paropts:148    buf.write('\nBuilt with par options %s\n' % paropts)149  data_str = buf.getvalue()150  buf.close()...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
