Example #1
0
 def __init__(self, settings = None):
     UserDict.__init__(self, DEFAULTS)
     if settings is not None:
         if 'zonesdbcfg' in settings:
             import getzones
             getzones.__dict__.update(settings.pop('zonesdbcfg'))
         self.data.update(settings)
Example #2
0
 def __init__(self, data):
     UserDict.__init__(self, data)
     try:
         self.conn = MySQLdb.connect(host=self.get('host'), user=self.get('user'), passwd=self.get('pwd'), db=self.get('db'), port=self.get('port'))
     except Exception, err:
         print err
         sys.exit()
Example #3
0
File: Cookie.py Project: jeske/csla
    def __init__(self, input=None,
                 net_setfunc=_debabelize, user_setfunc=_babelize,
		 domain="", 
		 path="/", 
		 expires="Thu, 15 Apr 2010 20:00:00 GMT", maxage=31536000,
                 browser=""):
        self.net_setfunc   = net_setfunc   # when set from network
        self.user_setfunc  = user_setfunc  # when set by user
        UserDict.__init__(self)
        if input: self.load(input)

	self.domain = domain
	self.expires = expires
	self.path = path
        self.maxage = maxage
        self.browser = browser
        # Certain older browsers don't support setting of attributes
        # on cookies, at least not the new attributes like Max-Age
        # These browsers will probably break at Y2K as well, in which case
        # we need to stop sending an EXPIRE time based on this setting
        self.old_browser = 0
        if self.old_browser_re is None:
          self.old_browser_re = re.compile ("MSIE 3.0")
        m = self.old_browser_re.search (browser)
        if m:
          self.old_browser = 1
 def __init__(self, name = '', kind = 'module', ispkg = 0):
     UserDict.__init__(self)
     self.imports = {'plain': [], 'from': []}
     self.activated = 0
     self.ispkg = ispkg
     self.name = name
     self.kind = kind
Example #5
0
    def __init__(self,file):

        self.file = file
        self.unicode = [None,] * 65536

        try:
            lines = open(self.file).readlines()
        except IOError:
            sys.stderr.write("ads.Unicode: Warning: annot open Unicode Table file %s\n" % self.file)
            raise IOError,"Cannot open Unicode Table "+self.file
        else:
            UserDict.__init__(self)
            for line in lines:
                fields = line.split()
                fields = [ field.replace('"','') for field in fields ]

                if len(fields) > 3:
                    try:
                        code = int(fields[0].split(':')[0].split(';')[0])
                        entity = fields[1]
                        self[entity] = UnicodeChar(fields)  # keep entity table

                        if len(fields) > 4:    # keep code table
                            if not self.unicode[code]:
                                self.unicode[code] = self[entity]
                            else:
                                pass
                    except ValueError:
                        pass
Example #6
0
	def __init__(self, defaults = {}, types = {}):
		"""Constructor.
			If any filenames given tries to parse them
			Input: (string) filename. You can pass pultiple file names
				(dict) defaults: {'section': {'attrib': 'value'}},
				(dict) types: {'section': {'attrib': 'type'}};
				See Typecast.py for supported types.
			Output: (Config) class instance
		"""
		UserDict.__init__(self) # create self.data
		self.cliParser = None # we don't need CLI parser by default
		self.fileParser = SafeConfigParser()
		self._types = types
		self._defaults = defaults
		
		# set defaults in configfile parser
		fileParser = self.fileParser
		for (section, attributes) in defaults.items():
			section = str(section)
			if not fileParser.has_section(section):
				fileParser.add_section(section)
			for (key, value) in attributes.items():
				key = str(key)
				value = str(value)
				key = fileParser.optionxform(key)
				fileParser.set(section, key, value)
		
		# store parsed default values
		self.storeParsedFileItems()
