Dynamically scope an audit class
180646
public function loadClass($auditClassName, $type)
    {
        $foundClassName = false;
        foreach ($this->getJoinEntityConfigCollection() as $className => $config) {
            if ($this->getAuditObjectManager()
                ->getRepository(Entity\AuditEntity::class)
                ->generateClassName($className) == $auditClassName
            ) {
                $foundClassName = true;
                break;
            }
        }

        if (! $foundClassName) {
            return false;
        }

        $metadata = $this->getObjectManager()->getClassMetadata($config['ownerEntity']);

        foreach ($metadata->getAssociationMappings() as $mapping) {
            if (isset($mapping['joinTable'])) {
                if ($mapping['joinTable']['name'] == $config['tableName']) {
                    $foundJoinEntity = true;
                    break;
                }
            }
        }

        if (! $foundJoinEntity) {
            return false;
        }

        $auditClass = new ClassGenerator();
        $auditClass->setNamespaceName("ZF\\Doctrine\\Audit\\AuditEntity");
        $auditClass->setName($auditClassName);
        $auditClass->setExtendedClass('ZF\Doctrine\Audit\AuditEntity\AbstractAudit');

        // Add revision reference getter and setter
        $auditClass->addProperty('revisionEntity', null, PropertyGenerator::FLAG_PROTECTED);
        $auditClass->addMethod(
            'getRevisionEntity',
            [],
            MethodGenerator::FLAG_PUBLIC,
            " return \$this->revisionEntity;"
        );

        $auditClass->addMethod(
            'setRevisionEntity',
            ['value'],
            MethodGenerator::FLAG_PUBLIC,
            " \$this->revisionEntity = \$value;\n\nreturn \$this;
            "
        );

        $fields = [];
        foreach ($mapping['joinTable']['joinColumns'] as $column) {
            $column['dataType'] = $this->getObjectManager()
                ->getClassMetadata($mapping['sourceEntity'])
                ->getTypeOfField($column['referencedColumnName']);
            $fields[] = $column;
        }
        foreach ($mapping['joinTable']['inverseJoinColumns'] as $column) {
            $column['dataType'] = $this->getObjectManager()
                ->getClassMetadata($mapping['targetEntity'])
                ->getTypeOfField($column['referencedColumnName']);
            $fields[] = $column;
        }

        // Generate audit entity
        foreach ($fields as $field) {
            $auditClass->addProperty($field['name'], null, PropertyGenerator::FLAG_PROTECTED);
        }

        $auditClass->addMethod(
            'getAssociationMappings',
            [],
            MethodGenerator::FLAG_PUBLIC,
            "return unserialize('" . serialize($mapping) . "');"
        );

        // Add exchange array method
        $setters = [];
        foreach ($fields as $field) {
            $setters[] = '$this->' . $field['name']
                . ' = (isset($data["' . $field['name'] . '"])) ? $data["' . $field['name'] . '"]: null;';
            $arrayCopy[] = "    \"" . $field['name'] . "\"" . ' => $this->' . $field['name'];
        }

        $auditClass->addMethod(
            'getArrayCopy',
            [],
            MethodGenerator::FLAG_PUBLIC,
            "return array(\n" . implode(",\n", $arrayCopy) . "\n);"
        );

        $auditClass->addMethod(
            'exchangeArray',
            ['data'],
            MethodGenerator::FLAG_PUBLIC,
            implode("\n", $setters)
        );

        // Add function to return the entity class this entity audits
        $auditClass->addMethod(
            'getAuditedEntityClass',
            [],
            MethodGenerator::FLAG_PUBLIC,
            " return '" . addslashes($auditClassName) . "';"
        );

        // echo "Created " . $auditClass->getName() . "\n" . $auditClass->getNamespaceName() . "\n";

        eval($auditClass->generate());

        return true;
    }
529178
def scopes(cls):
        
        # Why do we need this? This should either
        # * Be bubbled to the places where it is used (AcidXBlock).
        # * Be automatic. Look for all members of a type.
        return [cls.USAGE, cls.DEFINITION, cls.TYPE, cls.ALL]
790419
def should_audit(instance):
    """"""

    # do not audit any model listed in UNREGISTERED_CLASSES
    for unregistered_class in UNREGISTERED_CLASSES:
        if isinstance(instance, unregistered_class):
            return False

    # only audit models listed in REGISTERED_CLASSES (if it's set)
    if len(REGISTERED_CLASSES) > 0:
        for registered_class in REGISTERED_CLASSES:
            if isinstance(instance, registered_class):
                break
        else:
            return False

    # all good
    return True
433843
@Override
    public void execute() {
        Set<String> annotated = db.getAnnotationIndex().get(Audit.class.getName());
        ScanAnnotatedFilter filter = new ScanAnnotatedFilter();
        for (String annotaionClass : annotated) {
            try {
                Class<?> clazz = Class.forName(annotaionClass);
                filter.addClass(clazz);
            } catch (ClassNotFoundException e) {
                throw new InitializationException("", e);
            }
        }
        PreConfigurationContext.addAnnotationFilter(filter);
    }
250813
def _get_scope_with_mangled(self, name):
        """"""
        scope = self
        while True:
            parent = scope.get_enclosing_scope()
            if parent is None:
                return

            if name in parent.rev_mangled:
                return parent

            scope = parent
