text:
using namespace IECoreMaya;

SceneShapeInterfaceComponentBoundIterator::SceneShapeInterfaceComponentBoundIterator( void *userGeometry, MObjectArray &components )
	: 	MPxGeometryIterator( userGeometry, components ),
		m_sceneShapeInterface( (SceneShapeInterface*) userGeometry ),
		m_idx( 0 ),
		m_components( components )
{
	computeNumComponents();
}

SceneShapeInterfaceComponentBoundIterator::SceneShapeInterfaceComponentBoundIterator( void *userGeometry, MObject &components )
	: 	MPxGeometryIterator( userGeometry, components ),
		m_sceneShapeInterface( (SceneShapeInterface*) userGeometry ),
		m_idx( 0 )
{
	m_components.append( components );
	computeNumComponents();
}

void SceneShapeInterfaceComponentBoundIterator::computeNumComponents()
{
	MStatus s;
	m_numComponents = 0;
	for( unsigned j=0; j < m_components.length(); ++j )
	{
		MFnSingleIndexedComponent fnCmp( m_components[j], &s );
		if( s )
		{
			m_numComponents += fnCmp.elementCount();
		}
	}
}

SceneShapeInterfaceComponentBoundIterator::~SceneShapeInterfaceComponentBoundIterator()
{
}

void SceneShapeInterfaceComponentBoundIterator::reset()
{
	m_idx = 0;
}

MPoint SceneShapeInterfaceComponentBoundIterator::point() const
{
	MPoint ret;

	Imath::Box3d bbox = m_sceneShapeInterface->componentBound( index() );

	switch( m_idx % 8 )
	{
		case 0: ret = MPoint( bbox.min[0], bbox.min[1], bbox.min[2] ); break;
		case 1: ret = MPoint( bbox.max[0], bbox.min[1], bbox.min[2] ); break;
		case 2: ret = MPoint( bbox.min[0], bbox.max[1], bbox.min[2] ); break;
		case 3: ret = MPoint( bbox.max[0], bbox.max[1], bbox.min[2] ); break;
		case 4: ret = MPoint( bbox.min[0], bbox.min[1], bbox.max[2] ); break;
		case 5: ret = MPoint( bbox.max[0], bbox.min[1], bbox.max[2] ); break;
		case 6: ret = MPoint( bbox.min[0], bbox.max[1], bbox.max[2] ); break;
		case 7: ret = MPoint( bbox.max[0], bbox.max[1], bbox.max[2] ); break;
		default: break;
	}

	return ret;
}

void SceneShapeInterfaceComponentBoundIterator::setPoint( const MPoint & ) const
{
}

int SceneShapeInterfaceComponentBoundIterator::iteratorCount() const
{
	// one for each bounding box corner
	return m_numComponents * 8;
}

bool SceneShapeInterfaceComponentBoundIterator::hasPoints() const
{
	return true;
}

bool SceneShapeInterfaceComponentBoundIterator::isDone() const
{
	return m_idx >= m_numComponents * 8;
}

void SceneShapeInterfaceComponentBoundIterator::next()
{
	++m_idx;
}

void SceneShapeInterfaceComponentBoundIterator::component( MObject &component )
{
	component = MObject::kNullObj;
}

int SceneShapeInterfaceComponentBoundIterator::setPointGetNext(MPoint &p)
{
	return m_idx + 1;
}

int SceneShapeInterfaceComponentBoundIterator::index() const
{
	MStatus s;
	unsigned componentNum = 0;
	unsigned targetComponentNum = m_idx / 8;
	for( unsigned j=0; j < m_components.length(); ++j )
	{
		MFnSingleIndexedComponent fnCmp( m_components[j], &s );
		if( s )
		{
			if( componentNum + fnCmp.elementCount() > targetComponentNum )
			{
				return fnCmp.element( targetComponentNum - componentNum );
			}
			componentNum += fnCmp.elementCount();
		}
	}
	return 0;
}

bool SceneShapeInterfaceComponentBoundIterator::hasNormals() const
{
	return false;
}

int SceneShapeInterfaceComponentBoundIterator::indexUnsimplified() const
{
	return m_idx;
}


text:
<?php