Example #7
0
    def __init__(self, action, ec):

        if isinstance(action, dict):
            lazy_keys = []
            UserDict.__init__(self, action)
            if 'name' in self.data:
                self.data.setdefault( 'id', self.data['name'].lower() )
                self.data.setdefault( 'title', self.data['name'] )
                del self.data['name']
            self.data.setdefault( 'url', '' )
            self.data.setdefault( 'category', 'object' )
            self.data.setdefault( 'visible', True )
            self.data['available'] = True
        else:
            # if action isn't a dict, it has to implement IAction
            (lazy_map, lazy_keys) = action.getInfoData()
            UserDict.__init__(self, lazy_map)

        self.data['allowed'] = True
        permissions = self.data.pop( 'permissions', () )
        if permissions:
            self.data['allowed'] = self._checkPermissions
            lazy_keys.append('allowed')

        self._ec = ec
        self._lazy_keys = lazy_keys
        self._permissions = permissions
    def __init__(self, model, query_parameters, *args, **kwargs):
        self._model = model

        # Core options, not modifiable by client updates
        if "columns" not in kwargs:
            model_fields = model._meta.local_fields
            kwargs["columns"] = map(lambda f: f.verbose_name.capitalize(), model_fields)

        if "hidden_columns" not in kwargs or kwargs["hidden_columns"] is None:
            kwargs["hidden_columns"] = []

        if "search_fields" not in kwargs or kwargs["search_fields"] is None:
            kwargs["search_fields"] = []

        # Absorb query GET params
        kwargs = self._normalize_options(query_parameters, kwargs)

        UserDict.__init__(self, DEFAULT_OPTIONS, *args, **kwargs)

        self._flat_column_names = []
        for field_name in self.columns:
            if isinstance(field_name, (tuple, list)):
                pretty_name, field_name = field_name[:2]

            if not field_name or isinstance(field_name, (tuple, list)):
                field_name = pretty_name

            self._flat_column_names.append(field_name)
Example #9
0
    def __init__(self,tempdir=None,stdin=None,stderr=None,stdout=None,
                 executor=Popen,use_defIOE=0,name=None,cleanup=0,args=None,logfile=None):
        '''main functionality is to determine default temp dir and I/O/E settings

        '''
        UserDict.__init__(self)

            
        self["executor"] = executor
        self['cleanup'] = cleanup
        self['files'] = []
        self['logfile'] = logfile
        self['out'] = None

        if args:
            self.controller_type = os.path.basename(args[0])
            self['args'] = args

        if name:
            self["name"] = name
        else:
            self["name"] = random_filename(prefix=self.controller_type)

        if tempdir: #no longer calls setitem, must do this manually, or in compose_arg
            self.data["tempdir"] = tempdir
        else: #not explicitly set by call; wait on dir creation
            prog = sys.argv[0] and sys.argv[0] or self.__module__
            self.data["tempdir"] = os.path.join(paths["temp"],os.path.basename(prog))

        #if use_defIOE=1 set stdin, stderr and stdout based on self.default_IOE(),
        #otherwise use individual arguments
        #since assignment is to self.data instead of self, __setitem__ behaviors do not fire
        (self.data["stdin"],self.data["stdout"],self.data["stderr"]) = \
            use_defIOE and self.default_IOE() or (stdin,stdout,stderr)
Example #10
0
	def __init__(self, object, message, valueDict={}, **valueArgs):
		""" Initializes an error with the object the error occurred for, and the user-readable error message. The message should be self sufficient such that if printed by itself, the user would understand it. """
		UserDict.__init__(self)
		self._object    = object
		self._message   = message
		self.update(valueDict)
		self.update(valueArgs)
Example #11
0
    def __init__(self,parent=None):
        UserDict.__init__(self)

        assert parent is None or isinstance(parent,CommandDict)
        self.__parent = parent

        self.__lookuptable = {}
Example #12
0
 def __init__(self, filename=""):
     """initialize with content of patternfile"""
     UserDict.__init__(self)
     self.data = {}
     self.cnt = 1
     if len(filename) > 0:
         self.__read_pattern_file(filename)
 def __init__(self,filename=None):
     UserDict.__init__(self)
     if filename:
         self.load(filename)
         
     self._filter=None
     self._ref_re=re.compile(r' +\| +')
Example #14
0
 def __init__(self, name, check_list, minions=(), **kwargs):
     self.minions = []
     self.name = name
     self.check_list = check_list
     for minion in minions:
         self.minions.append(minion)
     UserDict.__init__(self, **kwargs)
