def __init__(self, docstring=DEFAULTS['docstring'], options=DEFAULTS['options'], default=[], optional=DEFAULTS['optional'], values=DEFAULTS['values'], category=DEFAULTS['category'], callback=DEFAULTS['callback'], synopsis=DEFAULTS['synopsis'], environ=DEFAULTS['environ'], registry=DEFAULTS['registry'], delim=' ', range=[1,'*'], mandatory=None, name=DEFAULTS['name'], source=DEFAULTS['source'], template=StringOption): """ Initialize a multi argument """ self.delim = delim self.range = range assert not issubclass(template, MultiArgument), \ 'MultiArguments can not have a MultiArguments as a template' assert not issubclass(template, MultiOption), \ 'MultiOptions can not have a MultiOptions as a template' assert issubclass(template, GenericOption), \ 'Templates must be a subclass of GenericOption' self.template = template(options=options,name=name,values=values) UserList.__init__(self, []) GenericOption.initialize(self, locals())
def __init__(self, imm, addr, heap = 0x0, log = None ): """ Win32 Heap Lookaside list """ UserList.__init__(self) if not log: log = imm.Log self.log = log self.imm = imm self.heap = heap self.Lookaside = [] LookSize = PLook(self.imm, 0x0).getSize() mem = imm.readMemory(addr, LookSize * HEAP_MAX_FREELIST) for ndx in range(0, HEAP_MAX_FREELIST): base_addr = addr + ndx * LookSize l = PLook(self.imm, base_addr, mem[ ndx * LookSize : ndx * LookSize + LookSize ], self.heap ) self.data.append(l) next = l.ListHead while next and next != base_addr: l.append( next ) try: next = self.imm.readLong(next) except: break
def __init__(self, *args): #print args, len(args), isinstance(args[0], Messages), type(args[0]) if len(args) == 1 and (isinstance(args[0], UserList) or type(args[0]) == ListType): UserList.__init__(self, args[0]) else: UserList.__init__(self, list(args))
def __init__(self, docstring=DEFAULTS['docstring'], options=DEFAULTS['options'], default=[], optional=DEFAULTS['optional'], values=DEFAULTS['values'], category=DEFAULTS['category'], callback=DEFAULTS['callback'], synopsis=DEFAULTS['synopsis'], environ=DEFAULTS['environ'], registry=DEFAULTS['registry'], delim=',', range=[1,'*'], mandatory=None, name=DEFAULTS['name'], source=DEFAULTS['source'], template=StringOption): """ Initialize a multi option This class is initialized with the same options as the Option class with one addition: delim. The 'delim' argument specifies what the delimiter is for each item in the list. If the delimiter is 'None' or whitespace, each item in the list is assumed to be delimited by whitespace. """ self.delim = delim self.range = range assert not issubclass(template, MultiOption), \ 'MultiOptions can not have a MultiOption as a template' assert issubclass(template, GenericOption), \ 'Templates must be a subclass of GenericOption' self.template = template(options=options,name=name,values=values) UserList.__init__(self, []) GenericOption.initialize(self, locals())
def __init__(self, data=None, name=None, kind=None, element=None): self.val = 0 self.free_spaces = 8 self.name = name UserList.__init__(self) if data == None: # The code below creates 4 units of element with a comp # of (4,2,2,0). Each unit is equiped with a unique weapon. if kind == 'mins': if element != None: s = Stone() s[element] = 4 s[OPP[element]] = 0 for o in ORTH[element]: s[o] = 2 for wep in WEP_LIST: scient = Scient(element, s) scient.equip(eval(wep)(element, Stone())) scient.name = "Ms. " + wep self.append(scient) else: raise ("Kind requires element from %s." % ELEMENTS) if self.name == None: self.name = element + " " + 'mins' return if isinstance(data, list): for x in data: self.append(x) else: self.append(data)
def __init__(self, imm, addr, heap = 0x0, log = None ): """ Win32 Heap Lookaside list """ UserList.__init__(self) if not log: log = imm.log self.log = log self.imm = imm self.heap = heap self.Lookaside = [] LookSize = PLook(self.imm, 0x0).getSize() mem = imm.readMemory(addr, LookSize * HEAP_MAX_FREELIST) for ndx in range(0, HEAP_MAX_FREELIST): base_addr = addr + ndx * LookSize l = PLook(self.imm, base_addr, mem[ ndx * LookSize : ndx * LookSize + LookSize ], self.heap ) self.data.append(l) next = l.ListHead while next and next != base_addr: l.append( next - 8 ) try: next = self.imm.readLong(next) except: break
def __init__(self, file_name=None): """Creates a ReservationList composed by Reservation objects, from a file with a list of reservations. Requires: If given, file_name is str with the name of a .txt file containing a list of reservations organized as in the examples provided in the general specification (omitted here for the sake of readability). Ensures: if file_name is given: a ReservationList, composed by objects of class Service that correspond to the services listed in file with name file_name. if file_name is none: a empty ServiceList.""" UserList.__init__(self) if file_name is not None: inFile = FileUtil(file_name) for line in inFile.getContent(): reservData = line.rstrip().split(", ") reservClient = reservData[ReservationsList.INDEXClientNameInReservation] reservRequestedStartTime = Time(reservData[ReservationsList.INDEXRequestedStartHour]) reservRequestedEndTime = Time(reservData[ReservationsList.INDEXRequestedEndHour]) reservCircuit = reservData[ReservationsList.INDEXCircuitInReservation] reservCircuitKms = reservData[ReservationsList.INDEXCircuitKmsInReservation] newReserv = Reservation(reservClient, reservRequestedStartTime, reservRequestedEndTime, reservCircuit, reservCircuitKms) self.append(newReserv)
def __init__(self, name="Default deck", initlist=None): ''' Create a deck ''' UserList.__init__(self, initlist) self.name = name logging.info("Creating %s" % name)
def __init__(self, sFilename, sFormat): # The list stores all information contained in the file UserList.__init__(self) self.sFilename = sFilename self.sFormat = sFormat self.stylesheet = None assert self.sFormat in ["fixed", "free"]
def __init__(self, docstring=DEFAULTS['docstring'], options=DEFAULTS['options'], default=[], optional=DEFAULTS['optional'], values=DEFAULTS['values'], category=DEFAULTS['category'], callback=DEFAULTS['callback'], synopsis=DEFAULTS['synopsis'], environ=DEFAULTS['environ'], registry=DEFAULTS['registry'], delim=' ', range=[1, '*'], mandatory=None, name=DEFAULTS['name'], source=DEFAULTS['source'], template=StringOption): """ Initialize a multi argument """ self.delim = delim self.range = range assert not issubclass(template, MultiArgument), \ 'MultiArguments can not have a MultiArguments as a template' assert not issubclass(template, MultiOption), \ 'MultiOptions can not have a MultiOptions as a template' assert issubclass(template, GenericOption), \ 'Templates must be a subclass of GenericOption' self.template = template(options=options, name=name, values=values) UserList.__init__(self, []) GenericOption.initialize(self, locals())
def __init__(self,filename='',encoding='utf-8',linesep='\n'): UserList.__init__(self) if filename: self.linesep=linesep self.encoding=encoding self.filename=filename self.load()
def __init__(self, timeStr, collection=None): UserList.__init__(self) self.collection = collection self.timeStr = timeStr RepositorySearcher.__init__(self, collection=collection, xmlFormat='osm')
def __init__(self, numYears, quartersNotUsed, coursesTakenFileName, courseList, currentQuarter): """inits the parameters and objects in the schedule object""" UserList.__init__(self) self.numYears = numYears self.quartersNotUsed = quartersNotUsed # A - Autumn/Fall, W - Winter, Sp - Spring S - Summer self.quarters = quarterAbbrev = ['A', 'W', 'Sp', 'S'] # keeps track of courses added to the schedule self.coursesTaken = [] # the list of courses to be assigned to the quarters self.courseList = courseList # file name of courses taken so that they can be loaded into their respective quarters self.coursesTakenFileName = coursesTakenFileName # sets the total difficulty self.totalDifficulty = courseList.returnTotalDifficulty() # inits the difficulty upper bound self.difficultyUpperBound = float(courseList.returnTotalDifficulty()/courseList.returnNum()) # quarter to start planning {quarter : q, year : y} self.start = currentQuarter
def __init__(self, collection=None, xmlFormat=None, baseUrl=None): UserList.__init__(self) baseUrl = baseUrl or self.default_baseUrl if self.verbose: print 'baseUrl:', baseUrl self.timing = {} self.params = self.get_params(collection, xmlFormat) self.service_client = ServiceClient(baseUrl) self.numRecords = self._get_num_records() if self.verbose: print "%d total records" % self.numRecords s = 0 numToGet = min(self.numToFetch, self.numRecords) tics = time.time() self.getResults(numToGet) self.timing['download'] = time.time() - tics self.numFetched = len(self) tics = time.time() self.filterResults() self.timing['filter'] = time.time() - tics tics = time.time() self.processResults() self.timing['processing'] = time.time() - tics
def __init__(self, data = None, seq = [], restart=None): if isinstance(data, list): seq = data elif isinstance(data, dict): restart = data UserList.__init__(self, seq) self._up_to_date = False self.normalized = False self.spherical = False # prim -> primitives # cont -> contracted self._cont_types = None self._nprim_per_cont = None self._prim_coeffs = None self._assign_prim_to_cont = None self._assign_cont_to_atoms = None self._lxlylz = None self._assign_lxlylz_to_cont = None self._nlxlylz_per_cont = None self._lm = None self._assign_lm_to_cont = None #self.atom_indices = None #self.type_list = None #self.pnum_list = None #self.ao_coeffs = None #self.prim2cont = None #self.lxlylz = None #self.assign_lxlylz = None #self.bincount_lxlylz = None #self.lm = None #self.assign_lm = None if restart is not None: self._up_to_date = True self.normalized = restart['normalized'] self.spherical = restart['spherical'] self._assign_cont_to_atoms = restart['_assign_cont_to_atoms'] self._cont_types = restart['_cont_types'] self._nprim_per_cont = restart['_nprim_per_cont'] self._prim_coeffs = restart['_prim_coeffs'] self._assign_prim_to_cont = restart['_assign_prim_to_cont'] self._lxlylz = restart['_lxlylz'] self._assign_lxlylz_to_cont = restart['_assign_lxlylz_to_cont'] self._nlxlylz_per_cont = restart['_nlxlylz_per_cont'] self._lm = restart.get('_lm', None) self._assign_lm_to_cont = restart.get('_assign_lm_to_cont', None) self.internal_to_dict()
def __init__(self, path=data_worksheeet_path): UserList.__init__(self) self.ws = PubNamesWorkSheet(path) self.errors = [] print "%d worksheet records read" % len(self.ws) self.populate() self.reportErrors()
def __init__(self, data=None, name=None, kind=None, element=None): self.value = 0 self.free_spaces = 8 self.name = name UserList.__init__(self) if data == None: # The code below creates 4 units of element with a comp # of (4,2,2,0). Each unit is equiped with a unique weapon. if kind == 'mins': if element != None: s = Stone() s[element] = 4 s[OPP[element]] = 0 for o in ORTH[element]: s[o] = 2 for wep in WEP_LIST: scient = Scient(element, s) scient.equip(eval(wep)(element, Stone())) scient.name = "Ms. " + wep self.append(scient) else: raise("Kind requires element from %s." %ELEMENTS) if self.name == None: self.name = element + " " + 'mins' return if isinstance(data, list): for x in data: self.append(x) else: self.append(data)
def __init__(self, path="output/fy2010UpdateInfo.txt"): UserList.__init__(self) if not os.path.exists(path): raise IOError, "upfate info does not exist at %s" % path ids = open(path, 'r').read().split('\n') print "%d recs read from %s to %s" % (len(ids), ids[0], ids[-1]) for recId in ids: updateMetadata(changeSpec)
def __init__(self, cls, initial_list=None): UserList.__init__(self) if initial_list: for item in initial_list: if isinstance(item, cls): self.data.append(item) elif isinstance(item, dict): self.data.append(cls.from_json(item))
def __init__(self, quarter, year, courses = [], currentDifficulty = 0): """inits the quarter object""" UserList.__init__(self) self.quarter = quarter self.year = year # keeps track of the current difficulty of the quarter self.currentDifficulty = currentDifficulty
def __init__(self, l = None): if isinstance(l, basestring): UserList.__init__(self) self.add(l) return if l: l = [ PBXType.Convert(v) for v in l ] UserList.__init__(self, l)
def __init__(self, seq=None, fieldmapper=_donothing, storelists=1): list.__init__(self, seq or []) self.fieldmapper=fieldmapper self.__d={} self.storelists=storelists if seq: for s in seq: self.__register_field(s)
def __init__(self, seq=None, fieldmapper=_donothing, storelists=1): list.__init__(self, seq or []) self.fieldmapper = fieldmapper self.__d = {} self.storelists = storelists if seq: for s in seq: self.__register_field(s)
def __init__(self, f=None, procmail=""): UserList.__init__(self) if procmail: self.procmail = "|%s " % procmail else: self.procmail = "" self.pmlen = len(self.procmail) self.addrs = self.data if f: if hasattr(f, "read"): self.parse(f.read()) else: self.parse(f)
def __init__(self, l=None): if isinstance(l, basestring): UserList.__init__(self) self.add(l) return elif l: l = [PBXType.Convert(v) for v in l] UserList.__init__(self, l)
def __init__(self, data=[]): UserList.__init__(self) self.feature_no = None self.name = None self.class_omega = None self.init_precomputed() self.classadmin = pylib_basics.name_number_hash() for i in data: self.append(i)
def __init__(self, collection): UserList.__init__(self) self.collection = collection self.dataPath = os.path.join(self.baseDir, collection + '.xml') print "DATA_PATH: ", self.dataPath self.rec = XmlRecord(path=self.dataPath) nodes = self.rec.selectNodes(self.rec.dom, "collectionInfo:rec") print "%d recs read from meta-metadata" % len(nodes) map(self.append, map(RecordInfo, nodes))
def __init__(self): UserList.__init__(self) self.tables = {} # _table_names entries relate a paramter line name to a table and # its Entry object name. The tables are defined in external text # files. for param, tabledata in self.__class__._table_names.items(): tablename, rowclass = tabledata self.tables[param] = (ParameterTable(tablename), rowclass)
def __init__ (self, path): UserList.__init__ (self) lines = open (path, 'r').read().split('\r\n') # windows print "%d lines read" % len (lines) self.schema = lines[0].split('\t') for line in lines[1:]: if line: self.append (WOSRecord (line, self.schema))
def __init__ (self, data_file): UserList.__init__ (self) self.data_file = data_file raw = open(self.data_file, 'r').read() lines = raw.split('\n') # print len(lines), 'lines read' for line in lines: if not line.strip(): continue if line[0] == '#': continue self.append(line)
def __init__(self, dirname): self.dirname = dirname data = [] for filename in os.listdir(self.dirname): absolute_filename = os.path.join(self.dirname, filename) if os.path.isfile(absolute_filename): try: data.append(BackupFile.from_filename(filename)) except (ValueError, KeyError): pass UserList.__init__(self, data)
def __init__ (self, path="output/MetadataModifySpecs.xml"): UserList.__init__ (self) if not os.path.exists(path): raise IOError, "output does not exist at %s" % path updateInfoDoc = XmlRecord(path=path) updateInfos = updateInfoDoc.selectNodes (updateInfoDoc.dom, "changeSpecs:pubNameSpec") print "%d specs found" % len(updateInfos) for info in updateInfos: changeSpec = ChangeSpec (info) print changeSpec self.updateMetadata (changeSpec)
def __init__(self, path): UserList.__init__(self, []) self.path = path data = [] if os.path.exists(path): for filename in os.listdir(path): if self._accept(filename): data.append(filename) data.sort(self._cmp) self.data = data
def __init__(self, dirname): UserList.__init__(self) self.dirname = dirname # print "Users dirname: ", self.dirname for filename in os.listdir(self.dirname): path = os.path.join(self.dirname, filename) root, ext = os.path.splitext(filename) # print 'ext', ext if not ext.lower() == ".xml": continue self.append(User(path))
def __init__(self, F=None, X=None, Y=None): #def __init__(self): UserList.__init__(self) #self.data=WalkingList() self.i = 0 self.repetitions = 1 self.n = 0 if (F != None) & (X != None) & (Y != None): self.append(F, X, Y) self.dataind = -1 return
def __init__(self, values=None): """ Subclassing requirements: Subclasses of UserList are expected to offer a constructor which can be called with either no arguments or one argument. List operations which return a new sequence attempt to create an instance of the actual implementation class. To do so, it assumes that the constructor can be called with a single parameter, which is a sequence object used as a data source. :param listElements: List of initial elements """ UserList.__init__(self, values)
def __init__ (self, items=None): if items != None: invalid = filter (lambda x: not isinstance (x, ListItem), items) if len (invalid) != 0: raise ValueError ("items must contain only ListItem objects") UserList.__init__ (self, items) self._length = 0 # Notifier slots. self._listchanged = None self._itemchanged = None
def __init__(self, path): UserList.__init__(self, []) self.path = path data = [] for filename in os.listdir(path): filepath = os.path.join(path, filename) ## if not os.path.isdir (filepath) and not filename[0] == '.': if self.acceptFile(filename): data.append(filename) data.sort(self._cmp) self.data = data
def __init__(self, type, fetch=False, recursive=1, fields=None, filters=None, parent_uuid=None, **kwargs): UserList.__init__(self) self.type = type self.fields = fields or [] self.filters = filters or [] self.parent_uuid = list(self._sanitize_parent_uuid(parent_uuid)) self.meta = dict(kwargs) if fetch: self.fetch(recursive=recursive) self.emit('created', self)
def __init__ (self, xsdpath): UserList.__init__ (self) s = codecs.open(path, 'r', 'utf-8').read() ## print s.encode('utf-8') m = restriction_pat.search (s) if not m: raise Exception, "restriction tag contents not found" lines = map (string.strip, m.group(1).split('\n')) lines = filter (lambda x: x, lines) self.data = map (VocabTerm, lines) self.sort()
def __init__(self, items=None): if items != None: invalid = filter(lambda x: not isinstance(x, ListItem), items) if len(invalid) != 0: raise ValueError("items must contain only ListItem objects") UserList.__init__(self, items) self._length = 0 # Notifier slots. self._listchanged = None self._itemchanged = None
def __init__(self, dirname): self.dirname = dirname data = [] for filename in os.listdir(self.dirname): absolute_filename = os.path.join(self.dirname, filename) if os.path.isfile(absolute_filename): try: data.append(BackupFile.from_filename(filename)) except (ValueError, KeyError): log.debug("Can't handle %s", absolute_filename) else: log.debug("%s isn't a file", absolute_filename) UserList.__init__(self, data)
def __init__ (self, line): self.line = line UserList.__init__ (self) self.cur_field = '' self.infield = 0 # start off collecting field data self.start_field_chars = self.field_brackets.keys() self.end_char = None self.parse() try: self.timestamp = self.get_timestamp() except: raise Exception, 'Could NOT parse time for %s' % self['datetime']
def __init__(self, dirname): self.dirname = dirname data = [] for filename in os.listdir(self.dirname): absolute_filename = os.path.join(self.dirname, filename) if os.path.isfile(absolute_filename): try: data.append(BackupFile.from_filename(filename)) except (ValueError, KeyError): logger.debug("Can't handle %s", absolute_filename) else: logger.debug("%s isn't a file", absolute_filename) UserList.__init__(self, data)
def __init__(self,F=None,X=None,Y=None,level=[]): UserList.__init__(self) self.i=0 self.repetitions=1 self.n=0 if (F != None) & (X != None) & (Y != None): self.append(F,X,Y) self.dataind=-1 import copy self.level = copy.copy(level) self.level.append(-1) print "Level: ",self.level return
def __init__(self, term, searchFields): UserList.__init__(self) self.term = term if type(searchFields) == type(""): self.searchFields = [searchFields] else: self.searchFields = searchFields self.params = self.get_params(None, None) self.service_client = ServiceClient(self.baseUrl) self.numRecords = self._get_num_records() if self.verbose: print "%d total records" % self.numRecords
def __init__(self, F=None, X=None, Y=None, level=[]): UserList.__init__(self) self.i = 0 self.repetitions = 1 self.n = 0 if (F != None) & (X != None) & (Y != None): self.append(F, X, Y) self.dataind = -1 import copy self.level = copy.copy(level) self.level.append(-1) print "Level: ", self.level return
def __init__(self, type, fetch=False, recursive=1, fields=None, detail=None, filters=None, parent_uuid=None, back_refs_uuid=None, data=None): UserList.__init__(self, initlist=data) self.type = type self.fields = fields or [] self.filters = filters or [] self.parent_uuid = list(self._sanitize_uuid(parent_uuid)) self.back_refs_uuid = list(self._sanitize_uuid(back_refs_uuid)) self.detail = detail if fetch: self.fetch(recursive=recursive) self.emit('created', self)
def __init__(self, object, methodNameList): UserList.__init__(self) # if the description had None for a list, return an empty list if not methodNameList: return; for methodName in methodNameList: try: method = getattr(object, methodName) except AttributeError: raise ValueError, 'action "%s" not found' % methodName else: if not callable(method): raise AttributeError, 'action "%s" not callable' % methodName self.append(method)
def __init__(self, data=None, name=None): self.value = 0 self.free_spaces = 8 self.name = name UserList.__init__(self) if data == None: return if isinstance(data, list): for x in data: self.append(x) else: self.append(data) self.data = self.datadata del self.data
def __init__(self, data=None, elementType=None, stringRepr=None, comments="", keywords=[]): if data is not None and len(data)!=0: assert( hasattr(data[0], '__class__') ) if elementType is not None: assert( isinstance(data[0], elementType) ) UserList.__init__(self, data) # save call to __setattr__ self.__dict__['elementType'] = elementType #self.elementType = elementType # class of elements in that set self.stringRepr = stringRepr # this will hold a concise string repr of # the set of objects in that list self.__dict__['comments'] = comments self.__dict__['keywords'] = keywords self.selector = None
def fill(self): """Separate method used to refresh the ScriptLog data structure from file""" # Clean up all data structures for each fill UserList.__init__(self) buffer = () self.warn = {} self.crit = {} self.ack = {} # Create new array to hold log data if os.path.exists(self.filename): buffer = self.open_file(self.filename) else: print "File does not exist:", self.filename sys.exit(16) # Buffer has bow been created and work with file is done # Now it is time to determine what kind of objects will be # used for construction of self. # Finally, build self with the ScriptlogEntries for line in buffer: # Test line to make sure it is a ScriptLog entry, then add if ScriptlogEntry.is_type(line, self.label): # Setup main list (self) self.append(ScriptlogEntry(line.expandtabs())) # Setup supporting dictionaries # Set Entry entry = self[len(self)-1] # Parse warning items if entry.type == ScriptLog.labels["warn"]: self.warn[entry.id] = True # Parse critical items if entry.type == ScriptLog.labels["crit"]: self.crit[entry.id] = True # If a genuine ack is found, increment if entry.type == ScriptLog.labels["ack"]: self.ack[entry.id] = True
def __init__(self, drivers=None, vehicles=None, services=None): """Creates a new DetailedServicesList composed by DetailedServices that are extensions of Services with more information about the driver and vehicles. Requires: drivers is a DriverList, vehicles is a VehicleList and services is a ServiceList. drivers, vehicles and services concern the same period. Ensures: a DetailedServicesList object whose members are DetailedService objects resulting from the extension of Service objects with information of Driver and Vehicle objects. If some of the arguments is not given, it creates an empty DetailedServicesList""" # Creates empty DetailedServicesList UserList.__init__(self) # If some of the arguments is not give, DetailedServicesList stays empty if (drivers is not None) and (vehicles is not None) and (services is not None): services.reverse() driversInWaitingList = [] waitingList = ServicesList() # Obtains sublist SL for service in services: driver = service.getServiceDriver() driverTerminated = service.getServiceDriverStatus() == Driver.STATUSTerminated if (driver not in driversInWaitingList) and (not driverTerminated): if service.getServiceDriverStatus() == Driver.STATUSCharging: service.resetVehic() driversInWaitingList.append(driver) waitingList.append(service) # Creates a list of services with further data items for service in waitingList: drivername = service.getServiceDriver() driver = drivers[drivername] vehicleplate = service.getServicePlate() vehicle = vehicles[vehicleplate] detailedService = DetailedService(driver, vehicle, service) self.append(detailedService) # Sorting according to increasing availability time, # untying with drivers's names self.sort()
def __init__(self, initlist=None): # Several methods to construct a Blockset. # Method 1: Provide another Blockset via initlist if isinstance(initlist, BlockSet): BlockSet.__init__(initlist.data) # Method 2: provide a list of blocks via initlist elif initlist != None: initlist = list(initlist) if not all([isinstance(b, Block) for b in initlist]): raise ValueError('[Error] Encountered input error for initlist. ' + 'initlist contains non-Blocks') UserList.__init__(self, initlist)
def __init__(self, filename=None, pattern=None): """provide the list object as a list of files""" UserList.__init__(self) self.data = [] if pattern == None: self.filetype = "[A-Za-z0-9]" else: self.filetype = pattern self.path = "." try: mode = os.stat(filename)[ST_MODE] if S_ISDIR(mode): self.read_the_filenames(filename) elif S_ISREG(mode): self.data.append(filename) else: print 'Skipping %s' % filename except OSError, err: print "Error: " + err.strerror + ": " +filename sys.exit(1)
def __init__(self, filename=""): UserList.__init__(self) buf = list() if filename == "": return elif filename == "__none__": self.f = sys.stdin else: logging.debug("Opening File: " + filename) self.f = open(filename) for line in self.f.xreadlines(): buf.append(line) if len(buf) < 1: print "No data found" sys.exit() # Automatically select entry type self.Entry = self.select(buf) # Save for introspective purpose self.payload_type = self.Entry.__name__ self.file_name = filename self.build_date = datetime.datetime.now() # Build from entry type counter = 0 for line in buf: try: self.append(self.Entry(line)) counter += 1 except (ValueError, TypeError): print "Cannot parse values on line: " + str(counter) sys.exit() del buf
def __init__(self, file_name=None): """Creates a ServicesList composed by Services objects, from a file with a list of services. Requires: If given, file_name is str with the name of a .txt file containing a list of services organized as in the examples provided in the general specification (omitted here for the sake of readability). Ensures: if file_name is given: a ServiceList, composed by objects of class Service that correspond to the services listed in file with name file_name. In this ServiceList, drivers terminating their services earlier have priority over the ones terminating later; lexicographic order of drivers's names decides eventual ties in each case above. if file_name is none: a empty ServiceList. """ # creates empty ServicesList UserList.__init__(self) # if file_name is given, self is populated with Services corresponding to the # services on the file file_name if file_name is not None: inFile = FileUtil(file_name) for line in inFile.getContent(): servData = line.rstrip().split(", ") servDriver = servData[ServicesList.INDEXDriverName] servPlate = servData[ServicesList.INDEXVehiclePlate] servClient = servData[ServicesList.INDEXClientName] servDeparTime = Time(servData[ServicesList.INDEXDepartureHour]) servArrivalTime = Time(servData[ServicesList.INDEXArrivalHour]) servCircuit = servData[ServicesList.INDEXCircuitId] servCircuitKms = servData[ServicesList.INDEXCircuitKms] servDriverStatus = servData[ServicesList.INDEXDriverStatus] newService = Service(servDriver, servPlate, servClient, servDeparTime, servArrivalTime, \ servCircuit, servCircuitKms, servDriverStatus) self.append(newService)