예제 #1
0
def isreadonly(obj, aname, attr): #{{{
    ret = False
    try:
        _ab.setattr(obj, aname, attr)
    except:
        ret = True
    return ret
예제 #2
0
파일: item.py 프로젝트: Johan-Paz/pyif-test
 def __init__(self,name=None,gender=None,location=None,limits=None,others=None):
     '''
     Constructor
     '''
     if name:
         if not isinstance(name, str) and not isinstance(name, unicode):
             raise NotProperParamForItem('Name is not a string.')
         self.name = name
     else:
         self.name = self.__class__.__name__
     if gender:
         if not isinstance(gender,Gender):
             raise NotProperParamForItem('Gender is not a proper one.')
         self.gender = gender
     else:
         self.gender = SingularMale
     if location:
         self.location = location
     else:
         self.location = None
         
     if limits:
         for a, b in limits.items():
             setattr(self,'verify_' + a,b)  
                       
     if others:
         for a, b in others.items():
             setattr(self,a,b)
예제 #3
0
    def __init__(self,
                 name=None,
                 gender=None,
                 location=None,
                 limits=None,
                 others=None):
        '''
        Constructor
        '''
        if name:
            if not isinstance(name, str) and not isinstance(name, unicode):
                raise NotProperParamForItem('Name is not a string.')
            self.name = name
        else:
            self.name = self.__class__.__name__
        if gender:
            if not isinstance(gender, Gender):
                raise NotProperParamForItem('Gender is not a proper one.')
            self.gender = gender
        else:
            self.gender = SingularMale
        if location:
            self.location = location
        else:
            self.location = None

        if limits:
            for a, b in limits.items():
                setattr(self, 'verify_' + a, b)

        if others:
            for a, b in others.items():
                setattr(self, a, b)
예제 #4
0
파일: models.py 프로젝트: cretta/trove
    def promote_to_replica_source(self):
        self.validate_can_perform_action()
        LOG.info(_LI("Promoting instance %s to replication source."), self.id)
        if not self.slave_of_id:
            raise exception.BadRequest(_("Instance %s is not a replica.")
                                       % self.id)

        # Update task status of master and all slaves
        master = BuiltInstance.load(self.context, self.slave_of_id)
        for dbinfo in [master.db_info] + master.slaves:
            setattr(dbinfo, 'task_status', InstanceTasks.PROMOTING)
            dbinfo.save()

        task_api.API(self.context).promote_to_replica_source(self.id)
예제 #5
0
 def setattr(cls, obj, name, val):
     """ Overrides the builtin `setattr` function within LimitedExec
         scripts.  This version checks that the given attribute is
         permissible.
     """
     if name.startswith(config.names.LTDEXEC_PRIVATE_PREFIX):
         m = 'Cannot access attribute "{0}".'.format(name)
         raise exceptions.LXPrivateAttrError(m)
     elif name in cls.forbidden_attrs_set:
         m = 'Cannot access attribute "{0}".'.format(name)
         raise exceptions.ForbiddenAttrError(m)
     elif name in cls.unassignable_attrs_set:
         m = 'Cannot assign to attribute "{0}".'.format(name)
         raise exceptions.UnassignableAttrError(m)
     __builtin__.setattr(obj, name, val)
예제 #6
0
 def set_client(self, settings):
     for key in settings.iterkeys():
         setattr(self, key, settings.get(key))
     base64string = base64.encodestring(
         '%s:%s' % (self.username, self.password)).replace('\n', '')
     authenticationHeader = {
         "SOAPAction": "ActionName",
         "Authorization": "Basic %s" % base64string
     }
     t = HttpAuthenticated(username=self.username, password=self.password)
     self._client = Client(self.url,
                           headers=authenticationHeader,
                           transport=t,
                           cache=NoCache(),
                           timeout=500)