Example #15
0
 def __init__(self):
     UserDict.__init__(self)
     self['meta']= {}
     self['faces'] = []
     self['nc_codes']= self._nc_codes()
     # stop this business of user dict subclassing, it's useless here
     self['reg'] = self._reg()
	def __init__( self, binaryDataString ):
		UserDict.__init__( self )
		self.binaryData = binaryDataString
		self.length = len( self.binaryData ) - 2
		self.calculateChecksum()
		if self.checksum:
			self.interpretBinaryData()
    def __init__(self, changes={}):
        UserDict.__init__(self)

        self.network_config = NetworkConfig()
        self.outer_network_config = OuterNetworkConfig()
        self.output_config = OutputConfig()
        self.choice_set_config = ChoiceSetConfig()
        self.assign_config = AssignConfig()

        # location of travel data in matsim format
        self["travel_dir"] = r"X:\Projects\BikeModel\data\bike_model\input\travel\2010_04_18"

        # directory with trip start times in hours on 24 hr clock
        self["time_file"] = r"X:\Projects\BikeModel\data\bike_model\input\context\2010_04_18\time.csv"

        # to holdback a sample of observations from estimation to use for validation
        self["use_holdback_sample"] = True
        self["holdback_rate"] = 0.10
        self["holdback_from_file"] = True
        self["holdback_file"] = r"X:\Projects\BikeModel\data\bike_model\input\holdback\Holdback.csv"

        self["n_processes"] = 4

        """deprecated"""
        # rules to lookup time dependent variables in network data { variable in choice_set_config : [ ( (time lower bound, time upper bound) , variable to lookup), ... ,('else', variable to lookup if time outside preceeding bounds) ]}
        # else condition must be last for each rule
        self["time_dependent_relation"] = {
            "V": [((3, 6), "V_EA"), ((6, 9), "V_AM"), ((9, 15.5), "V_MD"), ((15.5, 18.5), "V_PM"), ("else", "V_EV")]
        }

        # this gives the location of travel data with chosen routes that are hard to reproduce, used in route_model.evaluate_parameters
        self["imperfect_file"] = r"X:\Projects\BikeModel\data\bike_model\input\optim\imperfect.csv"

        for key in changes:
            self[key] = changes[key]
Example #18
0
 def __init__(self, deviceData=None, address=None):
     UserDict.__init__(self)
     self["data"] = deviceData
     self["address"] = address
     #self["geocoding"] = None
     # Fecha y hora (del sistema)
     self["datetime"] = datetime.datetime.now()
 def __init__(self, name, config, workload, dbs):
     UserDict.__init__(self)
     self.name           = name
     self.num_nodes      = config['num_nodes']
     self.category       = config['category']
     self._dbs           = dbs
     self.update_time    = workload['timestamp']
     self["name"]        = self.name
     self['num_nodes']   = self.num_nodes
     self['category']    = self.category
     self["update_time"] = self.update_time
     if self.category == "hpc":
         # we have a list of Queue instances, to inspect queue information,
         # indexed by queue name
         self.queues = dict()
         for queue_name in config['queue_info']:
             self.queues[queue_name] = Queue(self.name, queue_name,
                                             config['queue_info'][queue_name],
                                             workload[queue_name])
         self['queues'] = self.queues
     elif self.category == "grid":
         self.num_queueing_jobs    = workload['num_queueing_jobs']
         self.busy_jobslots        = workload['busy_jobslots']
         self.idle_jobslots        = workload['idle_jobslots']
         self["num_queueing_jobs"] = self.num_queueing_jobs
         self["busy_jobslots"]     = self.busy_jobslots
         self["idle_jobslots"]     = self.idle_jobslots
         self.sites  = dict()
         for site_name in config['site_info']:
             self.sites[site_name] = Site(self.name, site_name,
                                          config['site_info'][site_name],
                                          workload[site_name])
         self['sites'] = self.sites