/**
 * CExistValidator validates that the attribute value exists in a table.
 *
 * This validator is often used to verify that a foreign key contains a value
 * that can be found in the foreign table.
 *
 * When using the {@link message} property to define a custom error message, the message
 * may contain additional placeholders that will be replaced with the actual content. In addition
 * to the "{attribute}" placeholder, recognized by all validators (see {@link CValidator}),
 * CExistValidator allows for the following placeholders to be specified:
 *

 *
{value}: replaced with value of the attribute.

 *

 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @package system.validators
 */
class CExistValidator extends CValidator
{
	/**
	 * @var boolean whether the comparison is case sensitive. Defaults to true.
	 * Note, by setting it to false, you are assuming the attribute type is string.
	 */
	public $caseSensitive=true;
	/**
	 * @var string the ActiveRecord class name that should be used to
	 * look for the attribute value being validated. Defaults to null,
	 * meaning using the ActiveRecord class of the attribute being validated.
	 * You may use path alias to reference a class name here.
	 * @see attributeName
	 */
	public $className;
	/**
	 * @var string the ActiveRecord class attribute name that should be
	 * used to look for the attribute value being validated. Defaults to null,
	 * meaning using the name of the attribute being validated.
	 * @see className
	 */
	public $attributeName;
	/**
	 * @var mixed additional query criteria. Either an array or CDbCriteria.
	 * This will be combined with the condition that checks if the attribute
	 * value exists in the corresponding table column.
	 * This array will be used to instantiate a {@link CDbCriteria} object.
	 */
	public $criteria=array();
	/**
	 * @var boolean whether the attribute value can be null or empty. Defaults to true,
	 * meaning that if the attribute is empty, it is considered valid.
	 */
	public $allowEmpty=true;

	/**
	 * Validates the attribute of the object.
	 * If there is any error, the error message is added to the object.
	 * @param CModel $object the object being validated
	 * @param string $attribute the attribute being validated
	 * @throws CException if given table does not have specified column name
	 */
	protected function validateAttribute($object,$attribute)
	{
		$value=$object->$attribute;
		if($this->allowEmpty && $this->isEmpty($value))
			return;

		if(is_array($value))
		{
			// https://github.com/yiisoft/yii/issues/1955
			$this->addError($object,$attribute,Yii::t('yii','{attribute} is invalid.'));
			return;
		}

		$className=$this->className===null?get_class($object):Yii::import($this->className);
		$attributeName=$this->attributeName===null?$attribute:$this->attributeName;
		$finder=$this->getModel($className);
		$table=$finder->getTableSchema();
		if(($column=$table->getColumn($attributeName))===null)
			throw new CException(Yii::t('yii','Table "{table}" does not have a column named "{column}".',
				array('{column}'=>$attributeName,'{table}'=>$table->name)));

		$columnName=$column->rawName;
		$criteria=new CDbCriteria();
		if($this->criteria!==array())
			$criteria->mergeWith($this->criteria);
		$tableAlias = empty($criteria->alias) ? $finder->getTableAlias(true) : $criteria->alias;
		$valueParamName = CDbCriteria::PARAM_PREFIX.CDbCriteria::$paramCount++;
		$criteria->addCondition($this->caseSensitive ? "{$tableAlias}.{$columnName}={$valueParamName}" : "LOWER({$tableAlias}.{$columnName})=LOWER({$valueParamName})");
		$criteria->params[$valueParamName] = $value;

		if(!$finder->exists($criteria))
		{
			$message=$this->message!==null?$this->message:Yii::t('yii','{attribute} "{value}" is invalid.');
			$this->addError($object,$attribute,$message,array('{value}'=>$value));
		}
	}

	/**
	 * Given active record class name returns new model instance.
	 *
	 * @param string $className active record class name.
	 * @return CActiveRecord active record model instance.
	 *
	 * @since 1.1.14
	 */
	protected function getModel($className)
	{
		return CActiveRecord::model($className);
	}
}

redpajama_set_name: RedPajamaGithub


text:
layout: post
title:  "openSAP"
img: opensap.png
modalID: modalopenSAP
link: https://open.sap.com
runtime: "2013 - ongoing"
---
openSAP is the MOOC platform where SAP provides free courses. As a part of the research team on knowledge and learning engineering we are responsible for development and research in the field of enterprise MOOCs. I mainly work in the field of learning analytics, UI/UX and Offline Support.


