def fromDict(self, args): if (lists.isDict(args)): try: __iter__ = args.iteritems() except: try: __iter__ = args.asPythonDict().iteritems() except: try: __iter__ = args.asDict().iteritems() except: __iter__ = None for ak, av in __iter__: try: for k, v in av.iteritems(): self.__dict__['%s_%s' % (ak, k)] = v except: self.__dict__[ak] = av if (not misc.isList(av)) else [ item if (not lists.isDict(item)) else self.__class__(item) for item in av ] else: logging.warning( '(%s.%s) :: Illegal args variable, expected type "dict" but got type "%s".' % (ObjectTypeName.typeName(self), misc.funcName(), ObjectTypeName.typeName(args)))
def _getAccountTree_(self,account,tree=[],skip_ancestors=False): '''Walk-up the tree look for the account that has no parent then locate all children.''' try: if (account['ParentId'] is None): tree.append(account) ancestors = [] # There cannot be any ancestors because this account has no parent and this makes the account the progenitor by default. else: ancestors = self.getAccountAncestors(account,ancestors=[]) if (not skip_ancestors) and (len(ancestors) > 0): d_ancestors = lists.HashedLists2() for ancestor in ancestors: d_ancestors[ancestor['ParentId']] = ancestor progenitor = d_ancestors[None] if (lists.isDict(progenitor)) and (len([node for node in tree if (node['Id'] == progenitor['Id'])]) == 0): tree.append(progenitor) return self._getAccountTree_(progenitor,tree=tree,skip_ancestors=skip_ancestors) else: if (not lists.isDict(account)): return tree children = self.getAccountsByParentId(account['Id']) for child in children: if (lists.isDict(child)) and (len([node for node in tree if (node['Id'] == child['Id'])]) == 0): tree.append(child) self._getAccountTree_(child,tree=tree,skip_ancestors=True) except Exception as details: info_string = _utils.formattedException(details=details) print >>sys.stderr, info_string return tree
def asSmartObjects(self, objects): from vyperlogix.hash import lists items = [] if (isinstance(objects, list)) or (isinstance(objects, tuple)): for obj in objects: items.append( PyroSmartObject(obj) if (lists.isDict(obj)) else obj) elif (lists.isDict(objects)): items.append(objects) return items
def get_from_session(request, name, default=None): from vyperlogix.hash import lists from vyperlogix.classes.SmartObject import PyroSmartObject try: obj = request.session.get(name, default) return [ o if (not lists.isDict(o)) else PyroSmartObject(o) for o in obj ] if (misc.isList(obj)) else obj if ( not lists.isDict(obj)) else PyroSmartObject(obj) except: pass return ''
def fromDict(self, args): if (lists.isDict(args)): for ak, av in args.iteritems(): if (lists.isDict(av)): self.__dict__[ak] = SmartObject(av) else: self.__dict__[ak] = av if (not misc.isList(av)) else [ item if (not lists.isDict(item)) else self.__class__(item) for item in av ] else: logging.warning( '(%s.%s) :: Illegal args variable, expected type "dict" but got type "%s".' % (ObjectTypeName.typeName(self), misc.funcName(), ObjectTypeName.typeName(args)))
def __call__(self, *args, **kwargs): ''' Automatically redirect all unknown methods to the underlying Pyro Proxy object. Builds a request in the format of: contacts.getPortalContactByEmail('*****@*****.**') that is turned into: request_objects('contacts.getPortalContactByEmail("%s")' % (contact_username)) ''' m = super(MagicObject2, self).__call__(*args, **kwargs)[1:] if (len(m[0]) > 1): isExecute = (m[0][-1] == 'execute') and (len(args) == 0) and (len(kwargs) == 0) if (isExecute): s = 'self.proxy.request_objects(\'%s.%s\')' % (m[0][0], m[0][1]) else: s = 'self.proxy.request_objects(\'%s.%s(%s)\')' % ( m[0][0], m[0][1], _utils.args(*args, **kwargs)) else: s = 'self.proxy.%s(%s)' % (m[0][0], _utils.args(*args, **kwargs)) lastError = 'n/a' objs = self.get_objects(s) if (isinstance(objs, tuple)): objs = list(objs) lastError = objs[-1] objs = objs[0] if (_isRunningLocal): print '"%s" --> %s' % (s, objs if (not misc.isString(objs)) else '"%s"' % (objs)) self.__reset_magic__() if (not isinstance(objs, list)) and (not isinstance( objs, tuple)) and (not lists.isDict(objs)): return objs return self.asSmartObjects(objs), lastError
def asDict(self, cls=lists.HashedLists2): '''cls can also be dict to allow for normal native dict objects to be returned for safe pickling using the standard Python pickle methods.''' d = cls() for k, v in self.__dict__.iteritems(): d[real_k(k)] = [asPythonDict(item) for item in v ] if (misc.isList(v)) else asPythonDict(v) if ( lists.isDict(v)) else v.asPythonDict() if ( isSmartObject(v)) else v return d
def renderTable(row0, dict_obj, **attributes): from vyperlogix.hash import lists h = Html() h_html = h.tag(oohtml.HTML) h_body = h_html.tag(oohtml.BODY) h_Content = h_body.tag(oohtml.DIV) _rows = [['', '']] if (not isinstance(row0, list)) and ( not isinstance(row0, tuple)) else [list(row0)] if (lists.isDict(dict_obj)): for k, v in dict_obj.iteritems(): _rows.append([ k, str(v) if (v is not None) and (len(str(v)) > 0) else ' ' ]) h_Content.html_table(_rows, **attributes) return h_Content.toHtml().replace('\n', '').replace('\t', '')
def getZipFilesAnalysis2(_zip): import os from vyperlogix.misc import ObjectTypeName from vyperlogix.hash import lists _analysis = lists.HashedLists2() try: iterable = None if (ObjectTypeName.typeClassName(_zip) == 'zipfile.ZipFile'): iterable = (f.filename for f in _zip.filelist) elif (lists.isDict(_zip)): iterable = (f for f in _zip.keys()) for f in iterable: _analysis[f] = f except: pass return _analysis
def __call__(self, *args, **kwargs): ''' Automatically redirect all unknown methods to the underlying Pyro Proxy object. ''' s = 'self.proxy.%s(%s)' % (self.n.pop(), _utils.args(*args, **kwargs)) lastError = 'n/a' objs = self.get_objects(s) if (isinstance(objs, tuple)): objs = list(objs) lastError = objs[-1] objs = objs[0] if (_isRunningLocal): print '"%s" --> %s' % (s, objs if (not misc.isString(objs)) else '"%s"' % (objs)) self.__reset_magic__() if (not isinstance(objs, list)) and (not isinstance( objs, tuple)) and (not lists.isDict(objs)): return objs return objs, lastError
def getZipFilesAnalysis(_zip, prefix='', _acceptable_types=[]): import os from vyperlogix.misc import ObjectTypeName from vyperlogix.hash import lists _analysis = lists.HashedLists() try: iterable = None if (ObjectTypeName.typeClassName(_zip) == 'zipfile.ZipFile'): iterable = (f.filename for f in _zip.filelist) elif (lists.isDict(_zip)): iterable = (f for f in _zip.keys()) for f in iterable: toks = os.path.splitext(f) if (len(_acceptable_types) == 0) or ( toks[-1].split('.')[-1] in _acceptable_types) or ((len(prefix) > 0) and (toks[0].startswith(prefix))): _analysis[toks[0]] = toks[-1] if (len(toks) > 1) else '' except: pass return _analysis
def write_as_csv(self,fname,list_of_records=[],ordering=[]): """ Writes a list of records (dict objects) to a .CSV filename. """ info_string = '' info_strings = [] if (misc.isList(list_of_records)): if (len(list_of_records) > 0): if (all([lists.isDict(r) for r in list_of_records])): header = list_of_records[0].keys() if (misc.isList(ordering)) and (len(ordering) > 0): header = ordering s_header = ','.join(header) fOut = open(fname,'w') try: print >>fOut, s_header for rec in list_of_records: l_values = [] for h in header: l_values.append(str(rec[h]) if (str(rec[h]).find(',') == -1) else '"%s"' % (rec[h])) print >>fOut, ','.join(l_values) except Exception as details: info_string = _utils.formattedException(details=details) info_strings.append(info_string) finally: fOut.flush() fOut.close() else: info_string = '%s :: Expected list_of_records to contains dictionary objects however some do not.' % (ObjectTypeName.objectSignature(self)) info_strings.append(info_string) else: info_string = '%s :: Expected list_of_records to contains dictionary objects however list is empty.' % (ObjectTypeName.objectSignature(self)) info_strings.append(info_string) else: info_string = '%s :: Expected list_of_records to be of type list rather than type "%s".' % (ObjectTypeName.objectSignature(self),type(list_of_records)) info_strings.append(info_string) return '\n'.join(info_strings)
def __init__(self, name, locals={}, globals=None): """ Create a LazyImport instance wrapping module name. The module will later on be registered in locals under the given module name. globals is optional and defaults to locals. """ self.__dict__ = lists.HashedLists2(self.__dict__) self.__lazyimport_locals = lists.HashedLists2(locals) if (globals is None): globals = lists.HashedLists2(locals) elif (lists.isDict(globals)): globals = lists.HashedLists2(globals) self.__lazyimport_globals = globals mainname = globals.get('__name__', '') if (globals.has_key('__name__')) else None if (mainname): self.__name__ = mainname + '.' + name self.__lazyimport_name = name else: self.__name__ = self.__lazyimport_name = name self.__lazyimport_init = 1
def reportTheList(l, title, callback=None, asCSV=False, fOut=sys.stdout): '''Report the List using a callback or asCSV or the default str(item) method.''' from vyperlogix.hash import lists from vyperlogix.parsers import CSV from vyperlogix import misc from vyperlogix.misc import ObjectTypeName print >> fOut, 'BEGIN: %s num=(%s)' % (title, len(l)) i = 1 if (misc.isIterable(l)) or (misc.isList(l)): for item in l: if (isinstance(item, tuple)): item = list(item) if (isinstance(item, list)): if (lists.isDict(item[0])): lists.prettyPrint(item[0], title='%d :: %s' % (i, title), asCSV=asCSV, fOut=fOut) i += 1 else: isHandled = False if (callable(callback)): try: print >> fOut, '\t%s' % (callback(item[0])) isHandled = True except: pass if (not isHandled): if (asCSV): print >> fOut, '%s' % (CSV.asCSV(item)) else: print >> fOut, '\t%s' % (item[0]) i += 1 for _item in item[1:]: if (misc.isList(_item)): for __item in _item: if (lists.isDict(__item)): lists.prettyPrint(__item, title='%d :: %s' % (i, title), asCSV=asCSV, fOut=fOut) i += 1 else: isHandled = False if (callable(callback)): try: print >> fOut, '\t\t%d :: %s' % ( ii, callback(__item)) isHandled = True except: pass if (not isHandled): if (asCSV): print >> fOut, '"%d","%s"' % (ii, __item) else: print >> fOut, '\t\t%d :: %s' % ( ii, __item) i += 1 else: if (lists.isDict(_item)): lists.prettyPrint(_item, title='%d :: %s' % (i, title), asCSV=asCSV, fOut=fOut) i += 1 else: isHandled = False if (callable(callback)): try: print >> fOut, '\t\t%s' % ( callback(__item)) isHandled = True except: pass if (not isHandled): if (asCSV): print >> fOut, '"%s"' % (_item) else: print >> fOut, '\t\t%s' % (_item) i += 1 else: if (lists.isDict(item)): lists.prettyPrint(item, title='%d :: %s' % (i, title), asCSV=asCSV, fOut=fOut) i += 1 else: isHandled = False if (callable(callback)): try: print >> fOut, '\t%d :: %s' % (i, callback(item)) isHandled = True except: pass if (not isHandled): if (asCSV): print >> fOut, '"%d","%s"' % (i, item) else: print >> fOut, '\t%d :: %s' % (i, item) i += 1 else: print >> fOut, 'NOTHING TO REPORT, List is EMPTY or not an interable; just for the record type "%s" is not iterable.' % ( ObjectTypeName.typeClassName(l)) print >> fOut, 'END! %s' % (title)