Example #20
0
    def __init__(self, rawItems):
        """Canonicalize a dictionary of configuration items.

        Values in a configuration item dictionary are, canonically, an object
        subclassed from black.configure.Item. However, shortcuts are allowed
        for specification. For example, a Blackfile could simple set a string
        value to create a configuration datum that is always applicable, has
        no related configuration option, and whose value is that string.
        """
        UserDict.__init__(self)
    
        for name, item in rawItems.items():
            if item is None:
                continue
            elif isinstance(item, (int, long, float, str, tuple, list, dict)):
                # this is a simple Datum()
                self.data[name] = Datum(name, value=item)
            elif type(item) == types.InstanceType:
                # this had better be an instance subclassed from class Item
                if isinstance(item, Item):
                    self.data[name] = item
                else:
                    raise ConfigureError("The configuration item '%s' does "\
                        "not derive from class %s.\n" % (name, Item))
            else:
                raise ConfigureError("Don't know how to massage a "\
                    "configuration item of type %s: %s" % (type(item), item))
Example #21
0
 def __init__(self, name):
     """
     Class which serves as a placeholder for
     player's data
     """
     UserDict.__init__(self)
     self.dict_file = DictFile(name)
     temp = self.dict_file.read()
     for key, value in temp.items():
         self[key] = value
     self.buying = False
     self.passed = 0
     self.killed = 0
     self.lpassed = 0
     self.newa = False
     self.lost = False
     self.passed = 0
     self.failed = 0
     self.collected = 0
     self.charges = 0
     self.hasscroll = 0
     self.tw = 0
     self.sp = 0
     self.paused = 1
     self["magicka"] = 0
Example #22
0
    def __init__(self, log):

        # Call parent init
        UserDict.__init__(self)

        # Turn first line into syslog
        if len(log) > 0:
            first_entry = log[0]
        else:
            sys.exit()

        # Local Variables
        counter = 0
        self.second = 0
        self.minute = 0
        self.hour = 0
        self.day = 1
        self.month = str(first_entry.month)
        self.year = first_entry.year
        self.unit = "month"
        self.duration = 12

        start_date = datetime.datetime(
            int(self.year), int(self.month), int(self.day), int(self.hour), int(self.minute), int(self.second)
        )
        start_key = start_date.year + start_date.month

        # Zero out each entry, this will fill in blanks which
        # may be in the log, especially sparse logs.
        for i in range(0, self.duration):

            # Calculate the current date, the last one will be the end date
            end_date = start_date + datetime.timedelta(days=i * 365 / 12 + 1)
            end_key = str(end_date.year) + str("%.2d" % (end_date.month))
            self.zero(end_key)
            logging.debug("End Date: " + str(end_date))
            logging.debug("End Key: " + end_key)

            # Check for middle date and save
            if i == (self.duration / 2):
                middle_date = end_date

        # Save final values
        self.start_date = start_date
        self.middle_date = middle_date
        self.end_date = end_date

        # Create a dictionary with an entry for each line. Increment
        # the value for each time the word is found. Merge lines by
        # Removing numbers and replacing them with a single '#'
        for entry in log:

            # Create key rooted in time
            key = entry.year + entry.month

            # Check to make sure key is found in the list built above
            if key in self.keys():
                self.increment(key)

        self.build_calculations()
Example #23
0
 def __init__(self, init_dict=None, **kwargs):
     UserDict.__init__(self)
     self.child_classes = {}
     self.conf_vars = {}
     for cls in iterbases(self, ConfBase):
         if hasattr(cls, "_child_classes"):
             for key, val in cls._child_classes.iteritems():
                 self.child_classes[key] = val
         if hasattr(cls, "_conf_vars"):
             for conf_var in cls._conf_vars:
                 if isinstance(conf_var, basestring):
                     conf_var = {"name": conf_var}
                 conf_var = ConfVar(conf_var)
                 self.conf_vars[conf_var.name] = conf_var
     json_str = kwargs.get("json_str")
     if json_str is not None:
         del kwargs["json_str"]
         init_dict = json.loads(json_str)
     if init_dict is None:
         init_dict = {}
     else:
         print init_dict
         print repr(init_dict)
     for key, val in init_dict.iteritems():
         self[key] = val
     for key, val in kwargs.iteritems():
         self[key] = val
     for key, val in self.child_classes.iteritems():
         if key not in self:
             self[key] = val()
     self.do_init(**kwargs)