text:
<?php

	Class RoleManager {

		public static $_pool = array();

		/**
		 * Given an associative array of data with the keys being the
		 * relevant table names, and the values being an associative array
		 * of data to insert, add a new Role to the Database. Roles are spread
		 * across three tables, `tbl_members_roles`, `tbl_members_roles_forbidden_pages`
		 * and `tbl_members_roles_event_permissions`. This function will return
		 * the ID of the Role after it has been added to the database.
		 *
		 * @param array $data
		 * @return integer
		 *  The newly created Role's ID
		 */
		public static function add(array $data) {
			Symphony::Database()->insert($data['roles'], 'tbl_members_roles');
			$role_id = Symphony::Database()->getInsertID();

			$page_access = $data['roles_forbidden_pages']['page_access'];
			if(is_array($page_access) && !empty($page_access)) {
				foreach($page_access as $page_id){
					Symphony::Database()->insert(array(
							'page_id' => $page_id,
							'role_id' => $role_id
						),
						'tbl_members_roles_forbidden_pages'
					);
				}
			}

			$permissions = $data['roles_event_permissions']['permissions'];
			if(is_array($permissions) && !empty($permissions)){
				$sql = "INSERT INTO `tbl_members_roles_event_permissions` VALUES ";

				foreach($permissions as $event_handle => $p){
					foreach($p as $action => $level) {
						$sql .= sprintf("(NULL,%d,'%s','%s',%d),", $role_id, $event_handle, $action, $level);
					}
				}

				Symphony::Database()->query(trim($sql, ','));
			}

			return $role_id;
		}

		/**
		 * Given a `$role_id` and an associative array of data in the same fashion
		 * as `RoleManager::add()`, this will update a Role record returning boolean
		 *
		 * @param integer $role_id
		 * @param array $data
		 * @return boolean
		 */
		public static function edit($role_id, array $data) {
			if(is_null($role_id)) return false;

			Symphony::Database()->update($data['roles'], 'tbl_members_roles', "`id` = " . $role_id);

			Symphony::Database()->delete("`tbl_members_roles_forbidden_pages`", "`role_id` = " . $role_id);
			$page_access = $data['roles_forbidden_pages']['page_access'];
			if(is_array($page_access) && !empty($page_access)) {
				foreach($page_access as $page_id){
					Symphony::Database()->insert(array(
							'page_id' => $page_id,
							'role_id' => $role_id
						),
						'tbl_members_roles_forbidden_pages'
					);
				}
			}

			Symphony::Database()->delete("`tbl_members_roles_event_permissions`", "`role_id` = " . $role_id);
			$permissions = $data['roles_event_permissions']['permissions'];
			if(is_array($permissions) && !empty($permissions)){
				$sql = "INSERT INTO `tbl_members_roles_event_permissions` VALUES ";

				foreach($permissions as $event_handle => $p){
					if(!array_key_exists('create', $p)) {
						$sql .= sprintf("(NULL,%d,'%s','%s',%d),", $role_id, $event_handle, 'create', EventPermissions::NO_PERMISSIONS);
					}

					foreach($p as $action => $level) {
						$sql .= sprintf("(NULL,%d,'%s','%s',%d),", $role_id, $event_handle, $action, $level);
					}
				}

				$p = Symphony::Database()->query(trim($sql, ','));
			}

			return true;
		}

		/**
		 * Will delete the Role given a `$role_id`. Should `$purge_members`
		 * be passed, this function will remove all members associated with
		 * this role as well
		 *
		 * @param integer $role_id
		 * @param boolean $purge_members
		 * @return boolean
		 */
		public static function delete($role_id, $purge_members = false) {
			Symphony::Database()->delete("`tbl_members_roles_forbidden_pages`", " `role_id` = " . $role_id);
			Symphony::Database()->delete("`tbl_members_roles_event_permissions`", " `role_id` = " . $role_id);
			Symphony::Database()->delete("`tbl_members_roles`", " `id` = " . $role_id);

			if($purge_members) {
				$members = Symphony::Database()->fetchCol('entry_id', sprintf(
					"SELECT `entry_id` FROM `tbl_entries_data_%d` WHERE `role_id` = %d",
					extension_members::getField('role')->get('id'), $role_id
				));

				/**
				 * Prior to deletion of entries. Array of Entry ID's is provided.
				 * The array can be manipulated
				 *
				 * @delegate Delete
				 * @param string $context
				 * '/publish/'
				 * @param array $checked
				 *  An array of Entry ID's passed by reference
				 */
				Symphony::ExtensionManager()->notifymembers('Delete', '/publish/', array('entry_id' => &$checked));

				EntryManager::delete($members);
			}

			return true;
		}

		/**
		 * This function will return Roles from the database. If the `$role_id` is
		 * given the function will return a Role object (should it be found) otherwise
		 * an array of Role objects will be returned.
		 *
		 * @param integer $role_id
		 * @return Role|array
		 */
		public static function fetch($role_id = null) {
			$result = array();
			$return_single = is_null($role_id) ? false : true;

			if($return_single) {
				// Check static cache for object
				if(in_array($role_id, array_keys(RoleManager::$_pool))) {
					return RoleManager::$_pool[$role_id];
				}

				// No cache object found
				if(!$roles = Symphony::Database()->fetch(sprintf("
						SELECT * FROM `tbl_members_roles` WHERE `id` = %d ORDER BY `id` ASC LIMIT 1",
						$role_id
					))
				) return array();
			}
			else {
				$roles = Symphony::Database()->fetch("SELECT * FROM `tbl_members_roles` ORDER BY `id` ASC");
			}

			foreach($roles as $role) {
				if(!in_array($role['id'], array_keys(RoleManager::$_pool))) {
					RoleManager::$_pool[$role['id']] = new Role($role);
					RoleManager::$_pool[$role['id']]->setPermissions();
				}

				$result[] = RoleManager::$_pool[$role['id']];
			}

			return $return_single ? current($result) : $result;
		}

		/**
		 * This function will find a Role by it's handle. Should `$asObject` be
		 * passed as true, this function will return a Role object, otherwise just
		 * the `$role_id`.
		 *
		 * @param string $handle
		 * @param boolean $asObject
		 * @return integer|Role|null
		 */
		public static function fetchRoleIDByHandle($handle, $asObject = false){
			$role_id = Symphony::Database()->fetchVar('id', 0, sprintf("
				SELECT `id` FROM `tbl_members_roles` WHERE `handle` = '%s' LIMIT 1",
				Symphony::Database()->cleanValue($handle)
			));

			if(!$role_id) return null;

			if(!$asObject) return $role_id;

			return RoleManager::fetch($role_id);
		}
	}

	/**
	 * The Role class defines an Access Level for Frontend members which includes
	 * what pages are accessible and what events a member of this Role can use.
	 */
	Class Role {
		const PUBLIC_ROLE = 1;

		private $settings = array();

		public function __construct(array $settings){
			$this->setArray($settings);

			$this->set('forbidden_pages', array());
			$this->set('event_permissions', array());
		}

		/**
		 * Given a `$name` and a `$value`, this will set it into the Role's
		 * `$this->settings` array. By default, `$name` maps the `tbl_member_roles`
		 * column names.
		 *
		 * @param string $name
		 * @param mixed $value
		 */
		public function set($name, $value) {
			$this->settings[$name] = $value;
		}

		/**
		 * Convenience function to set an associative array without using multiple
		 * `set` calls. This function expects an associative array
		 *
		 * @param array $array
		 */
		public function setArray(array $array) {
			foreach($array as $name => $value) {
				$this->set($name, $value);
			}
		}

		/**
		 * Sets the permissions for the current Role by loading them from
		 * `tbl_member_roles_forbidden_pages` and `tbl_member_roles_event_permissions`.
		 * The permissions are set under `forbidden_pages` and `event_permissions` keys
		 * that can be accessed via `Role->get('event_permissions')`.
		 */
		public function setPermissions() {
			// Get all pages that this Role can't access
			$this->set('forbidden_pages', Symphony::Database()->fetchCol('page_id', sprintf(
				"SELECT `page_id` FROM `tbl_members_roles_forbidden_pages` WHERE `role_id` = %d",
				$this->get('id')
			)));

			// Get the events permssions for this Role
			$event_permissions = array();
			$tmp = Symphony::Database()->fetch(sprintf(
				"SELECT * FROM `tbl_members_roles_event_permissions` WHERE `role_id` = %d",
				$this->get('id')
			));

			if(is_array($tmp) && !empty($tmp)) foreach($tmp as $e) {
				$event_permissions[$e['event']][$e['action']] = $e['level'];
			}

			$this->set('event_permissions', $event_permissions);
		}

		/**
		 * Given a `$name`, this function returns the setting for this Role. If
		 * no setting is found, this function will return null.
		 * If `$name` is not provided, the entire `$this->settings` array will
		 * be returned.
		 *
		 * @param string $name
		 * @return mixed
		 */
		public function get($name = null) {
			if(is_null($name)) return $this->settings;

			if(!array_key_exists($name, $this->settings)) return null;

			return $this->settings[$name];
		}

		/**
		 * Given a `$page_id`, this functions return true if this role is
		 * allowed to view the page with that ID.
		 *
		 * @param integer $page_id
		 * @return boolean
		 */
		public function canAccessPage($page_id){
			return !in_array($page_id, $this->get('forbidden_pages'));
		}

		/**
		 * Given an event handle, the desired action, either create or edit, and
		 * the required permission level, this function will return boolean if
		 * the user can process the event. The `$required_level` is one of the
		 * `EventPermissions` constants, `NO_PERMISSIONS`, `OWN_ENTRIES`, `ALL_ENTRIES`
		 * or `CREATE`.
		 *
		 * @param string $event_handle
		 * @param string $action
		 * @param integer $required_level
		 * @return boolean
		 */
		public function canProcessEvent($event_handle, $action, $required_level){
			$event_permissions = $this->get('event_permissions');

			if(array_key_exists($event_handle, $event_permissions)) {
				return ($event_permissions[$event_handle][$action] >= $required_level);
			}

			// If the event wasn't in the array, then assume it's ok.
			return true;
		}
	}

	Class EventPermissions {
		const NO_PERMISSIONS = 0;
		const OWN_ENTRIES = 1;
		const ALL_ENTRIES = 2;
		const CREATE = 1;

		public static $permissionMap = array(
			self::NO_PERMISSIONS => 'No Permission',
			self::OWN_ENTRIES => 'Own Entries',
			self::ALL_ENTRIES => 'All Entries'
		);
	}