992206
def scope
      if tree.columns.scope?
        tree.base_class.where Hash[tree.columns.scope.map { |column| [column, record[column]] }]
      else
        tree.base_class.where(nil)
      end
    end
22128
private void loadAuditAllowed() {
		if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
			SibTr.entry(tc, "loadAuditAllowed", this);
		//
		// ConfigObject sibAudit = null;
		// try {
		// // Get config service
		// ConfigService service = (ConfigService)
		// WsServiceRegistry.getService(this, ConfigService.class);
		//
		// // Create server scope
		// ConfigScope scope = service.createScope(ConfigScope.BUS);
		// scope.set(ConfigScope.BUS, _name);
		//
		// // Get iterator over contents of audit document, could by from
		// dynamic config so don't use cache
		// List auditList = service.getDocumentObjects(scope,
		// JsConstants.WCCM_DOC_SECURITY_AUDIT, false);
		// if (auditList != null && !auditList.isEmpty()) {
		// // There will only be one entry
		// sibAudit = (ConfigObject) auditList.get(0);
		// }
		// } catch (FileNotFoundException e) {
		// // No FFDC code needed
		// // Document doesn't exist yet
		// sibAudit = null;
		// } catch (Exception e) {
		// com.ibm.ws.ffdc.FFDCFilter.processException(e, CLASS_NAME +
		// ".<init>", "5", this);
		// SibTr.debug(tc, "CONFIG_LOAD_FAILED_SIAS0008", "buses\\" + _name +
		// "\\" + JsConstants.WCCM_DOC_SECURITY_AUDIT);
		// sibAudit = null;
		// }
		//
		// // Read the configuration for the specified bus, and get bus
		// auditAllowed
		// if (sibAudit != null) {
		// // Bus auditAllowed value
		// _busAuditAllowed = sibAudit.getBoolean(CT_SIBAudit.ALLOWAUDIT_NAME,
		// CT_SIBAudit.ALLOWAUDIT_DEFAULT);
		// } else {
		// // Default to true
		// _busAuditAllowed = true;
		// }

		if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
			SibTr.exit(tc, "loadAuditAllowed");
	}
1230471
@Override
    public void before(final Method method, final Object[] params, final Object arg2) throws Throwable {
        AuditManager.getInstance().audit(method.getClass(), method, params);
    }
260722
def render(self,scope=None,local_vars=None,block=None):
		''' 
		'''

		if not scope:
			class Scope(object):
				pass

			scope = Scope()

		return self.evaluate(scope,local_vars or {}, block)
944766
private void executeInClassScope(Callable<Void> call) {
        try {
            classContext.get().activate(deploymentClass);
            call.call();
        } catch (Exception e) {
            throw new RuntimeException("Could not invoke operation", e); // NOPMD
        } finally {
            classContext.get().deactivate();
        }
    }
1315088
function observe($scope, $attrs, key, defValue, callbackFunc) {
        if (callbackFunc === void 0) { callbackFunc = null; }
        $attrs.$observe(key, function (value) {
            if (!angular.isDefined(value)) {
                $scope[key] = defValue;
            }
            else {
                $scope[key] = value;
            }
            if (angular.isDefined(callbackFunc) && callbackFunc) {
                callbackFunc($scope[key]);
            }
        });
    }
628995
def singleton_per_scope(_cls, _scope=None, _renew=False, *args, **kwargs):
    """"""

    result = None

    singletons = SINGLETONS_PER_SCOPES.setdefault(_scope, {})

    if _renew or _cls not in singletons:
        singletons[_cls] = _cls(*args, **kwargs)

    result = singletons[_cls]

    return result
963966
def scoped_session_decorator(func):
    """"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        from wallace.db import session as wallace_session
        with sessions_scope(wallace_session) as session:
            from psiturk.db import db_session as psi_session
            with sessions_scope(psi_session) as session_psiturk:
                # The sessions used in func come from the funcs globals, but
                # they will be proxied thread locals vars from the session
                # registry, and will therefore be identical to those returned
                # by the context managers above.
                logger.debug('Running worker %s in scoped DB sessions',
                             func.__name__)
                return func(*args, **kwargs)
    return wrapper
1254094
private Object evalAssignExpressionAndGetFileName(Scope scope) {
		Ctrl ctrl = scope.getCtrl();
		try {
			ctrl.setLocalAssignment();
			return exprList.evalExprList(scope)[0];
		} finally {
			ctrl.setWisdomAssignment();
		}
	}
16024
def build_scope(resource, method):
        
        if ResourceList in inspect.getmro(resource) and method == 'GET':
            prefix = 'list'
        else:
            method_to_prefix = {'GET': 'get',
                                'POST': 'create',
                                'PATCH': 'update',
                                'DELETE': 'delete'}
            prefix = method_to_prefix[method]

            if ResourceRelationship in inspect.getmro(resource):
                prefix = '_'.join([prefix, 'relationship'])

        return '_'.join([prefix, resource.schema.opts.type_])
52919
public void audit(String key, Object... params) {
        Tr.audit(tc, key, params);
    }
952204
public static void audit(TraceComponent tc, String msgKey, Object objs) {
     SibTr.audit(tc, msgKey, objs);
  }