var genobj = require('generate-object-property')
var genfun = require('generate-function')
var jsonpointer = require('jsonpointer')
var xtend = require('xtend')
var formats = require('./formats')

var get = function(obj, additionalSchemas, ptr) {
  if (/^https?:\/\//.test(ptr)) return null

  var visit = function(sub) {
    if (sub && sub.id === ptr) return sub
    if (typeof sub !== 'object' || !sub) return null
    return Object.keys(sub).reduce(function(res, k) {
      return res || visit(sub[k])
    }, null)
  }

  var res = visit(obj)
  if (res) return res

  ptr = ptr.replace(/^#/, '')
  ptr = ptr.replace(/\/$/, '')

  try {
    return jsonpointer.get(obj, decodeURI(ptr))
  } catch (err) {
    var end = ptr.indexOf('#')
    var other
    // external reference
    if (end !== 0) {
      // fragment doesn't exist.
      if (end === -1) {
        other = additionalSchemas[ptr]
      } else {
        var ext = ptr.slice(0, end)
        other = additionalSchemas[ext]
        var fragment = ptr.slice(end).replace(/^#/, '')
        try {
          return jsonpointer.get(other, fragment)
        } catch (err) {}
      }
    } else {
      other = additionalSchemas[ptr]
    }
    return other || null
  }
}

var formatName = function(field) {
  field = JSON.stringify(field)
  var pattern = /\[([^\[\]"]+)\]/
  while (pattern.test(field)) field = field.replace(pattern, '."+$1+"')
  return field
}

var types = {}

types.any = function() {
  return 'true'
}

types.null = function(name) {
  return name+' === null'
}

types.boolean = function(name) {
  return 'typeof '+name+' === "boolean"'
}

types.array = function(name) {
  return 'Array.isArray('+name+')'
}

types.object = function(name) {
  return 'typeof '+name+' === "object" && '+name+' && !Array.isArray('+name+')'
}

types.number = function(name) {
  return 'typeof '+name+' === "number"'
}

types.integer = function(name) {
  return 'typeof '+name+' === "number" && (Math.floor('+name+') === '+name+' || '+name+' > 9007199254740992 || '+name+' < -9007199254740992)'
}

types.string = function(name) {
  return 'typeof '+name+' === "string"'
}

var unique = function(array) {
  var list = []
  for (var i = 0; i < array.length; i++) {
    list.push(typeof array[i] === 'object' ? JSON.stringify(array[i]) : array[i])
  }
  for (var i = 1; i < list.length; i++) {
    if (list.indexOf(list[i]) !== i) return false
  }
  return true
}

var toType = function(node) {
  return node.type
}

var compile = function(schema, cache, root, reporter, opts) {
  var fmts = opts ? xtend(formats, opts.formats) : formats
  var scope = {unique:unique, formats:fmts}
  var verbose = opts ? !!opts.verbose : false;
  var greedy = opts && opts.greedy !== undefined ?
    opts.greedy : false;

  var syms = {}
  var gensym = function(name) {
    return name+(syms[name] = (syms[name] || 0)+1)
  }

  var reversePatterns = {}
  var patterns = function(p) {
    if (reversePatterns[p]) return reversePatterns[p]
    var n = gensym('pattern')
    scope[n] = new RegExp(p)
    reversePatterns[p] = n
    return n
  }

  var vars = ['i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z']
  var genloop = function() {
    var v = vars.shift()
    vars.push(v+v[0])
    return v
  }

  var visit = function(name, node, reporter, filter) {
    var properties = node.properties
    var type = node.type
    var tuple = false

    if (Array.isArray(node.items)) { // tuple type
      properties = {}
      node.items.forEach(function(item, i) {
        properties[i] = item
      })
      type = 'array'
      tuple = true
    }

    var indent = 0
    var error = function(msg, prop, value) {
      validate('errors++')
      if (reporter === true) {
        validate('if (validate.errors === null) validate.errors = []')
        if (verbose) {
          validate('validate.errors.push({field:%s,message:%s,value:%s})', formatName(prop || name), JSON.stringify(msg), value || name)
        } else {
          validate('validate.errors.push({field:%s,message:%s})', formatName(prop || name), JSON.stringify(msg))
        }
      }
    }

    if (node.required === true) {
      indent++
      validate('if (%s === undefined) {', name)
      error('is required')
      validate('} else {')
    } else {
      indent++
      validate('if (%s !== undefined) {', name)
    }

    var valid = [].concat(type)
      .map(function(t) {
        return types[t || 'any'](name)
      })
      .join(' || ') || 'true'

    if (valid !== 'true') {
      indent++
      validate('if (!(%s)) {', valid)
      error('is the wrong type')
      validate('} else {')
    }

    if (tuple) {
      if (node.additionalItems === false) {
        validate('if (%s.length > %d) {', name, node.items.length)
        error('has additional items')
        validate('}')
      } else if (node.additionalItems) {
        var i = genloop()
        validate('for (var %s = %d; %s < %s.length; %s++) {', i, node.items.length, i, name, i)
        visit(name+'['+i+']', node.additionalItems, reporter, filter)
        validate('}')
      }
    }

    if (node.format && fmts[node.format]) {
      if (type !== 'string' && formats[node.format]) validate('if (%s) {', types.string(name))
      var n = gensym('format')
      scope[n] = fmts[node.format]

      if (typeof scope[n] === 'function') validate('if (!%s(%s)) {', n, name)
      else validate('if (!%s.test(%s)) {', n, name)
      error('must be '+node.format+' format')
      validate('}')
      if (type !== 'string' && formats[node.format]) validate('}')
    }

    if (Array.isArray(node.required)) {
      var isUndefined = function(req) {
        return genobj(name, req) + ' === undefined'
      }

      var checkRequired = function (req) {
        var prop = genobj(name, req);
        validate('if (%s === undefined) {', prop)
        error('is required', prop)
        validate('missing++')
        validate('}')
      }
      validate('if ((%s)) {', type !== 'object' ? types.object(name) : 'true')
      validate('var missing = 0')
      node.required.map(checkRequired)
      validate('}');
      if (!greedy) {
        validate('if (missing === 0) {')
        indent++
      }
    }

    if (node.uniqueItems) {
      if (type !== 'array') validate('if (%s) {', types.array(name))
      validate('if (!(unique(%s))) {', name)
      error('must be unique')
      validate('}')
      if (type !== 'array') validate('}')
    }

    if (node.enum) {
      var complex = node.enum.some(function(e) {
        return typeof e === 'object'
      })

      var compare = complex ?
        function(e) {
          return 'JSON.stringify('+name+')'+' !== JSON.stringify('+JSON.stringify(e)+')'
        } :
        function(e) {
          return name+' !== '+JSON.stringify(e)
        }

      validate('if (%s) {', node.enum.map(compare).join(' && ') || 'false')
      error('must be an enum value')
      validate('}')
    }

    if (node.dependencies) {
      if (type !== 'object') validate('if (%s) {', types.object(name))

      Object.keys(node.dependencies).forEach(function(key) {
        var deps = node.dependencies[key]
        if (typeof deps === 'string') deps = [deps]

        var exists = function(k) {
          return genobj(name, k) + ' !== undefined'
        }

        if (Array.isArray(deps)) {
          validate('if (%s !== undefined && !(%s)) {', genobj(name, key), deps.map(exists).join(' && ') || 'true')
          error('dependencies not set')
          validate('}')
        }
        if (typeof deps === 'object') {
          validate('if (%s !== undefined) {', genobj(name, key))
          visit(name, deps, reporter, filter)
          validate('}')
        }
      })

      if (type !== 'object') validate('}')
    }

    if (node.additionalProperties || node.additionalProperties === false) {
      if (type !== 'object') validate('if (%s) {', types.object(name))

      var i = genloop()
      var keys = gensym('keys')

      var toCompare = function(p) {
        return keys+'['+i+'] !== '+JSON.stringify(p)
      }

      var toTest = function(p) {
        return '!'+patterns(p)+'.test('+keys+'['+i+'])'
      }

      var additionalProp = Object.keys(properties || {}).map(toCompare)
        .concat(Object.keys(node.patternProperties || {}).map(toTest))
        .join(' && ') || 'true'

      validate('var %s = Object.keys(%s)', keys, name)
        ('for (var %s = 0; %s < %s.length; %s++) {', i, i, keys, i)
          ('if (%s) {', additionalProp)

      if (node.additionalProperties === false) {
        if (filter) validate('delete %s', name+'['+keys+'['+i+']]')
        error('has additional properties', null, JSON.stringify(name+'.') + ' + ' + keys + '['+i+']')
      } else {
        visit(name+'['+keys+'['+i+']]', node.additionalProperties, reporter, filter)
      }

      validate
          ('}')
        ('}')

      if (type !== 'object') validate('}')
    }

    if (node.$ref) {
      var sub = get(root, opts && opts.schemas || {}, node.$ref)
      if (sub) {
        var fn = cache[node.$ref]
        if (!fn) {
          cache[node.$ref] = function proxy(data) {
            return fn(data)
          }
          fn = compile(sub, cache, root, false, opts)
        }
        var n = gensym('ref')
        scope[n] = fn
        validate('if (!(%s(%s))) {', n, name)
        error('referenced schema does not match')
        validate('}')
      }
    }

    if (node.not) {
      var prev = gensym('prev')
      validate('var %s = errors', prev)
      visit(name, node.not, false, filter)
      validate('if (%s === errors) {', prev)
      error('negative schema matches')
      validate('} else {')
        ('errors = %s', prev)
      ('}')
    }

    if (node.items && !tuple) {
      if (type !== 'array') validate('if (%s) {', types.array(name))

      var i = genloop()
      validate('for (var %s = 0; %s < %s.length; %s++) {', i, i, name, i)
      visit(name+'['+i+']', node.items, reporter, filter)
      validate('}')

      if (type !== 'array') validate('}')
    }

    if (node.patternProperties) {
      if (type !== 'object') validate('if (%s) {', types.object(name))
      var keys = gensym('keys')
      var i = genloop()
      validate
        ('var %s = Object.keys(%s)', keys, name)
        ('for (var %s = 0; %s < %s.length; %s++) {', i, i, keys, i)

      Object.keys(node.patternProperties).forEach(function(key) {
        var p = patterns(key)
        validate('if (%s.test(%s)) {', p, keys+'['+i+']')
        visit(name+'['+keys+'['+i+']]', node.patternProperties[key], reporter, filter)
        validate('}')
      })

      validate('}')
      if (type !== 'object') validate('}')
    }

    if (node.pattern) {
      var p = patterns(node.pattern)
      if (type !== 'string') validate('if (%s) {', types.string(name))
      validate('if (!(%s.test(%s))) {', p, name)
      error('pattern mismatch')
      validate('}')
      if (type !== 'string') validate('}')
    }

    if (node.allOf) {
      node.allOf.forEach(function(sch) {
        visit(name, sch, reporter, filter)
      })
    }

    if (node.anyOf && node.anyOf.length) {
      var prev = gensym('prev')

      node.anyOf.forEach(function(sch, i) {
        if (i === 0) {
          validate('var %s = errors', prev)
        } else {
          validate('if (errors !== %s) {', prev)
            ('errors = %s', prev)
        }
        visit(name, sch, false, false)
      })
      node.anyOf.forEach(function(sch, i) {
        if (i) validate('}')
      })
      validate('if (%s !== errors) {', prev)
      error('no schemas match')
      validate('}')
    }

    if (node.oneOf && node.oneOf.length) {
      var prev = gensym('prev')
      var passes = gensym('passes')

      validate
        ('var %s = errors', prev)
        ('var %s = 0', passes)

      node.oneOf.forEach(function(sch, i) {
        visit(name, sch, false, false)
        validate('if (%s === errors) {', prev)
          ('%s++', passes)
        ('} else {')
          ('errors = %s', prev)
        ('}')
      })

      validate('if (%s !== 1) {', passes)
      error('no (or more than one) schemas match')
      validate('}')
    }

    if (node.multipleOf !== undefined) {
      if (type !== 'number' && type !== 'integer') validate('if (%s) {', types.number(name))

      var factor = ((node.multipleOf | 0) !== node.multipleOf) ? Math.pow(10, node.multipleOf.toString().split('.').pop().length) : 1
      if (factor > 1) validate('if ((%d*%s) % %d) {', factor, name, factor*node.multipleOf)
      else validate('if (%s % %d) {', name, node.multipleOf)

      error('has a remainder')
      validate('}')

      if (type !== 'number' && type !== 'integer') validate('}')
    }

    if (node.maxProperties !== undefined) {
      if (type !== 'object') validate('if (%s) {', types.object(name))

      validate('if (Object.keys(%s).length > %d) {', name, node.maxProperties)
      error('has more properties than allowed')
      validate('}')

      if (type !== 'object') validate('}')
    }

    if (node.minProperties !== undefined) {
      if (type !== 'object') validate('if (%s) {', types.object(name))

      validate('if (Object.keys(%s).length < %d) {', name, node.minProperties)
      error('has less properties than allowed')
      validate('}')

      if (type !== 'object') validate('}')
    }

    if (node.maxItems !== undefined) {
      if (type !== 'array') validate('if (%s) {', types.array(name))

      validate('if (%s.length > %d) {', name, node.maxItems)
      error('has more items than allowed')
      validate('}')

      if (type !== 'array') validate('}')
    }

    if (node.minItems !== undefined) {
      if (type !== 'array') validate('if (%s) {', types.array(name))

      validate('if (%s.length < %d) {', name, node.minItems)
      error('has less items than allowed')
      validate('}')

      if (type !== 'array') validate('}')
    }

    if (node.maxLength !== undefined) {
      if (type !== 'string') validate('if (%s) {', types.string(name))

      validate('if (%s.length > %d) {', name, node.maxLength)
      error('has longer length than allowed')
      validate('}')

      if (type !== 'string') validate('}')
    }

    if (node.minLength !== undefined) {
      if (type !== 'string') validate('if (%s) {', types.string(name))

      validate('if (%s.length < %d) {', name, node.minLength)
      error('has less length than allowed')
      validate('}')

      if (type !== 'string') validate('}')
    }

    if (node.minimum !== undefined) {
      validate('if (%s %s %d) {', name, node.exclusiveMinimum ? '<=' : '<', node.minimum)
      error('is less than minimum')
      validate('}')
    }

    if (node.maximum !== undefined) {
      validate('if (%s %s %d) {', name, node.exclusiveMaximum ? '>=' : '>', node.maximum)
      error('is more than maximum')
      validate('}')
    }

    if (properties) {
      Object.keys(properties).forEach(function(p) {
        visit(genobj(name, p), properties[p], reporter, filter)
      })
    }

    while (indent--) validate('}')
  }

  var validate = genfun
    ('function validate(data) {')
      ('validate.errors = null')
      ('var errors = 0')

  visit('data', schema, reporter, opts && opts.filter)

  validate
      ('return errors === 0')
    ('}')

  validate = validate.toFunction(scope)
  validate.errors = null

  validate.__defineGetter__('error', function() {
    if (!validate.errors) return ''
    return validate.errors
      .map(function(err) {
        return err.field+' '+err.message
      })
      .join('\n')
  })

  validate.toJSON = function() {
    return schema
  }

  return validate
}

module.exports = function(schema, opts) {
  if (typeof schema === 'string') schema = JSON.parse(schema)
  return compile(schema, {}, schema, true, opts)
}

module.exports.filter = function(schema, opts) {
  var validate = module.exports(schema, xtend(opts, {filter: true}))
  return function(sch) {
    validate(sch)
    return sch
  }
}

{'repo_name': 'phamtrisi/airapi', 'stars': '135', 'repo_language': 'JavaScript', 'file_name': 'getCalendar.js', 'mime_type': 'text/plain', 'hash': -3634038918027859138, 'source_dataset': 'data'}


<?php
class ERestController extends Controller
{
	Const APPLICATION_ID = 'REST';
	Const C404NOTFOUND = 'HTTP/1.1 404 Not Found';
	Const C401UNAUTHORIZED = 'HTTP/1.1 401 Unauthorized';
	Const C406NOTACCEPTABLE = 'HTTP/1.1 406 Not Acceptable';
	Const C201CREATED = 'HTTP/1.1 201 Created';
	Const C200OK = 'HTTP/1.1 200 OK';
	Const C500INTERNALSERVERERROR = 'HTTP/1.1 500 Internal Server Error';

	public $HTTPStatus = 'HTTP/1.1 200 OK';
	public $restrictedProperties = array();
	public $restFilter = array();
	public $restSort = array();
	public $restLimit = 100; // Default limit
	public $restOffset = 0; //Default Offset
	public $developmentFlag = true; //When set to `false' 500 erros will not return detailed messages.
	protected $httpsOnly= FALSE; // Setting this variable to true allows the service to be used only via https
	//Auto will include all relations
	//FALSE will include no relations in response
	//You may also pass an array of relations IE array('posts', 'comments', etc..)
	//Override $nestedModels in your controller as needed
	public $nestedModels = 'auto';

	protected $requestReader;
	protected $model = null;

	public function __construct($id, $module = null)
	{
		parent::__construct($id, $module);
		$this->requestReader = new ERequestReader('php://input');
	}

	public function beforeAction($event)
	{
		if(isset($_GET['filter']))
			$this->restFilter = $_GET['filter'];

		if(isset($_GET['sort']))
			$this->restSort = $_GET['sort'];

		if(isset($_GET['limit']))
			$this->restLimit = $_GET['limit'];

		if(isset($_GET['offset']))
			$this->restOffset = $_GET['offset'];

		return parent::beforeAction($event);
	}

	public function onException($event)
	{
		if(!$this->developmentFlag && ($event->exception->statusCode == 500 || is_null($event->exception->statusCode)))
			$message = "Internal Server Error";
		else
		{
			$message = $event->exception->getMessage();
			if($tempMessage = CJSON::decode($message))
				$message = $tempMessage;
		}

		$errorCode = (!isset($event->exception->statusCode) || is_null($event->exception->statusCode))? 500: $event->exception->statusCode;

		$this->renderJson(array('success' => false, 'message' => $message, 'data' => array('errorCode'=>$errorCode)));
		$event->handled = true;
	}

	public function filters()
	{
		$restFilters = array('HttpsOnly','restAccessRules+ restList restView restCreate restUpdate restDelete');
		if(method_exists($this, '_filters'))
			return CMap::mergeArray($restFilters, $this->_filters());
		else
			return $restFilters;
	}

 	/**
	 * @author Romina Suarez
	 *
	 * allows users to block any nonHttps request if they want their service to be safe
	 * If the attribute $httpsOnly is set in one of the controllers that extend ERestController,
	 * you can avoid a specific model from being using witouth a secure connection.
	 */
	public function filterHttpsOnly($c){
		if ($this->httpsOnly){
			if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS']!='on'){
				Yii::app()->errorHandler->errorAction = '/' . $this->uniqueid . '/error';
				throw new CHttpException(401, "You must use a secure connection");
			}
		}
		$c->run();
	}
	public function accessRules()
	{
		$restAccessRules = array(
			array(
				'allow',	// allow all users to perform 'index' and 'view' actions
				'actions'=>array('restList', 'restView', 'restCreate', 'restUpdate', 'restDelete', 'error'),
				'users'=>array('*'),
			)
		);

		if(method_exists($this, '_accessRules'))
			return CMap::mergeArray($restAccessRules, $this->_accessRules());
		else
			return $restAccessRules;
	}

	/**
	 * Controls access to restfull requests
	 */
	public function filterRestAccessRules( $c )
	{
		Yii::app()->clientScript->reset(); //Remove any scripts registered by Controller Class
		Yii::app()->onException = array($this, 'onException'); //Register Custom Exception
		//For requests from JS check that a user is loged in and call validateUser
		//validateUser can/should be overridden in your controller.
		if(!Yii::app()->user->isGuest && $this->validateAjaxUser($this->action->id))
			$c->run();
		else
		{
			Yii::app()->errorHandler->errorAction = '/' . $this->uniqueid . '/error';

			if(!(isset($_SERVER['HTTP_X_'.self::APPLICATION_ID.'_USERNAME']) and isset($_SERVER['HTTP_X_'.self::APPLICATION_ID.'_PASSWORD']))) {
				// Error: Unauthorized
				throw new CHttpException(401, 'You are not authorized to preform this action.');
			}
			$username = $_SERVER['HTTP_X_'.self::APPLICATION_ID.'_USERNAME'];
			$password = $_SERVER['HTTP_X_'.self::APPLICATION_ID.'_PASSWORD'];
			// Find the user
			if($username != Yii::app()->params['RESTusername'])
			{
				// Error: Unauthorized
				throw new CHttpException(401, 'Error: User Name is invalid');
			}
			else if($password != Yii::app()->params['RESTpassword'])
			{
				// Error: Unauthorized
				throw new CHttpException(401, 'Error: User Password is invalid');
			}
			// This tells the filter chain $c to keep processing.
			$c->run();
		}
	}

	/**
	 * Custom error handler for restfull Errors
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			//print_r($error); exit();
			if(!Yii::app()->request->isAjaxRequest)
				$this->HTTPStatus = $this->getHttpStatus($error['code'], 'C500INTERNALSERVERERROR');
			else if(!$this->developmentFlag)
			{
				if($error['code'] == 500)
					$error['message'] = 'Internal Server Error';
			}

			$this->renderJson(array('success' => false, 'message' => $error['message'], 'data' => array('errorCode'=>$error['code'])));
		}
	}

	/**
	 * Get HTTP Status Headers From code
	 */
	public function getHttpStatus($statusCode, $default='C200OK')
	{
		switch ($statusCode)
		{
			case '200':
				return self::C200OK;
				break;
			case '201':
				return self::C201CREATED;
				break;
			case '401':
				return self::C401UNAUTHORIZED;
				break;
			case '404':
				return self::C404NOTFOUND;
				break;
			case '406':
				return self::C406NOTACCEPTABLE;
				break;
			case '500':
				return self::C500INTERNALSERVERERROR;
				break;
			default:
				return self::$default;
		}
	}

	protected function getNestedRelations()
	{
		$nestedRelations = array();
		if(!is_array($this->nestedModels) && $this->nestedModels == 'auto')
		{
			foreach($this->model->metadata->relations as $rel=>$val)
			{
				$className = $val->className;
				if(!is_array($className::model()->tableSchema->primaryKey))
					$nestedRelations[] = $rel;
			}
			return $nestedRelations;
		}
		else if(!is_array($this->nestedModels) && $this->nestedModels === false)
			return $nestedRelations;
		else if(is_array($this->nestedModels))
			return $this->nestedModels;

		return $nestedRelations;
	}

 /**
	******************************************************************************************
	******************************************************************************************
	* Actions that are tiggered by RESTFull requests
	* To change their default behavoir
	* you should overide "doRest..." Methods in the controller
	* and leave these actions as is
	******************************************************************************************
	******************************************************************************************
	 */

	/**
	 * Renders list of data assosiated with controller as json
	 */
	public function actionRestList()
	{
		$this->doRestList();
	}

	/**
	 * Renders View of record as json
	 * Or Custom method
	 */
	public function actionRestView($id, $var=null, $var2=null)
	{
		if($this->isPk($id) && is_null($var))
			$this->doRestView($id);
		else
		{
			if($this->isPk($id) && !is_null($var) && is_null($var2))
			{
				if($this->validateSubResource($var))
					$this->doRestViewSubResource($id, $var);
				else
					$this->triggerCustomRestGet(ucFirst($var), array($id));
			}
			else if($this->isPk($id) && !is_null($var) && !is_null($var2))
			{
				if($this->validateSubResource($var))
					$this->doRestViewSubResource($id, $var, $var2);
				else
					$this->triggerCustomRestGet(ucFirst($var), array($id, $var2));
			}
			else
			{
				//if the $id is not numeric and var + var2 are not set
				//we are assume that the client is attempting to call a custom method
				//There may optionaly be a second param `$var` passed in the url
				$this->triggerCustomRestGet(ucFirst($id), array($var, $var2));
			}
		}
	}

	/**
	 * Updated record
	 */
	public function actionRestUpdate($id, $var=null, $var2=null)
	{
		$this->HTTPStatus = $this->getHttpStatus('200');

		if($this->isPk($id))
		{
			if(is_null($var))
				$this->doRestUpdate($id, $this->data());
			else if (is_null($var2))
				$this->triggerCustomRestPut($var, array($id));
			else if(!is_null($var2))
			{
				if($this->validateSubResource($var))
					$this->doRestUpdateSubResource($id, $var, $var2);
				else
					$this->triggerCustomRestPut($var, array($id, $var2));
			}
		}
		else
			$this->triggerCustomRestPut($id, array($var, $var2));
	}

	/**
	 * Creates new record
	 */
	public function actionRestCreate($id=null, $var=null)
	{
		$this->HTTPStatus = $this->getHttpStatus('201');

		if(!$id)
		{
			$this->doRestCreate($this->data());
		}
		else
		{
			//we can assume if $id is set and var is not a subresource
			//then the user is trying to call a custom method
			$var = 'doCustomRestPost' . ucfirst($id);
			if(method_exists($this, $var))
				$this->$var($this->data());
			else if($this->isPk($var))
				$this->doRestCreate($this->data());
			else
				throw new CHttpException(500, 'Method or Sub-Resource does not exist.');
		}
	}

	/**
	 * Deletes record
	 */
	public function actionRestDelete($id, $var=null, $var2=null)
	{
		if($this->isPk($id))
		{
			if(is_null($var))
				$this->doRestDelete($id);
			else if(!is_null($var2))
			{
				if($this->validateSubResource($var, $var2))
					$this->doRestDeleteSubResource($id, $var, $var2); //Looks like we are trying to delete a subResource
				else
					$this->triggerCustomDelete($var, array($id, $var2));
			}
			else
				$this->triggerCustomDelete($var, array($id));
		}
		else
		{
			$this->triggerCustomDelete($id, array($var, $var2));
		}
	}

	 /**
	******************************************************************************************
	******************************************************************************************
	* Helper functions for processing Rest data
	******************************************************************************************
	******************************************************************************************
	 */

	/**
	 * Takes array and renders Json String
	 */
	protected function renderJson($data) {
		$this->layout = 'ext.restfullyii.views.layouts.json';
		$this->render('ext.restfullyii.views.api.output', array('data'=>$data));
	}

	/**
	 * Get data submited by the client
	 */
	public function data()
	{
		$request = $this->requestReader->getContents();
		if ($request) {
			if ($json_post = CJSON::decode($request)){
				return $json_post;
			}else{
				parse_str($request,$variables);
				return $variables;
			}
		}
		return false;
	}

	/**
	 * Returns the model assosiated with this controller.
	 * The assumption is that the model name matches your controller name
	 * If this is not the case you should override this method in your controller
	 */
	public function getModel()
	{
		if ($this->model === null)
		{
			$modelName = str_replace('Controller', '', get_class($this));
			$this->model = new $modelName;
		}
		$this->_attachBehaviors($this->model);
		return $this->model;
	}

	/**
	* Helper for loading a single model
	*/
	protected function loadOneModel($id)
	{
		return $this->getModel()->with($this->nestedRelations)->findByPk($id);
	}

	//Updated setModelAttributes to allow for related data to be set.
	private function setModelAttributes($model, $data)
	{
		foreach($data as $var=>$value)
		{
			if(($model->hasAttribute($var) || isset($model->metadata->relations[$var])) && !in_array($var, $this->restrictedProperties))
				$model->$var = $value;
			else
				throw new CHttpException(406, 'Parameter \'' . $var . '\' is not allowed for model');
		 }
		return $model;
	}

	/**
	 * Helper for saving single/mutliple models
	 */
	protected function saveModel($model, $data) {
        if (empty($data)) {
            $this->HTTPStatus = $this->getHttpStatus(406);
            throw new CHttpException(406, 'Model could not be saved as empty data.');
        }

        if (!isset($data[0]))
            $models[] = $this->setModelAttributes($model, $data);
        else {
            for ($i = 0; $i < count($data); $i++) {
                $models[$i] = $this->setModelAttributes($this->getModel(), $data[$i]);
                $this->model = null;
            }
        }

        for ($cnt = 0; $cnt < count($models); $cnt++) {
            $this->_attachBehaviors($models[$cnt]);
            if ($models[$cnt]->validate()) {
                if (!$models[$cnt]->save()) {
                    $this->HTTPStatus = $this->getHttpStatus(406);
                    throw new CHttpException(406, 'Model could not be saved');
                }else
                    $ids[] = $models[$cnt]->{$models[$cnt]->tableSchema->primaryKey};
            }else {
                $message = CJSON::encode(array('error' => 'Model could not be saved as validation failed.',
                            'validation' => $models[$cnt]->getErrors()));

                $this->HTTPStatus = $this->getHttpStatus(406);
                throw new CHttpException(406, $message);
            }
        }
        return $models;
    }

    //Attach helper behaviors
	public function _attachBehaviors($model)
	{
		//Attach this behavior to help saving nested models
		if(!array_key_exists('EActiveRecordRelationBehavior', $model->behaviors()))
			$model->attachBehavior('EActiveRecordRelationBehavior', new EActiveRecordRelationBehavior());

		//Attach this behavior to help outputting models and their relations as arrays
		if(!array_key_exists('MorrayBehavior', $model->behaviors()))
			$model->attachBehavior('MorrayBehavior', new MorrayBehavior());

		if(!array_key_exists('ERestHelperScopes', $model->behaviors()))
			$model->attachBehavior('ERestHelperScopes', new ERestHelperScopes());

		return true;
	}

	/**
	 *  Convert list of models or single model to array
	 */
	public function allToArray($models, $options=array('relname'=>''))
	{
		if(is_array($models))
		{
			$results = array();
			foreach($models as $model)
			{
				$this->_attachBehaviors($model);
				$results[] = $model->toArray($options);
			}
				return $results;
		}
		else if($models != null)
		{
			$this->_attachBehaviors($models);
			return $models->toArray($options);
		}
		else
			return array();
	}

	public function triggerCustomRestGet($id, $vars=array())
	{
		$method = 'doCustomRestGet' . ucfirst($id);
		if(method_exists($this, $method))
			$this->$method($vars);
		else
			throw new CHttpException(500, 'Method or Sub-Resource does not exist.');
	}

	public function triggerCustomRestPut($method, $vars=array())
	{
		$method = 'doCustomRestPut' . ucfirst($method);

		if(method_exists($this, $method))
		{
			if(count($vars) > 0)
				$this->$method($this->data(), $vars);
			else
				$this->$method($this->data());
		}
		throw new CHttpException(500, 'Method or Sub-Resource does not exist.');
	}

	public function triggerCustomDelete($methodName, $vars=array())
	{
		$method = 'doCustomRestDelete' . ucfirst($methodName);
		if(method_exists($this, $method))
			$this->$method($vars);
		else
			throw new CHttpException(500, 'Method or Sub-Resource does not exist.');
	}

	public function validateSubResource($subResourceName, $subResourceID=null)
	{
		if(is_null($relations = $this->getModel()->relations()))
			return false;
		if(!isset($relations[$subResourceName]))
			return false;
		if($relations[$subResourceName][0] != CActiveRecord::MANY_MANY)
			return false;
		if(!is_null($subResourceID))
			return filter_var($subResourceID, FILTER_VALIDATE_INT) !== false;

		return true;
	}

	public function getSubResource($subResourceName)
	{
		$relations = $this->getModel()->relations();
		return $this->getModel()->parseManyManyFk($subResourceName, $relations[$subResourceName]);
	}

	/**
	******************************************************************************************
	******************************************************************************************
	* OVERIDE THE METHODS BELOW IN YOUR CONTROLLER TO REMOVE/ALTER DEFAULT FUNCTIONALITY
	******************************************************************************************
	******************************************************************************************
	 */

	/**
	 * Override this function if your model uses a non Numeric PK.
	 */
	public function isPk($pk)
	{
		return filter_var($pk, FILTER_VALIDATE_INT) !== false;
	}

	/**
	 * You should override this method to provide stronger access control
	 * to specifc restfull actions via AJAX
	 */
	public function validateAjaxUser($action)
	{
		return false;
	}

	public function outputHelper($message, $results, $totalCount=0, $model=null)
	{
		if(is_null($model))
			$model = lcfirst(get_class($this->model));
		else
			$model = lcfirst($model);

		$this->renderJson(array(
			'success'=>true,
			'message'=>$message,
			'data'=>array(
				'totalCount'=>$totalCount,
				$model=>$this->allToArray($results)
			)
		));
	}

	/**
	 * This is broken out as a sperate method from actionRestList
	 * To allow for easy overriding in the controller
	 * and to allow for easy unit testing
	 */
	public function doRestList()
	{
		$this->outputHelper(
			'Records Retrieved Successfully',
			$this->getModel()->with($this->nestedRelations)
				->filter($this->restFilter)->orderBy($this->restSort)
				->limit($this->restLimit)->offset($this->restOffset)
			->findAll(),
			$this->getModel()
				->with($this->nestedRelations)
				->filter($this->restFilter)
			->count()
		);
	}

	/**
	 * This is broken out as a sperate method from actionRestView
	 * To allow for easy overriding in the controller
	 * adn to allow for easy unit testing
	 */
	public function doRestViewSubResource($id, $subResource, $subResourceID=null)
	{
		$subResourceRelation = $this->getModel()->getActiveRelation($subResource);
		$subResourceModel = new $subResourceRelation->className;
		$this->_attachBehaviors($subResourceModel);

		if(is_null($subResourceID))
		{
			$modelName = get_class($this->model);
			$newRelationName = "_" . $subResourceRelation->className . "Count";
			$this->getModel()->metaData->addRelation($newRelationName, array(
        $modelName::STAT, $subResourceRelation->className, $subResourceRelation->foreignKey
			));

			$model = $this->getModel()->with($newRelationName)->findByPk($id);
			$count = $model->$newRelationName;

			$results = $this->getModel()
				->with($subResource)
				->limit($this->restLimit)
				->offset($this->restOffset)
			->findByPk($id, array('together'=>true));

			$results = $results->$subResource;

			$this->outputHelper(
				'Records Retrieved Successfully',
				$results,
				$count,
				$subResourceRelation->className
			);
		}
		else
		{
			$results = $this->getModel()
				->with($subResource)
				->findByPk($id, array('condition'=>"$subResource.id=$subResourceID"));

			if(is_null($results))
			{
				$this->HTTPStatus = 404;
				throw new CHttpException('404', 'Record Not Found');
			}

			$this->outputHelper(
				'Record Retrieved Successfully',
				$results->$subResource,
				1,
				$subResourceRelation->className
			);
		}
	}

	 /**
	 * This is broken out as a sperate method from actionRestView
	 * To allow for easy overriding in the controller
	 * adn to allow for easy unit testing
	 */
	public function doRestView($id)
	{
		$model = $this->loadOneModel($id);
		if(is_null($model))
		{
			$this->HTTPStatus = 404;
				throw new CHttpException('404', 'Record Not Found');
		}

		$this->outputHelper(
			'Record Retrieved Successfully',
			$model,
			1
		);
	}

	/**
	 * This is broken out as a sperate method from actionResUpdate
	 * To allow for easy overriding in the controller
	 * and to allow for easy unit testing
	 */
    public function doRestUpdate($id, $data) {
        $model = $this->loadOneModel($id);
        if (is_null($model)) {
            $this->HTTPStatus = $this->getHttpStatus(404);
            throw new CHttpException(404, 'Record Not Found');
        }else{
            $model = $this->saveModel($model, $data);
			$this->outputHelper(
						'Record Updated', $model, 1
			);
		}
    }

	/**
	 * This is broken out as a sperate method from actionRestCreate
	 * To allow for easy overriding in the controller
	 * and to alow for easy unit testing
	 */
	public function doRestCreate($data)
	{
		$models = $this->saveModel($this->getModel(), $data);
		//$this->renderJson(array('success'=>true, 'message'=>'Record(s) Created', 'data'=>array($models)));
		$this->outputHelper(
			'Record(s) Created',
			$models,
			count($models)
		);
	}

	/**
	 * This is broken out as a sperate method from actionRestCreate
	 * To allow for easy overriding in the controller
	 * and to alow for easy unit testing
	 */
	public function doRestUpdateSubResource($id, $subResource, $subResourceID)
	{
		list($relationTable, $fks) = $this->getSubResource($subResource);
		if($this->saveSubResource($id, $subResourceID, $relationTable, $fks) > 0)
		{
			$this->renderJson(
				array('success'=>true, 'message'=>'Sub-Resource Added', 'data'=>array(
					$fks[0] => $id,
					$fks[1] => $subResourceID,
				))
			);
		}
		else
			throw new CHttpException('500', 'Could not save Sub-Resource');

	}

	public function saveSubResource($pk, $fk, $relationTable, $fks)
	{
		return $this->getModel()->dbConnection->commandBuilder->createInsertCommand($relationTable, array(
			$fks[0] => $pk,
			$fks[1] => $fk,
		))->execute();
	}

	/**
	 * This is broken out as a sperate method from actionRestDelete
	 * To allow for easy overridding in the controller
	 * and to alow for easy unit testing
	 */
	public function doRestDelete($id) {
        $model = $this->loadOneModel($id);
        if (is_null($model)) {
            $this->HTTPStatus = $this->getHttpStatus(404);
            throw new CHttpException(404, 'Record Not Found');
        } else {
            if ($model->delete())
                $data = array('success' => true, 'message' => 'Record Deleted', 'data' => array('id' => $id));
            else {
                $this->HTTPStatus = $this->getHttpStatus(406);
                throw new CHttpException(406, 'Could not delete model with ID: ' . $id);
            }
            $this->renderJson($data);
        }
    }

	/**
	 * This is broken out as a sperate method from actionRestDelete
	 * To allow for easy overridding in the controller
	 * and to alow for easy unit testing
	 */
	public function doRestDeleteSubResource($id, $subResource, $subResourceID)
	{
		list($relationTable, $fks) = $this->getSubResource($subResource);
		$criteria=new CDbCriteria();
		$criteria->addColumnCondition(array(
			$fks[0]=>$id,
			$fks[1]=>$subResourceID
		));
		if($this->getModel()->dbConnection->commandBuilder->createDeleteCommand($relationTable, $criteria)->execute())
		{
			$data = array('success'=>true, 'message'=>'Record Deleted', 'data'=>array(
				$fks[0]=>$id,
				$fks[1]=>$subResourceID
			));
		}
		else
		{
			throw new CHttpException(406, 'Could not delete model with ID: ' . array(
				$fks[0]=>$id,
				$fks[1]=>$subResourceID
			));
		}

		$this->renderJson($data);
	}

	public function setRequestReader($requestReader)
	{
		$this->requestReader = $requestReader;
	}

	public function setModel($model)
	{
		$this->model = $model;
	}
}

{'repo_name': 'kabasakalis/angular-yii', 'stars': '146', 'repo_language': 'JavaScript', 'file_name': 'jquery-1.8.2.js', 'mime_type': 'text/plain', 'hash': -8616298671820003874, 'source_dataset': 'data'}


/*
//
//               INTEL CORPORATION PROPRIETARY INFORMATION
//  This software is supplied under the terms of a license agreement or
//  nondisclosure agreement with Intel Corporation and may not be copied
//  or disclosed except in accordance with the terms of that agreement.
//        Copyright(c) 2002-2006 Intel Corporation. All Rights Reserved.
//
*/
#ifndef __AAC_STATUS_H__
#define __AAC_STATUS_H__

#ifdef __cplusplus
extern "C" {
#endif

  typedef enum
  {
      AAC_OK = 0,
      AAC_NOT_ENOUGH_DATA,
      AAC_BAD_FORMAT,
      AAC_ALLOC,
      AAC_BAD_STREAM,
      AAC_NULL_PTR,
      AAC_NOT_FIND_SYNCWORD,
      AAC_BAD_PARAMETER,
      AAC_UNSUPPORTED
  } AACStatus;

#ifdef __cplusplus
}
#endif

#endif

{'repo_name': 'Kinoma/kinomajs', 'stars': '435', 'repo_language': 'C', 'file_name': 'ca-bundle.crt', 'mime_type': 'text/plain', 'hash': 3658969983311174332, 'source_dataset': 'data'}


#-------------------------------------------------------------------------
#
# Makefile--
#    Makefile for storage/freespace
#
# IDENTIFICATION
#    src/backend/storage/freespace/Makefile
#
#-------------------------------------------------------------------------

subdir = src/backend/storage/freespace
top_builddir = ../../../..
include $(top_builddir)/src/Makefile.global

OBJS = \
	freespace.o \
	fsmpage.o \
	indexfsm.o

include $(top_srcdir)/src/backend/common.mk

{'repo_name': 'postgres/postgres', 'stars': '6959', 'repo_language': 'C', 'file_name': 'create_extension.sgml', 'mime_type': 'text/html', 'hash': -8776937008629303172, 'source_dataset': 'data'}


import React from "react";

import PropTypes from "prop-types";

import { Card, CardHeader } from "@material-ui/core";

function UserCard(props) {
  const user = props.user;

  return (
    <Card>
      <CardHeader
        title={`${user.firstName} ${user.lastName}`}
        subheader={user.username}
      />
    </Card>
  );
}

UserCard.propTypes = {
  user: PropTypes.object.isRequired,
};

export default UserCard;

{'repo_name': 'rmuif/web', 'stars': '471', 'repo_language': 'JavaScript', 'file_name': 'index.html', 'mime_type': 'text/html', 'hash': -5525575000020853482, 'source_dataset': 'data'}


package servers

// ExtractTags will extract the tags of a server.
// This requires the client to be set to microversion 2.26 or later.
func (r serverResult) ExtractTags() ([]string, error) {
	var s struct {
		Tags []string `json:"tags"`
	}
	err := r.ExtractInto(&s)
	return s.Tags, err
}

{'repo_name': 'terraform-providers/terraform-provider-oci', 'stars': '349', 'repo_language': 'Go', 'file_name': 'identity_auth_token_resource.go', 'mime_type': 'text/plain', 'hash': 7560573277059475845, 'source_dataset': 'data'}


import os
import numpy as np

on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd:
    from .superstrings import *

def array(ar):
    if isinstance(ar, (tuple, list)):
        ar = np.asarray(ar)
    if isinstance(ar, np.ndarray):
        return StringArray(ar.astype('O'))
    elif isinstance(ar, (StringList32, StringList64)):
        return ar
    else:
        raise ValueError('Cannot convert %r to a string array' % ar)

{'repo_name': 'vaexio/vaex', 'stars': '4603', 'repo_language': 'Python', 'file_name': 'requirements.txt', 'mime_type': 'text/plain', 'hash': -5773444057743769624, 'source_dataset': 'data'}


<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */

/** Zend_Search_Lucene_Search_Weight */
#require_once 'Zend/Search/Lucene/Search/Weight.php';

/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_Weight_Boolean extends Zend_Search_Lucene_Search_Weight
{
    /**
     * IndexReader.
     *
     * @var Zend_Search_Lucene_Interface
     */
    private $_reader;

    /**
     * The query that this concerns.
     *
     * @var Zend_Search_Lucene_Search_Query
     */
    private $_query;

    /**
     * Queries weights
     * Array of Zend_Search_Lucene_Search_Weight
     *
     * @var array
     */
    private $_weights;

    /**
     * Zend_Search_Lucene_Search_Weight_Boolean constructor
     * query - the query that this concerns.
     * reader - index reader
     *
     * @param Zend_Search_Lucene_Search_Query $query
     * @param Zend_Search_Lucene_Interface    $reader
     */
    public function __construct(Zend_Search_Lucene_Search_Query $query,
                                Zend_Search_Lucene_Interface    $reader)
    {
        $this->_query   = $query;
        $this->_reader  = $reader;
        $this->_weights = array();

        $signs = $query->getSigns();

        foreach ($query->getSubqueries() as $num => $subquery) {
            if ($signs === null || $signs[$num] === null || $signs[$num]) {
                $this->_weights[$num] = $subquery->createWeight($reader);
            }
        }
    }

    /**
     * The weight for this query
     * Standard Weight::$_value is not used for boolean queries
     *
     * @return float
     */
    public function getValue()
    {
        return $this->_query->getBoost();
    }

    /**
     * The sum of squared weights of contained query clauses.
     *
     * @return float
     */
    public function sumOfSquaredWeights()
    {
        $sum = 0;
        foreach ($this->_weights as $weight) {
            // sum sub weights
            $sum += $weight->sumOfSquaredWeights();
        }

        // boost each sub-weight
        $sum *= $this->_query->getBoost() * $this->_query->getBoost();

        // check for empty query (like '-something -another')
        if ($sum == 0) {
            $sum = 1.0;
        }
        return $sum;
    }

    /**
     * Assigns the query normalization factor to this.
     *
     * @param float $queryNorm
     */
    public function normalize($queryNorm)
    {
        // incorporate boost
        $queryNorm *= $this->_query->getBoost();

        foreach ($this->_weights as $weight) {
            $weight->normalize($queryNorm);
        }
    }
}

{'repo_name': 'OpenMage/magento-lts', 'stars': '496', 'repo_language': 'PHP', 'file_name': 'iestyles.css', 'mime_type': 'text/plain', 'hash': -6812472474086598721, 'source_dataset': 'data'}


<!doctype html><meta charset="utf-8"><title>Storybook</title><meta name="viewport" content="width=device-width,initial-scale=1">

{'repo_name': 'jxom/react-loads', 'stars': '258', 'repo_language': 'TypeScript', 'file_name': 'config.js', 'mime_type': 'text/x-java', 'hash': -3780297240983072543, 'source_dataset': 'data'}


// -*- C++ -*-
//
// Package:     HcalTestBeam
// Class  :     HcalTB06Analysis
//
// Implementation:
//     Main analysis class for Hcal Test Beam 2006 Analysis
//
// Original Author:
//         Created:  19 November 2015
//

// user include files
#include "HcalTB06Histo.h"
#include "HcalTB06BeamSD.h"

// to retreive hits
#include "DataFormats/HcalDetId/interface/HcalSubdetector.h"
#include "DataFormats/EcalDetId/interface/EBDetId.h"
#include "DataFormats/HcalDetId/interface/HcalDetId.h"
#include "DataFormats/Common/interface/Handle.h"

#include "SimG4CMS/Calo/interface/CaloG4Hit.h"
#include "SimG4CMS/Calo/interface/CaloG4HitCollection.h"

#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/PluginManager/interface/ModuleDef.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/one/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/Run.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"

#include "CommonTools/UtilAlgos/interface/TFileService.h"

#include "SimDataFormats/HcalTestBeam/interface/HcalTestBeamNumbering.h"
#include "SimDataFormats/CaloHit/interface/PCaloHitContainer.h"

#include "CLHEP/Units/GlobalSystemOfUnits.h"
#include "CLHEP/Units/GlobalPhysicalConstants.h"
#include "globals.hh"
#include "Randomize.hh"

// system include files
#include <iostream>
#include <iomanip>
#include <memory>
#include <vector>
#include <string>

//#define EDM_ML_DEBUG

class HcalTB06Analysis : public edm::one::EDAnalyzer<edm::one::SharedResources> {
public:
  explicit HcalTB06Analysis(const edm::ParameterSet& p);
  ~HcalTB06Analysis() override;

  void beginJob() override;
  void endJob() override;
  void analyze(const edm::Event& e, const edm::EventSetup& c) override;

  HcalTB06Analysis(const HcalTB06Analysis&) = delete;
  const HcalTB06Analysis& operator=(const HcalTB06Analysis&) = delete;

private:
  edm::EDGetTokenT<edm::PCaloHitContainer> m_EcalToken;
  edm::EDGetTokenT<edm::PCaloHitContainer> m_HcalToken;
  edm::EDGetTokenT<edm::PCaloHitContainer> m_BeamToken;
  bool m_ECAL;

  int count;
  int m_idxetaEcal;
  int m_idxphiEcal;
  int m_idxetaHcal;
  int m_idxphiHcal;

  double m_eta;
  double m_phi;
  double m_ener;
  double m_timeLimit;
  double m_widthEcal;
  double m_widthHcal;
  double m_factEcal;
  double m_factHcal;
  std::vector<int> m_PDG;

  HcalTB06Histo* m_histo;
};

HcalTB06Analysis::HcalTB06Analysis(const edm::ParameterSet& p) : count(0) {
  usesResource("TFileService");

  m_ECAL = p.getParameter<bool>("ECAL");
  if (m_ECAL) {
    m_EcalToken = consumes<edm::PCaloHitContainer>(edm::InputTag("g4SimHits", "EcalHitsEB"));
  }
  m_HcalToken = consumes<edm::PCaloHitContainer>(edm::InputTag("g4SimHits", "HcalHits"));
  m_BeamToken = consumes<edm::PCaloHitContainer>(edm::InputTag("g4SimHits", "HcalTB06BeamHits"));
  m_eta = p.getParameter<double>("MinEta");
  m_phi = p.getParameter<double>("MinPhi");
  m_ener = p.getParameter<double>("MinE");
  m_PDG = p.getParameter<std::vector<int> >("PartID");

  double minEta = p.getParameter<double>("MinEta");
  double maxEta = p.getParameter<double>("MaxEta");
  double minPhi = p.getParameter<double>("MinPhi");
  double maxPhi = p.getParameter<double>("MaxPhi");
  double beamEta = (maxEta + minEta) * 0.5;
  double beamPhi = (maxPhi + minPhi) * 0.5;
  if (beamPhi < 0) {
    beamPhi += twopi;
  }

  m_idxetaEcal = 13;
  m_idxphiEcal = 13;

  m_idxetaHcal = (int)(beamEta / 0.087) + 1;
  m_idxphiHcal = (int)(beamPhi / 0.087) + 6;
  if (m_idxphiHcal > 72) {
    m_idxphiHcal -= 73;
  }

  edm::ParameterSet ptb = p.getParameter<edm::ParameterSet>("TestBeamAnalysis");
  m_timeLimit = ptb.getParameter<double>("TimeLimit");
  m_widthEcal = ptb.getParameter<double>("EcalWidth");
  m_widthHcal = ptb.getParameter<double>("HcalWidth");
  m_factEcal = ptb.getParameter<double>("EcalFactor");
  m_factHcal = ptb.getParameter<double>("HcalFactor");
  double eMIP = ptb.getParameter<double>("MIP");

  edm::LogInfo("HcalTB06Analysis") << "Beam parameters: E(GeV)= " << m_ener << " pdgID= " << m_PDG[0]
                                   << "\n eta= " << m_eta << "  idx_etaEcal= " << m_idxetaEcal
                                   << "  idx_etaHcal= " << m_idxetaHcal << "  phi= " << m_phi
                                   << "  idx_phiEcal= " << m_idxphiEcal << "  idx_phiHcal= " << m_idxphiHcal
                                   << "\n        EcalFactor= " << m_factEcal << "  EcalWidth= " << m_widthEcal << " GeV"
                                   << "\n        HcalFactor= " << m_factHcal << "  HcalWidth= " << m_widthHcal << " GeV"
                                   << "  MIP=       " << eMIP << " GeV"
                                   << "\n        TimeLimit=  " << m_timeLimit << " ns"
                                   << "\n";
  m_histo = new HcalTB06Histo(ptb);
}

HcalTB06Analysis::~HcalTB06Analysis() { delete m_histo; }

void HcalTB06Analysis::beginJob() { edm::LogInfo("HcalTB06Analysis") << " =====> Begin of Run"; }

void HcalTB06Analysis::endJob() {
  edm::LogInfo("HcalTB06Analysis") << " =====> End of Run; Total number of events: " << count;
}

void HcalTB06Analysis::analyze(const edm::Event& evt, const edm::EventSetup&) {
  ++count;

  //Beam Information
  m_histo->fillPrimary(m_ener, m_eta, m_phi);

  edm::Handle<edm::PCaloHitContainer> Ecal;
  edm::Handle<edm::PCaloHitContainer> Hcal;
  edm::Handle<edm::PCaloHitContainer> Beam;
  std::vector<double> eCalo(6, 0), eTrig(7, 0);

  const std::vector<PCaloHit>* EcalHits = nullptr;
  if (m_ECAL) {
    evt.getByToken(m_EcalToken, Ecal);
    EcalHits = Ecal.product();
  }
  evt.getByToken(m_HcalToken, Hcal);
  const std::vector<PCaloHit>* HcalHits = Hcal.product();
  evt.getByToken(m_BeamToken, Beam);
  const std::vector<PCaloHit>* BeamHits = Beam.product();

  // Total Energy
  double eecals = 0.;
  double ehcals = 0.;

  unsigned int ne = 0;
  unsigned int nh = 0;
  if (m_ECAL) {
    ne = EcalHits->size();
    for (unsigned int i = 0; i < ne; ++i) {
      EBDetId ecalid((*EcalHits)[i].id());
#ifdef EDM_ML_DEBUG
      std::cout << "EB " << i << " " << ecalid.ieta() << ":" << m_idxetaEcal << "   " << ecalid.iphi() << ":"
                << m_idxphiEcal << "   " << (*EcalHits)[i].time() << ":" << m_timeLimit << "   "
                << (*EcalHits)[i].energy() << std::endl;
#endif
      // 7x7 crystal selection
      if (std::abs(m_idxetaEcal - ecalid.ieta()) <= 3 && std::abs(m_idxphiEcal - ecalid.iphi()) <= 3 &&
          (*EcalHits)[i].time() < m_timeLimit) {
        eCalo[0] += (*EcalHits)[i].energy();
      }
    }
    if (m_widthEcal > 0.0) {
      eCalo[1] = G4RandGauss::shoot(0.0, m_widthEcal);
    }
    eecals = m_factEcal * (eCalo[0] + eCalo[1]);
  }
  if (HcalHits) {
    nh = HcalHits->size();
    for (unsigned int i = 0; i < nh; ++i) {
      HcalDetId hcalid((*HcalHits)[i].id());
#ifdef EDM_ML_DEBUG
      std::cout << "HC " << i << " " << hcalid.subdet() << "  " << hcalid.ieta() << ":" << m_idxetaHcal << "   "
                << hcalid.iphi() << ":" << m_idxphiHcal << "   " << (*HcalHits)[i].time() << ":" << m_timeLimit << "   "
                << (*HcalHits)[i].energy() << std::endl;
#endif
      // 3x3 towers selection
      if (std::abs(m_idxetaHcal - hcalid.ieta()) <= 1 && std::abs(m_idxphiHcal - hcalid.iphi()) <= 1 &&
          (*HcalHits)[i].time() < m_timeLimit) {
        if (hcalid.subdet() != HcalOuter) {
          eCalo[2] += (*HcalHits)[i].energy();
        } else {
          eCalo[4] += (*HcalHits)[i].energy();
        }
      }
    }
    if (m_widthHcal > 0.0) {
      eCalo[3] = G4RandGauss::shoot(0.0, m_widthHcal);
      eCalo[5] = G4RandGauss::shoot(0.0, m_widthHcal);
    }
    ehcals = m_factHcal * eCalo[2] + eCalo[3];
  }
  double etots = eecals + ehcals;

  edm::LogInfo("HcalTBSim") << "HcalTB06Analysis:: Etot(MeV)= " << etots << "   E(Ecal)= " << eecals
                            << "   E(Hcal)= " << ehcals << "  Nhits(ECAL)= " << ne << "  Nhits(HCAL)= " << nh;
  m_histo->fillEdep(etots, eecals, ehcals);

  if (BeamHits) {
    for (unsigned int i = 0; i < BeamHits->size(); ++i) {
      unsigned int id = ((*BeamHits)[i].id());
      int det, lay, ix, iy;
      HcalTestBeamNumbering::unpackIndex(id, det, lay, ix, iy);
      if ((det == 1) && ((*BeamHits)[i].time() < m_timeLimit)) {
        if (lay > 0 && lay <= 4) {
          eTrig[lay - 1] += (*BeamHits)[i].energy();
        } else if (lay == 7 || lay == 8) {
          eTrig[lay - 2] += (*BeamHits)[i].energy();
        } else if (lay >= 11 && lay <= 14) {
          eTrig[4] += (*BeamHits)[i].energy();
        }
      }
    }
  }

  edm::LogInfo("HcalTBSim") << "HcalTB06Analysis:: Trigger Info: " << eTrig[0] << ":" << eTrig[1] << ":" << eTrig[2]
                            << ":" << eTrig[3] << ":" << eTrig[4] << ":" << eTrig[5] << ":" << eTrig[6];

  m_histo->fillTree(eCalo, eTrig);
}

#include "FWCore/PluginManager/interface/ModuleDef.h"

DEFINE_FWK_MODULE(HcalTB06Analysis);

{'repo_name': 'cms-sw/cmssw', 'stars': '741', 'repo_language': 'C++', 'file_name': 'HcalRecHitsValidation.cc', 'mime_type': 'text/x-c', 'hash': 7193176714902266735, 'source_dataset': 'data'}


/*
 * Copyright (c) 2015, Intel Corporation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors
 * may be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "ble_service.h"

#include <errno.h>
#include <string.h>
//#include <atomic.h>
//#include "util/assert.h"

#include "ble_service_int.h"
#include "ble_service_internal.h"
#include "cfw/cfw_service.h"
#include "cfw/cfw_client.h"

#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>

#include "ble_protocol.h"
#include "ble_service_utils.h"

int ble_service_enable(cfw_service_conn_t * p_service_conn, uint8_t enable,
			const struct ble_enable_config * p_config,
			void *p_priv)
{
	struct ble_enable_req * msg =
			(void *) cfw_alloc_message_for_service(p_service_conn,
				    MSG_ID_BLE_ENABLE_REQ,
				    sizeof(*msg), p_priv);
	msg->central_conn_params = p_config->central_conn_params;
	msg->enable = enable;

	if (p_config->p_bda) {
		msg->bda_present = 1;
		msg->bda = *p_config->p_bda;
	}

	return cfw_send_message(msg);
}

{'repo_name': 'arduino/ArduinoCore-arc32', 'stars': '292', 'repo_language': 'C', 'file_name': 'dccm_alloc.h', 'mime_type': 'text/x-c', 'hash': -3878721343376360975, 'source_dataset': 'data'}


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
  serializedVersion: 6
  m_ObjectHideFlags: 0
  m_CorrespondingSourceObject: {fileID: 0}
  m_PrefabInternal: {fileID: 0}
  m_Name: fontSLG_GridUnitInfo
  m_Shader: {fileID: 4800000, guid: 68e6db2ebdc24f95958faec2be5558d6, type: 3}
  m_ShaderKeywords:
  m_LightmapFlags: 4
  m_EnableInstancingVariants: 0
  m_DoubleSidedGI: 0
  m_CustomRenderQueue: -1
  stringTagMap: {}
  disabledShaderPasses: []
  m_SavedProperties:
    serializedVersion: 3
    m_TexEnvs:
    - _BumpMap:
        m_Texture: {fileID: 0}
        m_Scale: {x: 1, y: 1}
        m_Offset: {x: 0, y: 0}
    - _Cube:
        m_Texture: {fileID: 0}
        m_Scale: {x: 1, y: 1}
        m_Offset: {x: 0, y: 0}
    - _FaceTex:
        m_Texture: {fileID: 0}
        m_Scale: {x: 1, y: 1}
        m_Offset: {x: 0, y: 0}
    - _MainTex:
        m_Texture: {fileID: 28258557981044922, guid: 33050ba69b1afa74dac1c27e69d95dde,
          type: 2}
        m_Scale: {x: 1, y: 1}
        m_Offset: {x: 0, y: 0}
    - _OutlineTex:
        m_Texture: {fileID: 0}
        m_Scale: {x: 1, y: 1}
        m_Offset: {x: 0, y: 0}
    m_Floats:
    - _Ambient: 0.5
    - _Bevel: 0.5
    - _BevelClamp: 0
    - _BevelOffset: 0
    - _BevelRoundness: 0
    - _BevelWidth: 0
    - _BumpFace: 0
    - _BumpOutline: 0
    - _ColorMask: 15
    - _Diffuse: 0.5
    - _FaceDilate: 0
    - _FaceUVSpeedX: 0
    - _FaceUVSpeedY: 0
    - _GlowInner: 0.05
    - _GlowOffset: 0
    - _GlowOuter: 0.05
    - _GlowPower: 0.75
    - _GradientScale: 6
    - _LightAngle: 3.1416
    - _MaskSoftnessX: 0
    - _MaskSoftnessY: 0
    - _OutlineSoftness: 0
    - _OutlineUVSpeedX: 0
    - _OutlineUVSpeedY: 0
    - _OutlineWidth: 0
    - _PerspectiveFilter: 0.875
    - _Reflectivity: 10
    - _ScaleRatioA: 0.8333333
    - _ScaleRatioB: 0.6770833
    - _ScaleRatioC: 0.6770833
    - _ScaleX: 1
    - _ScaleY: 1
    - _ShaderFlags: 0
    - _SpecularPower: 2
    - _Stencil: 0
    - _StencilComp: 8
    - _StencilOp: 0
    - _StencilReadMask: 255
    - _StencilWriteMask: 255
    - _TextureHeight: 512
    - _TextureWidth: 512
    - _UnderlayDilate: 0
    - _UnderlayOffsetX: 0
    - _UnderlayOffsetY: 0
    - _UnderlaySoftness: 0
    - _VertexOffsetX: 0
    - _VertexOffsetY: 0
    - _WeightBold: 0.75
    - _WeightNormal: 0
    m_Colors:
    - _ClipRect: {r: -32767, g: -32767, b: 32767, a: 32767}
    - _EnvMatrixRotation: {r: 0, g: 0, b: 0, a: 0}
    - _FaceColor: {r: 1, g: 1, b: 1, a: 1}
    - _GlowColor: {r: 0, g: 1, b: 0, a: 0.5}
    - _MaskCoord: {r: 0, g: 0, b: 32767, a: 32767}
    - _OutlineColor: {r: 1, g: 1, b: 1, a: 1}
    - _ReflectFaceColor: {r: 0, g: 0, b: 0, a: 1}
    - _ReflectOutlineColor: {r: 0, g: 0, b: 0, a: 1}
    - _SpecularColor: {r: 1, g: 1, b: 1, a: 1}
    - _UnderlayColor: {r: 0, g: 0, b: 0, a: 0.5}

{'repo_name': 'elsong823/HalfSLG', 'stars': '161', 'repo_language': 'C#', 'file_name': 'AudioManager.asset', 'mime_type': 'text/plain', 'hash': 2181147982890308856, 'source_dataset': 'data'}


.. _quickref:

Quick reference for the ESP8266
===============================

.. image:: img/adafruit_products_pinoutstop.jpg
    :alt: Adafruit Feather HUZZAH board
    :width: 640px

The Adafruit Feather HUZZAH board (image attribution: Adafruit).

Installing MicroPython
----------------------

See the corresponding section of tutorial: :ref:`intro`. It also includes
a troubleshooting subsection.

General board control
---------------------

The MicroPython REPL is on UART0 (GPIO1=TX, GPIO3=RX) at baudrate 115200.
Tab-completion is useful to find out what methods an object has.
Paste mode (ctrl-E) is useful to paste a large slab of Python code into
the REPL.

The :mod:`machine` module::

    import machine

    machine.freq()          # get the current frequency of the CPU
    machine.freq(160000000) # set the CPU frequency to 160 MHz

The :mod:`esp` module::

    import esp

    esp.osdebug(None)       # turn off vendor O/S debugging messages
    esp.osdebug(0)          # redirect vendor O/S debugging messages to UART(0)

Networking
----------

The :mod:`network` module::

    import network

    wlan = network.WLAN(network.STA_IF) # create station interface
    wlan.active(True)       # activate the interface
    wlan.scan()             # scan for access points
    wlan.isconnected()      # check if the station is connected to an AP
    wlan.connect('essid', 'password') # connect to an AP
    wlan.config('mac')      # get the interface's MAC adddress
    wlan.ifconfig()         # get the interface's IP/netmask/gw/DNS addresses

    ap = network.WLAN(network.AP_IF) # create access-point interface
    ap.active(True)         # activate the interface
    ap.config(essid='ESP-AP') # set the ESSID of the access point

A useful function for connecting to your local WiFi network is::

    def do_connect():
        import network
        wlan = network.WLAN(network.STA_IF)
        wlan.active(True)
        if not wlan.isconnected():
            print('connecting to network...')
            wlan.connect('essid', 'password')
            while not wlan.isconnected():
                pass
        print('network config:', wlan.ifconfig())

Once the network is established the :mod:`socket <usocket>` module can be used
to create and use TCP/UDP sockets as usual.

Delay and timing
----------------

Use the :mod:`time <utime>` module::

    import time

    time.sleep(1)           # sleep for 1 second
    time.sleep_ms(500)      # sleep for 500 milliseconds
    time.sleep_us(10)       # sleep for 10 microseconds
    start = time.ticks_ms() # get millisecond counter
    delta = time.ticks_diff(time.ticks_ms(), start) # compute time difference

Timers
------

Virtual (RTOS-based) timers are supported. Use the :ref:`machine.Timer <machine.Timer>` class
with timer ID of -1::

    from machine import Timer

    tim = Timer(-1)
    tim.init(period=5000, mode=Timer.ONE_SHOT, callback=lambda t:print(1))
    tim.init(period=2000, mode=Timer.PERIODIC, callback=lambda t:print(2))

The period is in milliseconds.

Pins and GPIO
-------------

Use the :ref:`machine.Pin <machine.Pin>` class::

    from machine import Pin

    p0 = Pin(0, Pin.OUT)    # create output pin on GPIO0
    p0.on()                 # set pin to "on" (high) level
    p0.off()                # set pin to "off" (low) level
    p0.value(1)             # set pin to on/high

    p2 = Pin(2, Pin.IN)     # create input pin on GPIO2
    print(p2.value())       # get value, 0 or 1

    p4 = Pin(4, Pin.IN, Pin.PULL_UP) # enable internal pull-up resistor
    p5 = Pin(5, Pin.OUT, value=1) # set pin high on creation

Available pins are: 0, 1, 2, 3, 4, 5, 12, 13, 14, 15, 16, which correspond
to the actual GPIO pin numbers of ESP8266 chip. Note that many end-user
boards use their own adhoc pin numbering (marked e.g. D0, D1, ...). As
MicroPython supports different boards and modules, physical pin numbering
was chosen as the lowest common denominator. For mapping between board
logical pins and physical chip pins, consult your board documentation.

Note that Pin(1) and Pin(3) are REPL UART TX and RX respectively.
Also note that Pin(16) is a special pin (used for wakeup from deepsleep
mode) and may be not available for use with higher-level classes like
``Neopixel``.

PWM (pulse width modulation)
----------------------------

PWM can be enabled on all pins except Pin(16).  There is a single frequency
for all channels, with range between 1 and 1000 (measured in Hz).  The duty
cycle is between 0 and 1023 inclusive.

Use the ``machine.PWM`` class::

    from machine import Pin, PWM

    pwm0 = PWM(Pin(0))      # create PWM object from a pin
    pwm0.freq()             # get current frequency
    pwm0.freq(1000)         # set frequency
    pwm0.duty()             # get current duty cycle
    pwm0.duty(200)          # set duty cycle
    pwm0.deinit()           # turn off PWM on the pin

    pwm2 = PWM(Pin(2), freq=500, duty=512) # create and configure in one go

ADC (analog to digital conversion)
----------------------------------

ADC is available on a dedicated pin.
Note that input voltages on the ADC pin must be between 0v and 1.0v.

Use the :ref:`machine.ADC <machine.ADC>` class::

    from machine import ADC

    adc = ADC(0)            # create ADC object on ADC pin
    adc.read()              # read value, 0-1024

Software SPI bus
----------------

There are two SPI drivers. One is implemented in software (bit-banging)
and works on all pins, and is accessed via the :ref:`machine.SPI <machine.SPI>`
class::

    from machine import Pin, SPI

    # construct an SPI bus on the given pins
    # polarity is the idle state of SCK
    # phase=0 means sample on the first edge of SCK, phase=1 means the second
    spi = SPI(-1, baudrate=100000, polarity=1, phase=0, sck=Pin(0), mosi=Pin(2), miso=Pin(4))

    spi.init(baudrate=200000) # set the baudrate

    spi.read(10)            # read 10 bytes on MISO
    spi.read(10, 0xff)      # read 10 bytes while outputing 0xff on MOSI

    buf = bytearray(50)     # create a buffer
    spi.readinto(buf)       # read into the given buffer (reads 50 bytes in this case)
    spi.readinto(buf, 0xff) # read into the given buffer and output 0xff on MOSI

    spi.write(b'12345')     # write 5 bytes on MOSI

    buf = bytearray(4)      # create a buffer
    spi.write_readinto(b'1234', buf) # write to MOSI and read from MISO into the buffer
    spi.write_readinto(buf, buf) # write buf to MOSI and read MISO back into buf

Hardware SPI bus
----------------

The hardware SPI is faster (up to 80Mhz), but only works on following pins:
``MISO`` is GPIO12, ``MOSI`` is GPIO13, and ``SCK`` is GPIO14. It has the same
methods as the bitbanging SPI class above, except for the pin parameters for the
constructor and init (as those are fixed)::

    from machine import Pin, SPI

    hspi = SPI(1, baudrate=80000000, polarity=0, phase=0)

(``SPI(0)`` is used for FlashROM and not available to users.)

I2C bus
-------

The I2C driver is implemented in software and works on all pins,
and is accessed via the :ref:`machine.I2C <machine.I2C>` class::

    from machine import Pin, I2C

    # construct an I2C bus
    i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000)

    i2c.readfrom(0x3a, 4)   # read 4 bytes from slave device with address 0x3a
    i2c.writeto(0x3a, '12') # write '12' to slave device with address 0x3a

    buf = bytearray(10)     # create a buffer with 10 bytes
    i2c.writeto(0x3a, buf)  # write the given buffer to the slave

Real time clock (RTC)
---------------------

See :ref:`machine.RTC <machine.RTC>` ::

    from machine import RTC

    rtc = RTC()
    rtc.datetime((2017, 8, 23, 1, 12, 48, 0, 0)) # set a specific date and time
    rtc.datetime() # get date and time

Deep-sleep mode
---------------

Connect GPIO16 to the reset pin (RST on HUZZAH).  Then the following code
can be used to sleep, wake and check the reset cause::

    import machine

    # configure RTC.ALARM0 to be able to wake the device
    rtc = machine.RTC()
    rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)

    # check if the device woke from a deep sleep
    if machine.reset_cause() == machine.DEEPSLEEP_RESET:
        print('woke from a deep sleep')

    # set RTC.ALARM0 to fire after 10 seconds (waking the device)
    rtc.alarm(rtc.ALARM0, 10000)

    # put the device to sleep
    machine.deepsleep()

OneWire driver
--------------

The OneWire driver is implemented in software and works on all pins::

    from machine import Pin
    import onewire

    ow = onewire.OneWire(Pin(12)) # create a OneWire bus on GPIO12
    ow.scan()               # return a list of devices on the bus
    ow.reset()              # reset the bus
    ow.readbyte()           # read a byte
    ow.writebyte(0x12)      # write a byte on the bus
    ow.write('123')         # write bytes on the bus
    ow.select_rom(b'12345678') # select a specific device by its ROM code

There is a specific driver for DS18S20 and DS18B20 devices::

    import time, ds18x20
    ds = ds18x20.DS18X20(ow)
    roms = ds.scan()
    ds.convert_temp()
    time.sleep_ms(750)
    for rom in roms:
        print(ds.read_temp(rom))

Be sure to put a 4.7k pull-up resistor on the data line.  Note that
the ``convert_temp()`` method must be called each time you want to
sample the temperature.

NeoPixel driver
---------------

Use the ``neopixel`` module::

    from machine import Pin
    from neopixel import NeoPixel

    pin = Pin(0, Pin.OUT)   # set GPIO0 to output to drive NeoPixels
    np = NeoPixel(pin, 8)   # create NeoPixel driver on GPIO0 for 8 pixels
    np[0] = (255, 255, 255) # set the first pixel to white
    np.write()              # write data to all pixels
    r, g, b = np[0]         # get first pixel colour

For low-level driving of a NeoPixel::

    import esp
    esp.neopixel_write(pin, grb_buf, is800khz)

APA102 driver
-------------

Use the ``apa102`` module::

    from machine import Pin
    from apa102 import APA102

    clock = Pin(14, Pin.OUT)     # set GPIO14 to output to drive the clock
    data = Pin(13, Pin.OUT)      # set GPIO13 to output to drive the data
    apa = APA102(clock, data, 8) # create APA102 driver on the clock and the data pin for 8 pixels
    apa[0] = (255, 255, 255, 31) # set the first pixel to white with a maximum brightness of 31
    apa.write()                  # write data to all pixels
    r, g, b, brightness = apa[0] # get first pixel colour

For low-level driving of an APA102::

    import esp
    esp.apa102_write(clock_pin, data_pin, rgbi_buf)

DHT driver
----------

The DHT driver is implemented in software and works on all pins::

    import dht
    import machine

    d = dht.DHT11(machine.Pin(4))
    d.measure()
    d.temperature() # eg. 23 (°C)
    d.humidity()    # eg. 41 (% RH)

    d = dht.DHT22(machine.Pin(4))
    d.measure()
    d.temperature() # eg. 23.6 (°C)
    d.humidity()    # eg. 41.3 (% RH)

WebREPL (web browser interactive prompt)
----------------------------------------

WebREPL (REPL over WebSockets, accessible via a web browser) is an
experimental feature available in ESP8266 port. Download web client
from https://github.com/micropython/webrepl (hosted version available
at http://micropython.org/webrepl), and configure it by executing::

    import webrepl_setup

and following on-screen instructions. After reboot, it will be available
for connection. If you disabled automatic start-up on boot, you may
run configured daemon on demand using::

    import webrepl
    webrepl.start()

The supported way to use WebREPL is by connecting to ESP8266 access point,
but the daemon is also started on STA interface if it is active, so if your
router is set up and works correctly, you may also use WebREPL while connected
to your normal Internet access point (use the ESP8266 AP connection method
if you face any issues).

Besides terminal/command prompt access, WebREPL also has provision for file
transfer (both upload and download). Web client has buttons for the
corresponding functions, or you can use command-line client ``webrepl_cli.py``
from the repository above.

See the MicroPython forum for other community-supported alternatives
to transfer files to ESP8266.

{'repo_name': 'micropython/micropython-esp32', 'stars': '550', 'repo_language': 'C', 'file_name': 'perf.h', 'mime_type': 'text/x-c', 'hash': 5213913882804842558, 'source_dataset': 'data'}


---
-api-id: M:Windows.ApplicationModel.Store.Preview.StoreConfiguration.FilterUnsupportedSystemFeaturesAsync(Windows.Foundation.Collections.IIterable{Windows.ApplicationModel.Store.Preview.StoreSystemFeature})
-api-type: winrt method
---

<!-- Method syntax
public Windows.Foundation.IAsyncOperation<Windows.Foundation.Collections.IVectorView<Windows.ApplicationModel.Store.Preview.StoreSystemFeature>> FilterUnsupportedSystemFeaturesAsync(Windows.Foundation.Collections.IIterable<Windows.ApplicationModel.Store.Preview.StoreSystemFeature> systemFeatures)
-->

# Windows.ApplicationModel.Store.Preview.StoreConfiguration.FilterUnsupportedSystemFeaturesAsync

## -description
Given a list of hardware features, this method returns a modified list that contains only the hardware features that are supported on the current device.

## -parameters
### -param systemFeatures
A list of [StoreSystemFeature](storesystemfeature.md) objects that represent the hardware features to be queried on the current device.

## -returns
An asynchronous operation that, on successful completion, returns a list of hardware features that are supported on the current device. If you use [Asynchronous programming](/windows/uwp/threading-async/asynchronous-programming-universal-windows-platform-apps), the result type is a read-only list/vector of [StoreSystemFeature](storesystemfeature.md) items. (You can use APIs of [IVectorView<StoreSystemFeature>](../windows.foundation.collections/ivectorview_1.md) for C++ or JavaScript, APIs of [IReadOnlyList<StoreSystemFeature>](/dotnet/api/system.collections.generic.ireadonlylist-1?redirectedfrom=MSDN) for .NET.)

## -remarks

## -examples

## -see-also

{'repo_name': 'MicrosoftDocs/winrt-api', 'stars': '106', 'repo_language': 'JavaScript', 'file_name': 'AssemblyInfo.cs', 'mime_type': 'text/plain', 'hash': 6922021402926376226, 'source_dataset': 'data'}


/**
 * @brief ESC status plugin
 * @file esc_status.cpp
 * @author Ricardo Marques <marques.ricardo17@gmail.com>
 *
 * @addtogroup plugin
 * @{
 */
/*
 * Copyright 2020 Ricardo Marques <marques.ricardo17@gmail.com>.
 *
 * This file is part of the mavros package and subject to the license terms
 * in the top-level LICENSE file of the mavros repository.
 * https://github.com/mavlink/mavros/tree/master/LICENSE.md
 */

#include <mavros/mavros_plugin.h>
#include <mavros_msgs/ESCInfo.h>
#include <mavros_msgs/ESCStatus.h>

namespace mavros
{
namespace extra_plugins
{
/**
 * @brief ESC status plugin
 */
class ESCStatusPlugin : public plugin::PluginBase
{
public:
	ESCStatusPlugin() : PluginBase(),
		_max_esc_count(0),
		_max_esc_info_index(0),
		_max_esc_status_index(0),
		nh("~")
	{}

	void initialize(UAS &uas_)
	{
		PluginBase::initialize(uas_);

		esc_info_pub = nh.advertise<mavros_msgs::ESCInfo>("esc_info", 10);
		esc_status_pub = nh.advertise<mavros_msgs::ESCStatus>("esc_status", 10);

		enable_connection_cb();
	}

	Subscriptions get_subscriptions()
	{
		return {
			       make_handler(&ESCStatusPlugin::handle_esc_info),
			       make_handler(&ESCStatusPlugin::handle_esc_status),
		};
	}

private:
	using lock_guard = std::lock_guard<std::mutex>;
	std::mutex mutex;

	ros::NodeHandle nh;

	ros::Publisher esc_info_pub;
	ros::Publisher esc_status_pub;
	mavros_msgs::ESCInfo _esc_info;
	mavros_msgs::ESCStatus _esc_status;
	uint8_t _max_esc_count;
	uint8_t _max_esc_info_index;
	uint8_t _max_esc_status_index;
	const uint8_t batch_size = 4;

	void handle_esc_info(const mavlink::mavlink_message_t *msg, mavlink::common::msg::ESC_INFO &esc_info)
	{
		lock_guard lock(mutex);

		_esc_info.header.stamp = m_uas->synchronise_stamp(esc_info.time_usec);

		uint8_t esc_index = esc_info.index;

		_esc_info.counter = esc_info.counter;
		_esc_info.count = esc_info.count;
		_esc_info.connection_type = esc_info.connection_type;
		_esc_info.info = esc_info.info;

		if (_esc_info.count > _max_esc_count)
		{
			_max_esc_count = _esc_info.count;
		}

		if (_esc_info.esc_info.size() < _max_esc_count)
		{
			_esc_info.esc_info.resize(_max_esc_count);
		}

		for (int i = 0; i < std::min<ssize_t>(batch_size, ssize_t(_max_esc_count) - esc_index); i++)
		{
			_esc_info.esc_info[esc_index + i].header = _esc_info.header;
			_esc_info.esc_info[esc_index + i].failure_flags = esc_info.failure_flags[i];
			_esc_info.esc_info[esc_index + i].error_count = esc_info.error_count[i];
			_esc_info.esc_info[esc_index + i].temperature = esc_info.temperature[i];
		}

		_max_esc_info_index = std::max(_max_esc_info_index, esc_info.index);

		if (_max_esc_info_index == esc_info.index)
		{
			esc_info_pub.publish(_esc_info);
		}
	}

	void handle_esc_status(const mavlink::mavlink_message_t *msg, mavlink::common::msg::ESC_STATUS &esc_status)
	{
		lock_guard lock(mutex);

		uint8_t esc_index = esc_status.index;

		if (_esc_status.esc_status.size() < _max_esc_count)
		{
			_esc_status.esc_status.resize(_max_esc_count);
		}

		_esc_status.header.stamp = m_uas->synchronise_stamp(esc_status.time_usec);

		for (int i = 0; i < std::min<ssize_t>(batch_size, ssize_t(_max_esc_count) - esc_index); i++)
		{
			_esc_status.esc_status[esc_index + i].header = _esc_status.header;
			_esc_status.esc_status[esc_index + i].rpm = esc_status.rpm[i];
			_esc_status.esc_status[esc_index + i].voltage = esc_status.voltage[i];
			_esc_status.esc_status[esc_index + i].current = esc_status.current[i];
		}

		_max_esc_status_index = std::max(_max_esc_status_index, esc_status.index);

		if (_max_esc_status_index == esc_status.index)
		{
			esc_status_pub.publish(_esc_status);
		}
	}

	void connection_cb(bool connected) override
	{
		lock_guard lock(mutex);

		_max_esc_count = 0;
		_max_esc_status_index = 0;
		_max_esc_info_index = 0;
		_esc_info.esc_info.resize(0);
		_esc_status.esc_status.resize(0);
	}
};
}	// namespace extra_plugins
}	// namespace mavros

#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(mavros::extra_plugins::ESCStatusPlugin, mavros::plugin::PluginBase)

{'repo_name': 'mavlink/mavros', 'stars': '400', 'repo_language': 'C++', 'file_name': 'px4_config.yaml', 'mime_type': 'text/plain', 'hash': -1741018577250732660, 'source_dataset': 'data'}


<Project Sdk="MSBuild.Sdk.Extras">
  <PropertyGroup>
    <TargetFrameworks>net46;net48</TargetFrameworks>
    <UseWindowsForms>true</UseWindowsForms>
    <ExtrasEnableWinFormsProjectSetup>true</ExtrasEnableWinFormsProjectSetup>
    <OutputType>WinExe</OutputType>
    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
    <UseWindowsForms>true</UseWindowsForms>
    <AppendTargetFrameworkToOutputPath>true</AppendTargetFrameworkToOutputPath>
    <RootNamespace>GdiSvgTestBox</RootNamespace>
    <AssemblyName>GdiSvgTestBox</AssemblyName>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugType>full</DebugType>
    <DebugSymbols>true</DebugSymbols>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <OutputPath>Output\</OutputPath>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DefineConstants>TRACE</DefineConstants>
    <OutputPath>Output\</OutputPath>
  </PropertyGroup>
  <PropertyGroup>
    <ApplicationIcon>App.ico</ApplicationIcon>
    <RunAnalyzersDuringBuild>false</RunAnalyzersDuringBuild>
    <RunAnalyzersDuringLiveAnalysis>false</RunAnalyzersDuringLiveAnalysis>
  </PropertyGroup>
  <PropertyGroup>
    <DefineConstants Condition=" '$(TargetFramework)' == 'net40' ">$(DefineConstants);DOTNET40;NETFULL</DefineConstants>
    <DefineConstants Condition="$(TargetFramework.StartsWith('net45'))">$(DefineConstants);DOTNET45;NETFULL</DefineConstants>
    <DefineConstants Condition="$(TargetFramework.StartsWith('net46'))">$(DefineConstants);DOTNET46;NETFULL</DefineConstants>
    <DefineConstants Condition="$(TargetFramework.StartsWith('net47'))">$(DefineConstants);DOTNET47;NETFULL</DefineConstants>
    <DefineConstants Condition="$(TargetFramework.StartsWith('net48'))">$(DefineConstants);DOTNET48;NETFULL</DefineConstants>
    <DefineConstants Condition="$(TargetFramework.StartsWith('netcore'))">$(DefineConstants);NETCORE</DefineConstants>
    <DefineConstants Condition="$(TargetFramework.StartsWith('netstandard'))">$(DefineConstants);NETSTANDARD</DefineConstants>
  </PropertyGroup>
  <ItemGroup Condition=" '$(TargetFramework)' == 'net46'">
    <Reference Include="System.Design" />
    <Reference Include="System.IO.Compression" />
    <Reference Include="SharpVectors.ShellFileDialogs">
      <HintPath>..\..\Libraries\net46\SharpVectors.ShellFileDialogs.dll</HintPath>
    </Reference>
    <Reference Include="ICSharpCode.TextEditor">
      <HintPath>..\..\Libraries\net46\ICSharpCode.TextEditor.dll</HintPath>
    </Reference>
    <Reference Include="WeifenLuo.WinFormsUI.Docking">
      <HintPath>..\..\Libraries\net46\WeifenLuo.WinFormsUI.Docking.dll</HintPath>
    </Reference>
    <Reference Include="WeifenLuo.WinFormsUI.Docking.ThemeVS2015">
      <HintPath>..\..\Libraries\net46\WeifenLuo.WinFormsUI.Docking.ThemeVS2015.dll</HintPath>
    </Reference>
  </ItemGroup>
  <ItemGroup Condition=" '$(TargetFramework)' == 'net48'">
    <Reference Include="System.Design" />
    <Reference Include="System.IO.Compression" />
    <Reference Include="SharpVectors.ShellFileDialogs">
      <HintPath>..\..\Libraries\net48\SharpVectors.ShellFileDialogs.dll</HintPath>
    </Reference>
    <Reference Include="ICSharpCode.TextEditor">
      <HintPath>..\..\Libraries\net48\ICSharpCode.TextEditor.dll</HintPath>
    </Reference>
    <Reference Include="WeifenLuo.WinFormsUI.Docking">
      <HintPath>..\..\Libraries\net48\WeifenLuo.WinFormsUI.Docking.dll</HintPath>
    </Reference>
    <Reference Include="WeifenLuo.WinFormsUI.Docking.ThemeVS2015">
      <HintPath>..\..\Libraries\net48\WeifenLuo.WinFormsUI.Docking.ThemeVS2015.dll</HintPath>
    </Reference>
  </ItemGroup>
  <ItemGroup>
    <Compile Update="PopupMessage.cs">
      <SubType>UserControl</SubType>
    </Compile>
  </ItemGroup>
  <ItemGroup>
    <Content Include="App.ico" />
    <Content Include="Images\Debug.ico" />
    <Content Include="Images\Settings.ico" />
    <Content Include="Images\SvgLogoBasic.ico" />
    <Content Include="Images\Test.ico" />
    <Content Include="Images\TestResultDetail.ico" />
    <Content Include="Images\TestRunner.ico" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\..\Source\SharpVectorCore\SharpVectors.Core.VS2017.csproj" />
    <ProjectReference Include="..\..\Source\SharpVectorCss\SharpVectors.Css.VS2017.csproj" />
    <ProjectReference Include="..\..\Source\SharpVectorDom\SharpVectors.Dom.VS2017.csproj" />
    <ProjectReference Include="..\..\Source\SharpVectorModel\SharpVectors.Model.VS2017.csproj" />
    <ProjectReference Include="..\..\Source\SharpVectorRenderingGdi\SharpVectors.Rendering.Gdi.VS2017.csproj" />
  </ItemGroup>
  <ItemGroup>
    <Compile Update="Properties\Resources.Designer.cs">
      <AutoGen>True</AutoGen>
      <DesignTime>True</DesignTime>
      <DependentUpon>Resources.resx</DependentUpon>
    </Compile>
    <Compile Update="Properties\Settings.Designer.cs">
      <AutoGen>True</AutoGen>
      <DependentUpon>Settings.settings</DependentUpon>
      <DesignTimeSharedInput>True</DesignTimeSharedInput>
    </Compile>
    <EmbeddedResource Update="Properties\Resources.resx">
      <Generator>ResXFileCodeGenerator</Generator>
      <LastGenOutput>Resources.Designer.cs</LastGenOutput>
    </EmbeddedResource>
    <None Update="Properties\Settings.settings">
      <Generator>SettingsSingleFileGenerator</Generator>
      <LastGenOutput>Settings.Designer.cs</LastGenOutput>
    </None>
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>
</Project>

{'repo_name': 'ElinamLLC/SharpVectors', 'stars': '235', 'repo_language': 'C#', 'file_name': 'WeifenLuo.WinFormsUI.Docking.ThemeVS2015.deps.json', 'mime_type': 'text/plain', 'hash': -4877881659052037239, 'source_dataset': 'data'}


#! /bin/bash

# Copyright 2017-present Cisco Systems, Inc.

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Size of source trees, after being built on an x86_64 machine, without
# documentation:
# p4c - 1.3G
# behavioral-model - 2.0G

echo "As of August 2019, and perhaps even earlier, running the exercises in"
echo "this repository:"
echo ""
echo "    https://github.com/p4lang/tutorials"
echo ""
echo "requires installing code to enable the use of the P4Runtime API, which"
echo "this install script does _not_ install."
echo ""
echo "If you want an install script that will install enough software to"
echo "enable running the exercises in that tutorials repository, consider"
echo "using one of these scripts instead:"
echo ""
echo "+ install-p4dev-p4runtime.sh"
echo "+ install-p4dev-v2.sh - The primary difference between this and the"
echo "  previous one is that this one is more recent and a bit experimental,"
echo "  installing somewhat later versions of the Protobuf and gRPC"
echo "  libraries.  Use the previous one for now if you do not want to stick"
echo "  with older but more-tested versions."
echo ""
echo "If you understand that this install script is _not_ sufficient for"
echo "running the tutorials, and you want to use it anyway, edit the script"
echo "to delete or comment out the line 'exit 1', and run it again."

exit 1

# The maximum number of gcc/g++ jobs to run in parallel.  1 is the
# safest number that enables compiling p4c even on machines with only
# 2 GB of RAM, and even on machines with significantly more RAM, it
# does not speed things up a lot to run multiple jobs in parallel.
MAX_PARALLEL_JOBS=1

# Remember the current directory when the script was started:
INSTALL_DIR="${PWD}"

THIS_SCRIPT_FILE_MAYBE_RELATIVE="$0"
THIS_SCRIPT_DIR_MAYBE_RELATIVE="${THIS_SCRIPT_FILE_MAYBE_RELATIVE%/*}"
THIS_SCRIPT_DIR_ABSOLUTE=`readlink -f "${THIS_SCRIPT_DIR_MAYBE_RELATIVE}"`

echo "This script builds and installs the P4_16 (and also P4_14)"
echo "compiler, and the behavioral-model software packet forwarding"
echo "program, that can behave as just about any legal P4 program."
echo ""
echo "It regularly tested on freshly installed Ubuntu 16.04 and Ubuntu"
echo "18.04 systems, with all Ubuntu software updates as of the date"
echo "of testing.  See this directory for log files recording the last"
echo "date this script was tested on its supported operating systems:"
echo ""
echo "    https://github.com/jafingerhut/p4-guide/tree/master/bin/output"
echo ""
echo "The files installed by this script consume about 5 GB of disk space."
echo ""
echo "On a 2015 MacBook Pro with a decent speed Internet connection"
echo "and an SSD drive, running Ubuntu Linux in a VirtualBox VM, it"
echo "took about 40 minutes."
echo ""
echo "Versions of software that will be installed by this script:"
echo ""
echo "+ protobuf: github.com/google/protobuf v3.2.0"
echo "+ behavioral-model: github.com/p4lang/behavioral-model latest version"
echo "  which, as of 2019-Jun-10, also installs these things:"
echo "  + thrift version 0.9.2"
echo "  + nanomsg version 1.0.0"
echo "  + nnpy git checkout c7e718a5173447c85182dc45f99e2abcf9cd4065 (latest as of 2015-Apr-22"
echo "+ p4c: github.com/p4lang/p4c latest version"
echo ""
echo "Note that anything installed as 'the latest version' can change"
echo "its precise contents from one run of this script to another."
echo "That is an intentional property of this script -- to get the"
echo "latest version of that software.  If you want particular"
echo "versions that are not the latest, you can modify this script by"
echo "adding 'git checkout <tag>' and/or 'git checkout <commit-sha>'"
echo "command at the appropriate places."
echo ""

REPO_CACHE_DIR="${INSTALL_DIR}/repository-cache"
get_from_nearest() {
    local git_url="$1"
    local repo_cache_name="$2"

    if [ -e "${REPO_CACHE_DIR}/${repo_cache_name}" ]
    then
	echo "Creating contents of ${git_url} from local cached copy ${REPO_CACHE_DIR}/${repo_cache_name}"
	tar xkzf "${REPO_CACHE_DIR}/${repo_cache_name}"
    else
	echo "git clone ${git_url}"
	git clone "${git_url}"
    fi
}

echo "------------------------------------------------------------"
echo "Time and disk space used before installation begins:"
date
df -h .
df -BM .

# Install a few packages (vim is not strictly necessary -- installed for
# my own convenience):
sudo apt-get --yes install git vim

# Run a child process in the background that will keep sudo
# credentials fresh.  The hope is that after a user enters their
# password once, they will not need to do so again for the entire
# duration of running this install script.

# However, since it runs in the background, do _not_ start it until
# after the first command in this script that uses 'sudo', so the
# foreground 'sudo' command will cause the password prompt to be
# waited for, if it is needed.
"${THIS_SCRIPT_DIR_ABSOLUTE}/keep-sudo-credentials-fresh.sh" &
CHILD_PROCESS_PID=$!

clean_up() {
    echo "Killing child process"
    kill ${CHILD_PROCESS_PID}
    # Invalidate the user's cached credentials
    sudo --reset-timestamp
    exit
}

# Kill the child process
trap clean_up SIGHUP SIGINT SIGTERM

# Install Python2.  This is required for p4c, but there are several
# earlier packages that check for python in their configure scripts,
# and on a minimal Ubuntu 18.04 Desktop Linux system they find
# Python3, not Python2, unless we install Python2.  Most Python code
# in open source P4 projects is written for Python2.
sudo apt-get --yes install python

# Install Ubuntu packages needed by protobuf v3.2.0, from its src/README.md
sudo apt-get --yes install autoconf automake libtool curl make g++ unzip
# zlib is not required to install protobuf, nor do I think it is
# required by the open source P4 tools for protobuf to be built with
# support for zlib, but it seems like a reasonable thing to enable.
sudo apt-get --yes install zlib1g-dev
# Install Ubuntu dependencies needed by p4c, from its README.md
# Matches latest p4c README.md instructions as of 2019-Oct-09
sudo apt-get --yes install cmake g++ git automake libtool libgc-dev bison flex libfl-dev libgmp-dev libboost-dev libboost-iostreams-dev libboost-graph-dev llvm pkg-config python python-scapy python-ipaddr python-ply python3-pip tcpdump
# Starting in 2019-Nov, Python3 version of Scapy is needed for `cd
# p4c/build ; make check` to succeed.
pip3 install scapy

echo "------------------------------------------------------------"
echo "Installing Google protobuf, needed for p4lang/p4c"
echo "start install protobuf:"
date

cd "${INSTALL_DIR}"
get_from_nearest https://github.com/google/protobuf protobuf.tar.gz
cd protobuf
git checkout v3.2.0
./autogen.sh
./configure
make
sudo make install
sudo ldconfig
# Save about 0.5G of storage by cleaning up protobuf build
make clean

echo "end install protobuf:"
date

echo "------------------------------------------------------------"
echo "Installing p4lang/behavioral-model"
echo "start install behavioral-model:"
date

cd "${INSTALL_DIR}"
# Clone Github repo
get_from_nearest https://github.com/p4lang/behavioral-model.git behavioral-model.tar.gz
cd behavioral-model
# Get latest updates that are not in the repo cache version
git pull
git log -n 1
./install_deps.sh

# Compile and install behavioral-model
./autogen.sh
# With debug enabled in binaries:
./configure 'CXXFLAGS=-O0 -g'
# Without debug enabled:
#./configure
make
sudo make install
sudo ldconfig

echo "end install behavioral-model:"
date

echo "------------------------------------------------------------"
echo "Installing p4lang/p4c"
echo "start install p4c:"
date

cd "${INSTALL_DIR}"
# Clone p4c and its submodules:
git clone --recursive https://github.com/p4lang/p4c.git
cd p4c
git log -n 1
mkdir build
cd build
# Configure for a debug build
cmake .. -DCMAKE_BUILD_TYPE=DEBUG $*
make -j${MAX_PARALLEL_JOBS}
sudo make install
sudo ldconfig

echo "end install p4c:"
date

echo "------------------------------------------------------------"
echo "Time and disk space used when installation was complete:"
date
df -h .
df -BM .

P4GUIDE_BIN="${THIS_SCRIPT_DIR_ABSOLUTE}"

echo "----------------------------------------------------------------------"
echo "CONSIDER READING WHAT IS BELOW"
echo "----------------------------------------------------------------------"
echo ""

cd "${INSTALL_DIR}"
echo "P4_INSTALL=\"${INSTALL_DIR}\"" > p4setup.bash
echo "BMV2=\"\$P4_INSTALL/behavioral-model\"" >> p4setup.bash
echo "P4GUIDE_BIN=\"${P4GUIDE_BIN}\"" >> p4setup.bash
echo "export PATH=\"\$P4GUIDE_BIN:\$BMV2/tools:/usr/local/bin:\$PATH\"" >> p4setup.bash

echo "set P4_INSTALL=\"${INSTALL_DIR}\"" > p4setup.csh
echo "set BMV2=\"\$P4_INSTALL/behavioral-model\"" >> p4setup.csh
echo "set P4GUIDE_BIN=\"${P4GUIDE_BIN}\"" >> p4setup.csh
echo "set path = ( \$P4GUIDE_BIN \$BMV2/tools /usr/local/bin \$path )" >> p4setup.csh

echo ""
echo "Created files: p4setup.bash p4setup.csh"
echo ""
echo "If you use a Bash-like command shell, you may wish to copy the lines"
echo "of the file p4setup.bash to your .bashrc or .profile files in your"
echo "home directory to add some useful commands to your"
echo "command path every time you log in or create a new shell."
echo ""
echo "If you use the tcsh or csh shells, instead copy the contents of the"
echo "file p4setup.csh to your .tcshrc or .cshrc file in your home"
echo "directory."

echo "----------------------------------------------------------------------"
echo "CONSIDER READING WHAT IS ABOVE"
echo "----------------------------------------------------------------------"

clean_up

{'repo_name': 'jafingerhut/p4-guide', 'stars': '202', 'repo_language': 'P4', 'file_name': 'README.md', 'mime_type': 'text/plain', 'hash': -641031237826453904, 'source_dataset': 'data'}


/*
 *  Routines to access hardware
 *
 *  Copyright (c) 2013 Realtek Semiconductor Corp.
 *
 *  This module is a confidential and proprietary property of RealTek and
 *  possession or use of this module requires written permission of RealTek.
 */

#include "basic_types.h"
#include <stdarg.h>
#include <stddef.h>             /* Compiler defns such as size_t, NULL etc. */
#include "strproc.h"
#include "section_config.h"
#include "diag.h"
#include "ameba_soc.h"

/**
 * stricmp - A small but sufficient implementation for case insensitive strcmp.
 * @str1:
 * @str2:
 * @note support from B CUT
 */
LIBC_ROM_TEXT_SECTION
_LONG_CALL_ int _stricmp(const char* str1, const char* str2)
{
	char c1, c2;

	do {
		c1 = *str1++;
		c2 = *str2++;
		if (c1 != c2) {
			char c1_upc = c1 | 0x20;
			if ((c1_upc >= 'a') && (c1_upc <= 'z')) {
				/* characters are not equal an one is in the alphabet range:
				downcase both chars and check again */
				char c2_upc = c2 | 0x20;
				if (c1_upc != c2_upc) {
					/* still not equal */
					/* don't care for < or > */
					return 1;
				}
			} else {
				/* characters are not equal but none is in the alphabet range */
				return 1;
			}
		}
	} while (c1 != 0);
	return 0;
}

{'repo_name': 'Samsung/TizenRT', 'stars': '345', 'repo_language': 'C', 'file_name': 'Kconfig', 'mime_type': 'text/plain', 'hash': -6801989691555683236, 'source_dataset': 'data'}


import { combineReducers } from 'redux';

import actionSheetManager from './actionSheetManager';
import addCash from './addCash';
import appState from './appState';
import charts from './charts';
import contacts from './contacts';
import data from './data';
import editOptions from './editOptions';
import explorer from './explorer';
import gas from './gas';
import imageMetadata from './imageMetadata';
import keyboardHeight from './keyboardHeight';
import nonce from './nonce';
import openStateSettings from './openStateSettings';
import raps from './raps';
import requests from './requests';
import savings from './savings';
import settings from './settings';
import showcaseTokens from './showcaseTokens';
import uniqueTokens from './uniqueTokens';
import uniswap from './uniswap';
import walletconnect from './walletconnect';
import wallets from './wallets';

export default combineReducers({
  actionSheetManager,
  addCash,
  appState,
  charts,
  contacts,
  data,
  editOptions,
  explorer,
  gas,
  imageMetadata,
  keyboardHeight,
  nonce,
  openStateSettings,
  raps,
  requests,
  savings,
  settings,
  showcaseTokens,
  uniqueTokens,
  uniswap,
  walletconnect,
  wallets,
});

{'repo_name': 'rainbow-me/rainbow', 'stars': '219', 'repo_language': 'JavaScript', 'file_name': 'environment.js', 'mime_type': 'text/plain', 'hash': 8362557505501657101, 'source_dataset': 'data'}