예제 #7
0
    def __setattr__(self, name, value):
        # #
        """
            Is triggered if a property was tried to overwrite but is \
            inaccessible.

            **name**  - is the inaccessible property name.

            **value** - is the new value for the given property name.

            Returns the new value of the given property name depending on the \
            presence of setter method otherwise "None" is returned.

            Examples:

            >>> class TestA(Class):
            ...     _a = 'hans'
            ...     def set_a(self, value):
            ...         self._a = 'Not only ' + value + '. Also hans.'
            >>> test_a = TestA()
            >>> test_a.a = 'peter'
            >>> test_a._a
            'Not only peter. Also hans.'
            >>> class TestB(Class):
            ...     _a = ''
            ...     _b = ''
            ...     def __init__(self):
            ...         self._a = 'hans'
            ...         self._b = 'also hans'
            ...     def set(self, name, value):
            ...         if name in ('_a', '_b'):
            ...             self.__dict__[name] = 'hans and ' + value
            >>> test_b = TestB()
            >>> test_b.a = 'peter'
            >>> test_b._a
            'hans and peter'
        """
        if not self._set_attribute_helper(name, value):
            if name in self.__class__.__dict__:
                builtins.setattr(self.__class__, name, value)
            else:
                self.__dict__[name] = value
        return value
예제 #8
0
파일: models.py 프로젝트: cretta/trove
    def eject_replica_source(self):
        self.validate_can_perform_action()
        LOG.info(_LI("Ejecting replica source %s from it's replication set."),
                 self.id)

        if not self.slaves:
            raise exception.BadRequest(_("Instance %s is not a replica"
                                       " source.") % self.id)
        service = InstanceServiceStatus.find_by(instance_id=self.id)
        last_heartbeat_delta = datetime.utcnow() - service.updated_at
        agent_expiry_interval = timedelta(seconds=CONF.agent_heartbeat_expiry)
        if last_heartbeat_delta < agent_expiry_interval:
            raise exception.BadRequest(_("Replica Source %s cannot be ejected"
                                         " as it has a current heartbeat")
                                       % self.id)

        # Update task status of master and all slaves
        for dbinfo in [self.db_info] + self.slaves:
            setattr(dbinfo, 'task_status', InstanceTasks.EJECTING)
            dbinfo.save()

        task_api.API(self.context).eject_replica_source(self.id)
예제 #9
0
    def _set_properties(
        cls, level, buffer, terminator, colored_format, format
    ):
# #
        '''
            This method sets the class properties.

            Examples:

            >>> Logger._set_properties(
            ...     level=Logger.level, buffer=Logger.buffer,
            ...     terminator=Logger.terminator,
            ...     colored_format=Logger.colored_format, format=Logger.format
            ... ) # doctest: +ELLIPSIS
            <class '...Logger'>
        '''
        # TODO check branches.
        scope = builtins.locals()
        for name in builtins.filter(lambda name: scope[name], (
            'level', 'buffer', 'terminator', 'colored_format', 'format'
        )):
            builtins.setattr(cls, name, scope[name])
        return cls
예제 #10
0
파일: models.py 프로젝트: cretta/trove
        def _create_resources():

            if cluster_config:
                cluster_id = cluster_config.get("id", None)
                shard_id = cluster_config.get("shard_id", None)
                instance_type = cluster_config.get("instance_type", None)
            else:
                cluster_id = shard_id = instance_type = None

            ids = []
            names = []
            root_passwords = []
            root_password = None
            for instance_index in range(0, instance_count):
                db_info = DBInstance.create(
                    name=name, flavor_id=flavor_id, tenant_id=context.tenant,
                    volume_size=volume_size,
                    datastore_version_id=datastore_version.id,
                    task_status=InstanceTasks.BUILDING,
                    configuration_id=configuration_id,
                    slave_of_id=slave_of_id, cluster_id=cluster_id,
                    shard_id=shard_id, type=instance_type)
                LOG.debug("Tenant %(tenant)s created new Trove instance "
                          "%(db)s.",
                          {'tenant': context.tenant, 'db': db_info.id})

                instance_id = db_info.id
                instance_name = name
                ids.append(instance_id)
                names.append(instance_name)
                root_passwords.append(None)
                # change the name to be name + replica_number if more than one
                if multi_replica:
                    replica_number = instance_index + 1
                    names[instance_index] += '-' + str(replica_number)
                    setattr(db_info, 'name', names[instance_index])
                    db_info.save()

                # if a configuration group is associated with an instance,
                # generate an overrides dict to pass into the instance creation
                # method

                config = Configuration(context, configuration_id)
                overrides = config.get_configuration_overrides()
                service_status = InstanceServiceStatus.create(
                    instance_id=instance_id,
                    status=tr_instance.ServiceStatuses.NEW)

                if CONF.trove_dns_support:
                    dns_client = create_dns_client(context)
                    hostname = dns_client.determine_hostname(instance_id)
                    db_info.hostname = hostname
                    db_info.save()

                if cls.get_root_on_create(
                        datastore_version.manager) and not backup_id:
                    root_password = utils.generate_random_password()
                    root_passwords[instance_index] = root_password

            if instance_count > 1:
                instance_id = ids
                instance_name = names
                root_password = root_passwords
            task_api.API(context).create_instance(
                instance_id, instance_name, flavor, image_id, databases, users,
                datastore_version.manager, datastore_version.packages,
                volume_size, backup_id, availability_zone, root_password,
                nics, overrides, slave_of_id, cluster_config)

            return SimpleInstance(context, db_info, service_status,
                                  root_password)