Example #24
0
    def __init__(self, datasrc, defaultcontext=None):
        """
        Arguments:
        
        datasrc -- The data source for this instance. May be given in
        any of three forms: (1) the name of a CSS file, (2) a string
        containing style data in CSS syntax, or (3) a dictionary in
        the same form as self.data

        defaultcontext -- (OPTIONAL) The default context from which
        others inherit properties. If your stylesheet is for an
        ordinary web page, for example, you might use "BODY" as a
        default context. Must be present in the data source.

        """
        UserDict.__init__(self)
        if type(datasrc) is type({}):
            self.data = datasrc
        else:
            if os.path.isfile(datasrc):
                cssdata = self._readin(datasrc)
            elif type(datasrc) is type(""):
                cssdata = datasrc
            else:
                raise RuntimeError, "Invalid data type: %s" % type(datasrc)
            self._parse(cssdata)
        self.defaultcontext = defaultcontext
    def __init__(self, file_name=None):
        """Creates a VehicleDict composed by vehicles objects,
        from a file with a list of vehicles.

        Requires: If given, file_name is str with the name of a .txt file containing
        a list of vehicles organized as in the examples provided in
        the general specification (omitted here for the sake of readability).
        Ensures:
        if file_name is given:
            a VehiclesDict, composed by objects of class Vehicle that correspond to the vehicles listed
            in file with name file_name.
        if file_name is none:
            a empty VehiclesList.
        """

        UserDict.__init__(self)

        inFile = FileUtil(file_name)
        for line in inFile.getContent():
            vehicleData = line.rstrip().split(", ")
            vehiclePlate = vehicleData.pop(VehiclesDict.INDEXVehiclePlate)
            vehicleModel, vehicleAutonomy, vehicleKms = vehicleData
            newVehicle = Vehicle(vehiclePlate, vehicleModel, vehicleAutonomy, vehicleKms)

            self[vehiclePlate] = newVehicle
Example #26
0
    def __init__(self, action, ec):

        if isinstance(action, dict):
            lazy_keys = []
            UserDict.__init__(self, action)
            if "name" in self.data:
                self.data.setdefault("id", self.data["name"].lower())
                self.data.setdefault("title", self.data["name"])
                del self.data["name"]
            self.data.setdefault("url", "")
            self.data.setdefault("category", "object")
            self.data.setdefault("visible", True)
            self.data["available"] = True
        else:
            # if action isn't a dict, it has to implement IAction
            (lazy_map, lazy_keys) = action.getInfoData()
            UserDict.__init__(self, lazy_map)

        self.data["allowed"] = True
        permissions = self.data.pop("permissions", ())
        if permissions:
            self.data["allowed"] = self._checkPermissions
            lazy_keys.append("allowed")

        self._ec = ec
        self._lazy_keys = lazy_keys
        self._permissions = permissions
Example #27
0
 def __init__(self, filename, _ser=None, _load=True, _open_cm=None):
     UserDict.__init__(self)  ## Just to honour it
     if _ser is None:
         _ser = {'dump': json.dump, 'load': json.load}
     ## Allow specifying dumps/loads instead of dump/load
     if 'dump' not in _ser:
         _ser = dict(_ser, dump=_dumps_to_dump(_ser['dumps']))
     if 'load' not in _ser:
         _ser = dict(_ser, dump=_loads_to_load(_ser['loads']))
     ## ...
     self._ser = _ser
     ## Prefer AtomicFile for writing if available.
     if _open_cm is None:
         try:
             from atomicfile import AtomicFile
         except Exception:
             ## Alas, nope
             _open_cm = open
         else:
             _open_cm = AtomicFile
     self._open_cm = _open_cm
     ## ...
     self._filename = filename
     data = {}
     if _load:
         data = self.try_load() or data
     self.data = data
Example #28
0
	def __init__(self):
		"""default setup is beta-uniform"""
		UserDict.__init__(self)
		
		self['variables']=[]
		self['zero']={}
		self['pos']={}
Example #29
0
	def __init__(self):
		# Set defaults
		self.key = self.value = self.coded_value = None
		UserDict.__init__(self)

		# Set default attributes
		for K in self.__reserved_keys:
			UserDict.__setitem__(self, K, "")