text:
layout: page
title: 404 Not Found
permalink: /404.html
comments: false
author_footer: false
---

当前访问页面不存在

可能旧文已经删除(🙏抱歉),也可能是文章路径有更新,请尝试使用关键字进行站内搜索。

  <input class="page404-search-input" type="text" id="page404-search-input" placeholder="Search" />


text:
import type { NodePath } from "@babel/traverse";
import nameFunction from "@babel/helper-function-name";
import template from "@babel/template";
import * as t from "@babel/types";

const buildExpressionWrapper = template.expression(`
  (function () {
    var REF = FUNCTION;
    return function NAME(PARAMS) {
      return REF.apply(this, arguments);
    };
  })()
`);

const buildDeclarationWrapper = template(`
  function NAME(PARAMS) { return REF.apply(this, arguments); }
  function REF() {
    REF = FUNCTION;
    return REF.apply(this, arguments);
  }
`);

function classOrObjectMethod(path: NodePath, callId: Object) {
  const node = path.node;
  const body = node.body;

  const container = t.functionExpression(
    null,
    [],
    t.blockStatement(body.body),
    true,
  );
  body.body = [
    t.returnStatement(
      t.callExpression(t.callExpression(callId, [container]), []),
    ),
  ];

  // Regardless of whether or not the wrapped function is a an async method
  // or generator the outer function should not be
  node.async = false;
  node.generator = false;

  // Unwrap the wrapper IIFE's environment so super and this and such still work.
  path
    .get("body.body.0.argument.callee.arguments.0")
    .unwrapFunctionEnvironment();
}