예제 #11
0
파일: models.py 프로젝트: cretta/trove
 def update_db(self, **values):
     self.db_info = DBInstance.find_by(id=self.id, deleted=False)
     for key in values:
         setattr(self.db_info, key, values[key])
     self.db_info.save()
예제 #12
0
def _uno_struct__setattr__(self,name,value):
    return __builtin__.setattr(self.__dict__["value"],name,value)
예제 #13
0
def setattr(attr, value, obj):
  __builtin__.setattr(obj, attr, value)
  return obj
예제 #14
0
def setattr(object, name, value):
    return __builtin__.setattr(object, name, value)
예제 #15
0
파일: views.py 프로젝트: pranjalt/SchoolErp
def addStudentDetails(request):
    
    media_root = 'D://studentImages/student'
    logger.debug("start of addStudentDetails method :")
    print "in student add form"
    if request.POST:
       
        action_type= request.POST['action_type']
        PermAddrForm=studentPermanantAddressForm(request.POST)
        tempAddrForm=studentTempAddressForm(request.POST)
        pIntituteAddrForm=PInstituAddressForm(request.POST)
        pIntituteAddrForm.errors
        PermAddrForm.errors
        tempAddrForm.errors
        
        addr_fields = ['flatNo', 'street1', 'street2','city','pincode', 'state' ]
        
        if action_type == "add":
            form=studentForm(request.POST,request.FILES)
            print "in student add form form :",form
            parForm=parentForm(request.POST)
            
            pInstituteForm=previousIntituteDetailsForm(request.POST)
            
        else:
            student_id = request.POST['student_id']
            parent_id = request.POST['parent_id']
            
            student = Student.objects.get(student_id=student_id)
            parent = Parent.objects.get(parent_id=parent_id)
        
            form=studentForm(request.POST,request.FILES,instance=student)
            parForm=parentForm(request.POST, instance=parent)
            
            prev_institute_id =request.POST['previous_institute_id']
            if prev_institute_id is None  :
                pInstituteForm = previousIntituteDetailsForm(request.POST)
            else:   
                prev_institute_obj = PreviousInstituteDetails.objects.get(previous_institute_id=prev_institute_id)
                pInstituteForm = previousIntituteDetailsForm(request.POST,instance=prev_institute_obj)
           
        print "student form error :",form.errors
        print "Is student valid :",form.is_valid()
        print "Parent Form Error :",parForm.is_valid()
        print "Is Parent Form Valid :",parForm.errors
        print "Previous Institute Form error :",pInstituteForm.errors
        print "previous institute form valid :",pInstituteForm.is_valid()
        
        if form.is_valid() and parForm.is_valid() and pInstituteForm.is_valid():
             
            print "in if condition validate form and parent form"
            pInstitute = pInstituteForm.save()            
            student=form.save(commit=False)
            student.previous_institute = pInstitute
            student.save()
            
            if action_type == "add":
                student_id = student.student_id
                name = request.FILES['student_image_file'].name
                ext = name.split('.')[-1]
                print "ext ::::::: ",ext
                file_path = media_root + os.sep + "student_image_%s" % student_id + '.' + ext
                handle_uploaded_file(request.FILES['student_image_file'], file_path)
                print file_path
                student.student_pic = 'static/student/' + "student_image_%s.%s" % (student_id, ext)
                student.save()
            
            parent=parForm.save()            
            
            if action_type == "add":
                studParent= ParentStudent.objects.create(parent=parent,student=student)
                studParent.save()
            
            if PermAddrForm.is_valid() and tempAddrForm.is_valid() and pIntituteAddrForm.is_valid():
                print "in if condition validte form and address form"
                if action_type == "add":
                    model_dict = {}
                    for field in addr_fields:
                        model_dict[field] = PermAddrForm.cleaned_data[field]
                    p_address = StudentAddress(**model_dict)
                    p_address.type= 'permenant'
                    p_address.student = student
                    p_address.save() 
    
                    for field in addr_fields:
                        model_dict[field] = tempAddrForm.cleaned_data['temp'+field]
                    t_address = StudentAddress(**model_dict)
                    t_address.type= 'temporary'
                    t_address.student = student
                    t_address.save()
                    
                    for field in addr_fields:
                        print "in addr_fields if condition :"
                        model_dict[field] = pIntituteAddrForm.cleaned_data['pInstitute'+field]
                    prev_institute_addr = StudentAddress(**model_dict)
                    prev_institute_addr.type= 'PreviousInstituteAddr'
                    prev_institute_addr.student = student
                    prev_institute_addr.save()
                        
                else:
                    p_address = StudentAddress.objects.get(student=student, type="permenant")
                    t_address = StudentAddress.objects.get(student=student, type="temporary")
                   
                    prev_institute_addr = StudentAddress.objects.get(student=student, type="PreviousInstituteAddr")
                    print " in else cndtn edit 2222222",prev_institute_addr
                        
                    #if prev institute is not given,and entered at on edit then it fails to add all 3 address    
                    for field in addr_fields:
                        setattr(p_address, field, PermAddrForm.cleaned_data[field])
                        setattr(t_address, field, tempAddrForm.cleaned_data['temp' + field])
                        setattr(prev_institute_addr,field, pIntituteAddrForm.cleaned_data['pInstitute' + field])
                        
                    p_address.save()
                    t_address.save() 
                    prev_institute_addr.save()            
        else:
            print "form errors :"
            print form.errors
            print parForm.errors
            print pInstituteForm.errors
    Studform=studentForm()
    studentTable= StudentTable()
    parForm=parentForm()
    template= get_template('student/studentList.html')
    PermAddrForm=studentPermanantAddressForm()
    tempAddrForm=studentTempAddressForm()
    pIntituteDetailsForm=previousIntituteDetailsForm()
    pInstituteAddrFrom=PInstituAddressForm()
    
    variables = Context({
                        'student':studentTable,
                        'form':Studform,
                        'parForm':parForm,
                        'PermAddrForm':PermAddrForm,
                        'tempAddrForm':tempAddrForm,
                        'pIntituteDetailsForm':pIntituteDetailsForm,
                        'pInstituteAddrFrom':pInstituteAddrFrom
                         })   
    output = template.render(variables)
    #return HttpResponse(output)
    return redirect('/school/?default_load_tab=Students')
예제 #16
0
 def set_for_all_items(self, prop_name, prop_value):
     for item in self:
         if hasattr(item, prop_name):
             setattr(item, prop_name, prop_value)
             if hasattr(item, 'init_vertex_lists'):
                 item.init_vertex_lists()
예제 #17
0
파일: fn.py 프로젝트: dilgerma/shipwright
def setattr(attr, value, obj):
    __builtin__.setattr(obj, attr, value)
    return obj
예제 #18
0
def _uno_struct__setattr__(self, name, value):
    return __builtin__.setattr(self.__dict__["value"], name, value)