Example #30
0
 def __init__(self, basename, textLine):
     UserDict.__init__(self)
     self["files"] = []
     self["name"] = basename
     chunks = textLine.split()
     if chunks[0] != "Directory":
         raise Exception("A textline given to Directory() doesnt start with Directory: " + chunks[0])
     get_key_value_pairs(string.join(chunks[2:]), Directory.allowed_keys, self)
 def __init__(self, textLine, directory):
     UserDict.__init__(self)
     chunks = textLine.split()
     if chunks[0] != 'File':
         raise Exception(
             "A textline given to File() doesnt start with File: " +
             chunks[0])
     self['path'] = directory + chunks[1]
     self['name'] = chunks[1]
     get_key_value_pairs(string.join(chunks[2:]), File.allowed_keys, self)
Example #32
0
 def __init__(self, h, k, amp, phase):
     UserDict.__init__(self)
     self.h = int(h)
     self['h'] = self.h
     self.k = int(k)
     self['k'] = self.k
     self.amp = float(amp)
     self['amp'] = self.amp
     self.phase = float(phase)
     self['phase'] = self.phase
Example #33
0
 def __init__(self,prefix=""):
     UserDict.__init__(self)
     self.reset()
     self.nextlabel = 0
     self.nextTemp = 0
     self.nextEnum = 0
     self.nextParamSlot = 0
     self.var_params = []
     self.prefix = prefix
     self.temp_prefix = "t__%s" % prefix
Example #34
0
 def __init__(self, keyvalues=(), **other):
     _base.__init__(self)
     try:
         keyvalues = keyvalues.items()
     except AttributeError:
         pass
     for k, v in keyvalues:
         _base.__setitem__(self, k, v)
     _base.update(self, other)
     self._hash = hash(tuple(self.items()))
Example #35
0
 def __init__(self):
     UserDict.__init__(self)
     rec = XmlRecord('output/FINAL-accessionNumberMappings.xml')
     mappings = rec.selectNodes(rec.dom, 'accessionNumberMappings:mapping')
     print '%d mappings found' % len(mappings)
     for mapping in mappings:
         drNum = mapping.getAttribute("drNumber")
         queryString = mapping.getAttribute("queryString")
         # print '%s -> %s' % (drNum, queryString)
         self[drNum] = queryString
    def __init__(self, maxSize):
        UserDict.__init__(self)
        assert maxSize > 0
        self.maxSize = maxSize
        self.krono = []
        self.maxdepth = 0

        self.killer1 = [-1] * 20
        self.killer2 = [-1] * 20
        self.hashmove = [-1] * 20
Example #37
0
 def __init__(self, filename=None):
     UserDict.__init__(self)
     if filename is not None:
         infile = open(filename, 'r')
         lines = infile.readlines()
         infile.close()
         for i in range(len(lines)):
             (prepart, description) = lines[i].split('!')
             (parname, value) = prepart.split()
             self[parname] = Parameter(value, description.replace('\n', ''))
Example #38
0
	def __init__ (self, textfile=None):
		self.textfile = textfile or self.default_textfile
		UserDict.__init__ (self)

		s = open(self.textfile).read()
		lines = s.split('\n')
		print "%d lines read" % len(lines)
		for path in lines:
			if path.strip():
				self.add (Asset (path))
Example #39
0
 def __init__(self, schedule=None, logger=None, max_interval=None,
         lazy=False, **kwargs):
     UserDict.__init__(self)
     if schedule is None:
         schedule = {}
     self.data = schedule
     self.logger = logger or log.get_default_logger(name="celery.beat")
     self.max_interval = max_interval or conf.CELERYBEAT_MAX_LOOP_INTERVAL
     if not lazy:
         self.setup_schedule()
Example #40
0
    def __init__(self):
        UserDict.__init__(self)
        self._m1 = EWMA.oneMinute()
        self._m5 = EWMA.fiveMinute()
        self._m15 = EWMA.fifteenMinute()
        self._meters = (self._m1, self._m5, self._m15)
        TICKERS.append(self.tick)

        self['unit'] = 'per second'
        self['count'] = 0