function plainFunction(path: NodePath, callId: Object) {
  const node = path.node;
  const isDeclaration = path.isFunctionDeclaration();
  const functionId = node.id;
  const wrapper = isDeclaration
    ? buildDeclarationWrapper
    : buildExpressionWrapper;

  if (path.isArrowFunctionExpression()) {
    path.arrowFunctionToExpression();
  }

  node.id = null;

  if (isDeclaration) {
    node.type = "FunctionExpression";
  }

  const built = t.callExpression(callId, [node]);
  const container = wrapper({
    NAME: functionId || null,
    REF: path.scope.generateUidIdentifier(functionId ? functionId.name : "ref"),
    FUNCTION: built,
    PARAMS: node.params.reduce(
      (acc, param) => {
        acc.done =
          acc.done || t.isAssignmentPattern(param) || t.isRestElement(param);

        if (!acc.done) {
          acc.params.push(path.scope.generateUidIdentifier("x"));
        }

        return acc;
      },
      {
        params: [],
        done: false,
      },
    ).params,
  });

  if (isDeclaration) {
    path.replaceWith(container[0]);
    path.insertAfter(container[1]);
  } else {
    const retFunction = container.callee.body.body[1].argument;
    if (!functionId) {
      nameFunction({
        node: retFunction,
        parent: path.parent,
        scope: path.scope,
      });
    }

    if (!retFunction || retFunction.id || node.params.length) {
      // we have an inferred function id or params so we need this wrapper
      path.replaceWith(container);
    } else {
      // we can omit this wrapper as the conditions it protects for do not apply
      path.replaceWith(built);
    }
  }
}