Example #41
0
	def __init__ (self):
		UserDict.__init__(self)
		
		"""
		build dict of all NSESDataSet, keyed by NSES id
		"""
		for filename in os.listdir (analysis_data_dir):
			path = os.path.join (analysis_data_dir, filename)
			r = NSESDataSet (path)		
			self[r.nses_standard.id] = r
Example #42
0
 def __init__(self, *list):
     UserDict.__init__(self)
     # Verify if the list's items are the right format
     for table in list:
         if not isinstance(table, Table):
             raise TypeError("Expected a Table instance; got %s" %
                             type(table))
     # Now initialize the collection
     for table in list:
         self.__setitem__(table.name, table)
Example #43
0
    def __init__(self, url, debug=False):
        UserDict.__init__(self)
        self['url'] = url

        self['COOKIEFILE'] = 'freemed-cookies.lwp'

        if debug:
            import logging
            logger = logging.getLogger("cookielib")
            logger.addHandler(logging.StreamHandler(sys.stdout))
            logger.setLevel(logging.DEBUG)

        cj = None
        ClientCookie = None
        cookielib = None

        try:
            import cookielib
        except ImportError:
            pass
        else:
            import urllib2
            urlopen = urllib2.urlopen
            cj = cookielib.LWPCookieJar()
            Request = urllib2.Request

        if not cookielib:
            try:
                import ClientCookie
            except ImportError:
                import urllib2
                urlopen = urllib2.urlopen
                Request = urllib2.Request
            else:
                urlopen = ClientCookie.urlopen
                cj = ClientCookie.LWPCookieJar()
                Request = ClientCookie.Request
        if cj != None:
            if os.path.isfile(self['COOKIEFILE']):
                if debug:
                    print 'DEBUG: Loading cookiefile ' + self['COOKIEFILE']
                cj.load(self['COOKIEFILE'])
            if cookielib:
                opener = urllib2.build_opener(
                    urllib2.HTTPCookieProcessor(cj),
                    MultipartPostHandler.MultipartPostHandler)
                urllib2.install_opener(opener)
            else:
                opener = ClientCookie.build_opener(
                    ClientCookie.HTTPCookieProcessor(cj),
                    MultipartPostHandler.MultipartPostHandler)
                ClientCookie.install_opener(opener)
        self['Request'] = Request
        self['urlopen'] = urlopen
        self['cj'] = cj
 def __init__(self, file_name=None):
     """
     Parameters
     ----------
     file_name : string
         Path to a previously saved cache file
     """
     UserDict.__init__(self)
     self.mutable = True
     if file_name is not None:
         self.load(file_name)
Example #45
0
	def __init__ (self, collKey, db):
		UserDict.__init__(self)
		self.name = db.name
		messages = Messages (db, collKey)
		for msg in messages:
			id = msg['id']
			if not self.has_key (id):
				self[id] = []
			val = self[id]
			val.append (msg)
			self[id] = val
Example #46
0
    def __init__(self, instance):
        UserDict.__init__(self)
        self.instance = instance
        self.collectPath = os.path.join(instance.path, "dlese_collect",
                                        "collect")

        for filename in os.listdir(self.collectPath):
            if not filename.lower().endswith(".xml"): continue
            rec = DleseCollectRecord(
                path=os.path.join(self.collectPath, filename))
            self[rec.getKey()] = rec
Example #47
0
	def __init__ (self, db):
		self.db = db
		rows = db.doSelect (self.query)
		UserDict.__init__ (self)
		# print len(rows), " found"

		for row in rows:
			rec = {}
			for index in range(len(self.schema)):
				rec[self.schema[index]] = row[index]
			self[rec["collKey"]] = rec
Example #48
0
 def __init__(self, line=None, version=3, fields=None):
     UserDict.__init__(self)
     self["__version"] = version
     self["strand"] = '.'
     self["score"] = '.'
     self["source"] = '.'
     self["type"] = '.'
     self["phase"] = '.'
     self["attributes"] = {}
     self["__line"] = line
     if fields: self.update(fields)
    def __init__(self):
        UserDict.__init__(self)

        self.db_conn = None
        self.db_cursor = None

        self["host"] = constants.LOG_DB_SERVER
        self["user"] = constants.LOG_DB_USER
        self["password"] = constants.LOG_DB_PASS
        self["database"] = constants.LOG_DATABASE
        self["port"] = constants.LOG_DB_PORT
Example #50
0
    def __init__(self, builds=None):
        UserDict.__init__(self)
        # builds = "server_version: xxx;project:xxx"
        self['server_version'] = ''
        self['project'] = ''

        if builds is not None:
            lbuilds = builds.split(";")
            for build in lbuilds:
                sName, sNum = build.split(":")
                self[sName] = sNum
Example #51
0
    def __init__(self, model):
        UserDict.__init__(self)

        assert isinstance(model, Model)
        self._model = model
        self._klasses = []
        self._filename = None
        self._name = None
        self._tableHeadings = None

        self.initTypeMap()
Example #52
0
 def __init__(self, basename, textLine):
     UserDict.__init__(self)
     self['files'] = []
     self['name'] = basename
     chunks = textLine.split()
     if chunks[0] != 'Directory':
         raise Exception(
             "A textline given to Directory() doesnt start with Directory: "
             + chunks[0])
     get_key_value_pairs(string.join(chunks[2:]), Directory.allowed_keys,
                         self)
Example #53
0
	def __init__ (self, group, band, sample):
		UserDict.__init__ (self)
		self.group = group
		self.band = band
		self.NSES_stds = sample

		## self.report()

		for nses_std in sample:
			nses_id = makeFullId (nses_std)
			sugg_set = SuggestionSet (nses_id, group, band)
			self[nses_std] = sugg_set
	def __init__ (self):
		UserDict.__init__(self)
		self.errors = []
		self.pubsDB = PubsDB()
		self.esslPeopleDB = EsslPeopleDB()
		self.authorRecs = self._get_authorRecs()
		self.init()
		
		print '%d author recs found' % len(self.authorRecs)
		print '%d unique person_ids found' % len(self)

		self.reportErrors()
Example #55
0
    def __init__(self, filenames):
        '''
        Конструктор

        @param self         Ссылка на экземпляр класса
        @param filenames    Перечень имен файлов конфигурации, попытка найти которые будет сделана при загрузке [iterable]
        '''

        # Загруженная конфигурация будет хранится в self.data
        UserDict.__init__(self)
        # Сохранение параметров
        self._filenames = filenames
Example #56
0
    def __init__(self, data):
        """New Hightlights instance.

        TODO: add fulltext highlights.
        """
        new_data = {}
        for hit in data.get('hits', {}).get('hits', []):
            if hit.get("highlight"):
                new_data[int(hit.get('_id'))] = hit.get("highlight")
            else:
                new_data[int(hit.get('_id'))] = {}
        UserDict.__init__(self, new_data)
Example #57
0
 def __init__( self,
               dict=None,
               populate=None,
               keyTransform=None ):
     """dict: starting dictionary of values
     populate: function that returns the populated dictionary
     keyTransform: function to normalize the keys (e.g., toupper/None)
     """
     UserDict.__init__( self, dict )
     self._populated = 0
     self.__populateFunc = populate or (lambda: {})
     self._keyTransform = keyTransform or (lambda key: key)
Example #58
0
 def __init__(self,
              bundleID,
              bundlePath=None,
              defaultsPlistName='Defaults'):
     ''' bundleId: the application bundle identifier
         bundlePath: the full bundle path (useful to test a Debug build)
         defaultsPlistName: the name of the plist that contains default values
     '''
     self.__bundleID = bundleID
     self.__bundlePath = bundlePath
     UserDict.__init__(self)
     self.__setup(defaultsPlistName)
Example #59
0
    def __init__(self, dict=None):
        """
        Default class constructor.

        
        **Parameters:**

        * dict: a dictionary from where to get the new dict keys (optional).
        """

        self._keys = []
        UserDict.__init__(self, dict)
Example #60
0
    def __init__(self, filename=None, data=None):
        UserDict.__init__(self)

        if data is None:
            self.data = {}
            self.uwyofile(filename)
        else:
            self.data = data
            if not data.has_key("SoundingDate"):
                self["SoundingDate"] = "(no date)"
            if not data.has_key("StationNumber"):
                self["StationNumber"] = "(no number)"