export default function wrapFunction(path: NodePath, callId: Object) {
  if (path.isClassMethod() || path.isObjectMethod()) {
    classOrObjectMethod(path, callId);
  } else {
    plainFunction(path, callId);
  }
}


text:
var chai = require('chai');
var sinon = require('sinon');

global.expect = chai.expect;
global.sinon = sinon;

// clear console
require('util').print("\u001b[2J\u001b[0;0H");


text:
namespace ceres {

// Identity metafunction.
template <class T>
struct identity_ {
  typedef T type;
};

// Use implicit_cast as a safe version of static_cast or const_cast
// for implicit conversions. For example:
// - Upcasting in a type hierarchy.
// - Performing arithmetic conversions (int32 to int64, int to double, etc.).
// - Adding const or volatile qualifiers.
//
// In general, implicit_cast can be used to convert this code
//   To to = from;
//   DoSomething(to);
// to this
//   DoSomething(implicit_cast<To>(from));
//
// base::identity_ is used to make a non-deduced context, which
// forces all callers to explicitly specify the template argument.
template<typename To>
inline To implicit_cast(typename identity_<To>::type to) {
  return to;
}

// This version of implicit_cast is used when two template arguments
// are specified. It's obsolete and should not be used.
template<typename To, typename From>
inline To implicit_cast(typename identity_<From>::type const &f) {
  return f;
}

// When you upcast (that is, cast a pointer from type Foo to type
// SuperclassOfFoo), it's fine to use implicit_cast<>, since upcasts
// always succeed.  When you downcast (that is, cast a pointer from
// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
// how do you know the pointer is really of type SubclassOfFoo?  It
// could be a bare Foo, or of type DifferentSubclassOfFoo.  Thus,
// when you downcast, you should use this macro.  In debug mode, we
// use dynamic_cast<> to double-check the downcast is legal (we die
// if it's not).  In normal mode, we do the efficient static_cast<>
// instead.  Thus, it's important to test in debug mode to make sure
// the cast is legal!
//    This is the only place in the code we should use dynamic_cast<>.
// In particular, you SHOULDN'T be using dynamic_cast<> in order to
// do RTTI (eg code like this:
//    if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
//    if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
// You should design the code some other way not to need this.

template<typename To, typename From>     // use like this: down_cast<T*>(foo);
inline To down_cast(From* f) {                   // so we only accept pointers
  // Ensures that To is a sub-type of From *.  This test is here only
  // for compile-time type checking, and has no overhead in an
  // optimized build at run-time, as it will be optimized away
  // completely.

  // TODO(csilvers): This should use COMPILE_ASSERT.
  if (false) {
    implicit_cast<From*, To>(NULL);
  }

  // uses RTTI in dbg and fastbuild. asserts are disabled in opt builds.
  assert(f == NULL || dynamic_cast<To>(f) != NULL);  // NOLINT
  return static_cast<To>(f);
}

}  // namespace ceres

#endif  // CERES_INTERNAL_CASTS_H_