text:
/*!
**|   PonkBot Media Handling
**@
*/

'use strict';

const FLAGS = require('./flags.js');

module.exports = {

    mediaMove: function({ from, after = this.currUID }){
        this.logger.log(`Moving media uid ${from}`);
        this.client.move({ from, after });
    },

    mediaBlame: function(media, callback) {
        this.db.mediaBlame(media, [this.name, ...this.peers]).then((rows)=>{
            if(rows.length){
                return callback(rows.shift());
            }
            callback(false);
        },(error)=>{
            this.logger.error(`Media blame error: ${JSON.stringify(error)}`)
            callback(false);
        });
    },

    mediaUpdate: function(time, paused) {
        switch(true){
            case typeof time !== 'number'      : return this.sendMessage('mediaUpdate: time param unset');
            case typeof paused === 'undefined' : return this.sendMessage('mediaUpdate: paused param unset');
            case !this.leader                  : return this.sendMessage('mediaUpdate: not leader');
            case !this.currMedia.id            : return this.sendMessage('mediaUpdate: no currMedia');
        }

        this.logger.log(`Setting media time to ${time} ${paused ? 'paused' : 'unpaused'}.`);

        this.client.socket.emit('mediaUpdate', {
            type        : this.currMedia.type,
            id          : this.currMedia.id,
            currentTime : time,
            paused      : paused,
        });
    },

    mediaSend: function({ type, id, temp = true, pos = 'end' }) {
        const media = {
            'type'     : type,
            'id'       : id,
            'pos'      : pos,
            'temp'     : temp,
            'duration' : 0,
        }

        this.checkCooldown({ type: 'mediaSend', user: this.name, silent: true }).then(() => {
            this.logger.log(`Sending queue request for ${media.type}:${media.id}`);
            this.client.socket.emit('queue', media);
        },(message) => {
            setTimeout(()=>{
                process.nextTick(()=>{
                    this.mediaSend(media);
                });
            }, 500);
        });
    },

    mediaQueue: function(many) {
        const handleRow = (video) => {
            // duration is returned too, but we don't use it here
            const { type, id, title, flags } = video;

            if(type in this.validators){
                return this.validators[type](id).then(({ trash, reason, flag = false })=>{
                    if(!trash){
                        return this.mediaSend({ type, id });
                    }
                    this.mediaQueue(1);
                    this.logger.log('Media found to be invalid:', `${type}:${id}`, title);
                    if(flag){
                        if((flags & FLAGS.MEDIA.WHITE) === FLAGS.MEDIA.WHITE){
                            this.logger.log('Warning! Whitelisted video has been greylisted.');
                        }
                        this.db.mediaSetFlags({ type, id, title, flags: FLAGS.MEDIA.GREY });
                    }
                });
            }
            else {
                this.sendVideo({ type, id });
            }
        }

        // TODO: Whitelist
        this.db.mediaGet({ many, maxvidlen: this.maxvidlen, types: this.vidtypes }).then((rows)=>{
            if(!rows.length){
                this.logger.debug('Zero videos available. The media table may be empty.');
            }

            rows.forEach(video => {handleRow(video)});
        },(error)=>{
            this.logger.error(JSON.stringify(error));
        });
    },

    mediaValidate: function(playlistItem){
        this.logger.debug('Validating playlist item', playlistItem);

        const { type, id, title, seconds } = playlistItem.media;
        const { queueby, uid } = playlistItem;
        const rank = this.getUserRank(queueby);

        // TODO: Redesign how blacklist works

        const handleFlags = (flags) => {
            if(FLAGS.MEDIA.BLACK & flags && rank < 2){
                this.sendPrivate(`Media is blacklisted: ${type}:${id} - ${title}`, queueby);
                this.mediaDelete(uid);
                return;
            }

            this.userCheckBlocked(queueby).then((blocked)=>{
                handleBlock(blocked, flags)
            });
        }

        // Nuke's bot would greylist vids in this case but I don't think that's wise
        //   A particularly malicious malcontent could deliberately queue a bunch of good vids
        const handleBlock = (blocked, flags) => {
            if(blocked){
                this.sendPrivate(`You're playlist banned.`, queueby);
                this.mediaDelete(uid);
                return;
            }

            if(type in this.validators){
                this.validators[type](id).then(({ trash, reason, flag = false })=>{
                    if(!trash){
                        return; // TODO: Blacklist?
                    }

                    this.logger.log('Media found to be invalid:', `${type}:${id}`, title);

                    this.sendPrivate('Media you queued had issues:', queueby);
                    this.sendPrivate(`${type}:${id} - ${title}`, queueby);
                    this.sendPrivate(reason, queueby);

                    if(flag){
                        if((flags & FLAGS.MEDIA.WHITE) === FLAGS.MEDIA.WHITE){
                            this.logger.log('Warning! Whitelisted video has been greylisted.');
                        }
                        this.db.mediaSetFlags({ type, id, title, flags: FLAGS.MEDIA.GREY });
                    }

                    this.mediaDelete(uid);

                    // TODO: Cache validated media
                });
            }
            else {
                return; // TODO: Blacklist?
            }
        }

        if (![this.name, ...this.peers].includes(queueby)){
            this.db.mediaInsert({ type, id, title, duration : seconds });
        }

        // Start validation
        process.nextTick(()=>{
            this.db.mediaGetFlags({ type, id }).then(handleFlags);
        });
    },

    mediaGetByUID: function(uid){
        for(const item in this.playlist){
            if(this.playlist[item].uid === uid){ return this.playlist[item].media }
        }
        return false;
    },

    mediaGetByQueueby: function(user){
        return new Promise((resolve)=>{
            const mediaList = [];
            for(const item in this.playlist){
                if(this.playlist[item].queueby === user){
                    mediaList.push(this.playlist[item]);
                }
            }
            return resolve(mediaList);
        });
    },

    mediaDelete: function(uid){
        this.logger.log(`Deleting media uid ${uid}`);
        this.client.socket.emit('delete', uid);
    },

    mediaAddFlags: function({ type, id, flags, title = '' }){
        this.db.mediaSetFlags({ type, id, flags, title });
    },

    mediaGreylist: function({ type, id, title = '' }){
        this.mediaAddFlags({ type, id, flags: FLAGS.MEDIA.GREY });
    },

    mediaWhitelist: function({ type, id, title = '' }){
        this.mediaAddFlags({ type, id, flags: FLAGS.MEDIA.WHITE });
    },

    mediaBlacklist: function({ type, id, title = '', deletThis = true }){
        this.mediaAddFlags({ type, id, flags: FLAGS.MEDIA.BLACK });
        if(!deletThis){ return }
        for(const item in this.playlist){
            let media = this.playlist[item].media
            if(media.type === type && media.id === id){
                this.mediaDelete(this.playlist[item].uid);
            }
        }
    },

    mediaFlagByUID: function({ flag, uid }){
        const media = this.mediaGetByUID(uid);
        if(!media){ return }

        switch(flag.toLowerCase()){
            case 'grey'  : return this.mediaGreylist(media);
            case 'black' : return this.mediaBlacklist(media);
            case 'white' : return this.mediaWhitelist(media);
            default: throw new Error('Invalid flag type');
        }
    },

}


text:
namespace peloton {
namespace codegen {

//===----------------------------------------------------------------------===//
// OUTPUT TINYINT
//===----------------------------------------------------------------------===//

// Get the symbol name for ValuesRuntime::OutputTinyInt()
const std::string &ValuesRuntimeProxy::_OutputTinyInt::GetFunctionName() {
  static const std::string kOutputTinyIntFnName =
      "_ZN7peloton7codegen13ValuesRuntime13OutputTinyIntEPcja";
  return kOutputTinyIntFnName;
}

llvm::Function *ValuesRuntimeProxy::_OutputTinyInt::GetFunction(
    CodeGen &codegen) {
  const std::string &fn_name = GetFunctionName();

  // Has the function already been registered?
  llvm::Function *llvm_fn = codegen.LookupFunction(fn_name);
  if (llvm_fn != nullptr) {
    return llvm_fn;
  }

  auto *value_type = ValueProxy::GetType(codegen);
  auto *fn_type = llvm::FunctionType::get(
      codegen.VoidType(),
      {value_type->getPointerTo(), codegen.Int64Type(), codegen.Int16Type()},
      false);
  return codegen.RegisterFunction(fn_name, fn_type);
}

//===----------------------------------------------------------------------===//
// OUTPUT SMALLINT
//===----------------------------------------------------------------------===//

const std::string &ValuesRuntimeProxy::_OutputSmallInt::GetFunctionName() {
  static const std::string kOutputSmallIntFnName =
      "_ZN7peloton7codegen13ValuesRuntime14OutputSmallIntEPcjs";
  return kOutputSmallIntFnName;
}

llvm::Function *ValuesRuntimeProxy::_OutputSmallInt::GetFunction(
    CodeGen &codegen) {
  const std::string &fn_name = GetFunctionName();

  // Has the function already been registered?
  llvm::Function *llvm_fn = codegen.LookupFunction(fn_name);
  if (llvm_fn != nullptr) {
    return llvm_fn;
  }

  auto *value_type = ValueProxy::GetType(codegen);
  auto *fn_type = llvm::FunctionType::get(
      codegen.VoidType(),
      {value_type->getPointerTo(), codegen.Int64Type(), codegen.Int16Type()},
      false);
  return codegen.RegisterFunction(fn_name, fn_type);
}

//===----------------------------------------------------------------------===//
// OUTPUT INTEGER
//===----------------------------------------------------------------------===//

const std::string &ValuesRuntimeProxy::_OutputInteger::GetFunctionName() {
  static const std::string kOutputIntegerFnName =
      "_ZN7peloton7codegen13ValuesRuntime13OutputIntegerEPcji";
  return kOutputIntegerFnName;
}

llvm::Function *ValuesRuntimeProxy::_OutputInteger::GetFunction(
    CodeGen &codegen) {
  const std::string &fn_name = GetFunctionName();

  // Has the function already been registered?
  llvm::Function *llvm_fn = codegen.LookupFunction(fn_name);
  if (llvm_fn != nullptr) {
    return llvm_fn;
  }

  auto *value_type = ValueProxy::GetType(codegen);
  auto *fn_type = llvm::FunctionType::get(
      codegen.VoidType(),
      {value_type->getPointerTo(), codegen.Int64Type(), codegen.Int32Type()},
      false);
  return codegen.RegisterFunction(fn_name, fn_type);
}

//===----------------------------------------------------------------------===//
// OUTPUT BIGINT
//===----------------------------------------------------------------------===//

const std::string &ValuesRuntimeProxy::_OutputBigInt::GetFunctionName() {
  static const std::string kOutputBigIntFnName =
      "_ZN7peloton7codegen13ValuesRuntime12OutputBigIntEPcjl";
  return kOutputBigIntFnName;
}

llvm::Function *ValuesRuntimeProxy::_OutputBigInt::GetFunction(
    CodeGen &codegen) {
  const std::string &fn_name = GetFunctionName();

  // Has the function already been registered?
  llvm::Function *llvm_fn = codegen.LookupFunction(fn_name);
  if (llvm_fn != nullptr) {
    return llvm_fn;
  }

  auto *value_type = ValueProxy::GetType(codegen);
  auto *fn_type = llvm::FunctionType::get(
      codegen.VoidType(),
      {value_type->getPointerTo(), codegen.Int64Type(), codegen.Int64Type()},
      false);
  return codegen.RegisterFunction(fn_name, fn_type);
}

//===----------------------------------------------------------------------===//
// OUTPUT DOUBLE
//===----------------------------------------------------------------------===//

const std::string &ValuesRuntimeProxy::_OutputDouble::GetFunctionName() {
  static const std::string kOutputDoubleFnName =
      "_ZN7peloton7codegen13ValuesRuntime13OutputDecimalEPcjd";
  return kOutputDoubleFnName;
}

llvm::Function *ValuesRuntimeProxy::_OutputDouble::GetFunction(
    CodeGen &codegen) {
  const std::string &fn_name = GetFunctionName();

  // Has the function already been registered?
  llvm::Function *llvm_fn = codegen.LookupFunction(fn_name);
  if (llvm_fn != nullptr) {
    return llvm_fn;
  }

  auto *value_type = ValueProxy::GetType(codegen);
  auto *fn_type = llvm::FunctionType::get(
      codegen.VoidType(),
      {value_type->getPointerTo(), codegen.Int64Type(), codegen.DoubleType()},
      false);
  return codegen.RegisterFunction(fn_name, fn_type);
}

//===----------------------------------------------------------------------===//
// OUTPUT TIMESTAMP
//===----------------------------------------------------------------------===//

const std::string &ValuesRuntimeProxy::_OutputTimestamp::GetFunctionName() {
  static const std::string kOutputTimestampFnName =
      "_ZN7peloton7codegen13ValuesRuntime15OutputTimestampEPcjl";
  return kOutputTimestampFnName;
}

llvm::Function *ValuesRuntimeProxy::_OutputTimestamp::GetFunction(
    CodeGen &codegen) {
  const std::string &fn_name = GetFunctionName();

  // Has the function already been registered?
  llvm::Function *llvm_fn = codegen.LookupFunction(fn_name);
  if (llvm_fn != nullptr) {
    return llvm_fn;
  }

  auto *value_type = ValueProxy::GetType(codegen);
  auto *fn_type = llvm::FunctionType::get(
      codegen.VoidType(),
      {value_type->getPointerTo(), codegen.Int64Type(), codegen.Int64Type()},
      false);
  return codegen.RegisterFunction(fn_name, fn_type);
}

//===----------------------------------------------------------------------===//
// OUTPUT VARCHAR
//===----------------------------------------------------------------------===//

const std::string &ValuesRuntimeProxy::_OutputVarchar::GetFunctionName() {
  static const std::string kOutputVarcharFnName =
#ifdef __APPLE__
      "_ZN7peloton7codegen13ValuesRuntime13outputVarcharEPcjS2_j";
#else
      "_ZN7peloton7codegen13ValuesRuntime13OutputVarcharEPcjS2_j";
#endif
  return kOutputVarcharFnName;
}

llvm::Function *ValuesRuntimeProxy::_OutputVarchar::GetFunction(
    CodeGen &codegen) {
  const std::string &fn_name = GetFunctionName();

  // Has the function already been registered?
  llvm::Function *llvm_fn = codegen.LookupFunction(fn_name);
  if (llvm_fn != nullptr) {
    return llvm_fn;
  }

  auto *value_type = ValueProxy::GetType(codegen);
  std::vector<llvm::Type *> arg_types = {
      value_type->getPointerTo(), codegen.Int64Type(), codegen.CharPtrType(),
      codegen.Int32Type()};
  auto *fn_type = llvm::FunctionType::get(codegen.VoidType(), arg_types, false);
  return codegen.RegisterFunction(fn_name, fn_type);
}

//===----------------------------------------------------------------------===//
// OUTPUT VARBINARY
//===----------------------------------------------------------------------===//

const std::string &ValuesRuntimeProxy::_OutputVarbinary::GetFunctionName() {
  static const std::string kOutputVarbinaryFnName =
      "_ZN7peloton7codegen13ValuesRuntime15OutputVarbinaryEPcjS2_j";
  return kOutputVarbinaryFnName;
}

llvm::Function *ValuesRuntimeProxy::_OutputVarbinary::GetFunction(
    CodeGen &codegen) {
  const std::string &fn_name = GetFunctionName();

  // Has the function already been registered?
  llvm::Function *llvm_fn = codegen.LookupFunction(fn_name);
  if (llvm_fn != nullptr) {
    return llvm_fn;
  }

  auto *value_type = ValueProxy::GetType(codegen);
  std::vector<llvm::Type *> arg_types = {
      value_type->getPointerTo(), codegen.Int64Type(), codegen.CharPtrType(),
      codegen.Int32Type()};
  auto *fn_type = llvm::FunctionType::get(codegen.VoidType(), arg_types, false);
  return codegen.RegisterFunction(fn_name, fn_type);
}

//===----------------------------------------------------------------------===//
// COMPARE STRINGS
//===----------------------------------------------------------------------===//

const std::string &ValuesRuntimeProxy::_CompareStrings::GetFunctionName() {
  static const std::string kCompareStringsFnName =
#ifdef __APPLE__
      "_ZN7peloton7codegen13ValuesRuntime14CompareStringsEPKcjS3_j";
#else
      "_ZN7peloton7codegen13ValuesRuntime14CompareStringsEPKcjS3_j";
#endif
  return kCompareStringsFnName;
}

llvm::Function *ValuesRuntimeProxy::_CompareStrings::GetFunction(
    CodeGen &codegen) {
  const std::string &fn_name = GetFunctionName();

  // Has the function already been registered?
  llvm::Function *llvm_fn = codegen.LookupFunction(fn_name);
  if (llvm_fn != nullptr) {
    return llvm_fn;
  }

  std::vector<llvm::Type *> arg_types = {codegen.CharPtrType(),  // str1
                                         codegen.Int32Type(),    // str1 length
                                         codegen.CharPtrType(),  // str2
                                         codegen.Int32Type()};   // str2 length
  auto *fn_type =
      llvm::FunctionType::get(codegen.Int32Type(), arg_types, false);
  return codegen.RegisterFunction(fn_name, fn_type);
}

}  // namespace codegen
}  // namespace peloton

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML>

<title>Testcase, 'overflow' on elements with 'display:inline-block'</title>


text:
	<title>Jeremy Corbyn's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Jeremy Corbyn's panel show appearances

Jeremy Corbyn (born 1949-05-26[ref]) has appeared in 5 episodes between 2015-2019.  Jeremy Corbyn on Wikipedia.

2015

2016

2017

2018

2019

2019-11-22 / Question Time

2017-06-02 / Question Time

2016-09-08 / Question Time

2016-06-10 / The Last Leg

2015-07-02 / Question Time


text:
require 'rubygems'
require 'bundler'

Bundler.require

# Support files first
require 'active_support/core_ext/hash'
require 'active_support/core_ext/string/conversions'
require 'active_support/json'

require 'json'

unless defined? HashWithIndifferentAccess
  require 'active_support/hash_with_indifferent_access'
end

filepath = File.join( File.dirname(__FILE__), 'support', '*.rb' )
Dir.glob(filepath){|fname| require fname }

filepath = File.join( File.dirname(__FILE__), 'prism-residential-service-client', '*.rb' )
Dir.glob(filepath){|fname| require fname }


text:
<resources>

    <string name="app_name">FastFireFrameAndroidTest</string>

</resources>


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef CONF_BOARD_H_INCLUDED
#define CONF_BOARD_H_INCLUDED

/** Enable Com Port. */
#define CONF_BOARD_UART_CONSOLE

/* USART1 module is used in serial mode. */
#define CONF_BOARD_USART_RXD
#define CONF_BOARD_USART_TXD

/* Configure ADM3312 enable pin. */
#define CONF_BOARD_ADM3312_EN

#endif /* CONF_BOARD_H_INCLUDED */


text:
using Newtonsoft.Json;

namespace OpenInvoicePeru.Comun.Dto.Modelos
{
    public class Contribuyente
    {
        [JsonProperty(Order = 1, Required = Required.Always)]
        public string NroDocumento { get; set; }

        [JsonProperty(Order = 2, Required = Required.Always)]
        public string TipoDocumento { get; set; }

        [JsonProperty(Order = 3, Required = Required.Always)]
        public string NombreLegal { get; set; }

        [JsonProperty(Order = 4)]
        public string NombreComercial { get; set; }

        [JsonProperty(Order = 5)]
        public string Ubigeo { get; set; }

        [JsonProperty(Order = 6)]
        public string Direccion { get; set; }

        [JsonProperty(Order = 7)]
        public string Urbanizacion { get; set; }

        [JsonProperty(Order = 8)]
        public string Departamento { get; set; }

        [JsonProperty(Order = 9)]
        public string Provincia { get; set; }

        [JsonProperty(Order = 10)]
        public string Distrito { get; set; }
    }
}


text:
sudo apt-get install virtualbox-guest-utils virtualbox-guest-x11 virtualbox-guest-dkms \
	openssh-server


text:
using System;

namespace CodeCampService
{
	public class Room
	{
		public string Key { get; set; }
		public string Name { get; set; }
		public string Description { get; set; }
	}
}


text:
(function() {

let DiffAppDispatcher = require('../dispatcher/AppDispatcher')
  , DiffConstants = require('../constants/DiffConstants')
  , DiffActions = {
      postDataForComparison: function() {
        DiffAppDispatcher.dispatch({
          actionType: DiffConstants.DIFF_POST
        });
      },
      diffComplete: function() {
        DiffAppDispatcher.dispatch({
          actionType: DiffConstants.DIFF_COMPLETE
        });
      }
    };
  module.exports = DiffActions;
})();


text:
<?php

namespace Tests\Api;

use LastFmApi\Api\ChartApi;

/**
 * Tests chart api calls
 *
 * @group notAuthenticated
 * @author Marcos Peña
 */
class ChartTest extends BaseNotAuthenticatedApiTest
{

    private $chartApi;

    public function __construct($name = null, array $data = array(), $dataName = '')
    {
        if (!$this->isApiInitiated()) {
            $this->initiateApi();
        }
        parent::__construct($name, $data, $dataName);
        $this->chartApi = new ChartApi($this->authentication);
    }

    public function testTopArtists()
    {
        $result = $this->chartApi->getTopArtists(array(
            'limit' => 1)
        );
        $this->assertNotEmpty($result);
    }

    public function testTopTags()
    {
        $result = $this->chartApi->getTopTags(array(
                'limit' => 1)
        );
        $this->assertNotEmpty($result);
    }

    public function testTopTracks()
    {
        $result = $this->chartApi->getTopTracks(array(
            'limit' => 1)
        );
        $this->assertNotEmpty($result);
    }

}


text:
package net.coderland.server.core.dao;

import net.coderland.server.core.model.pojo.StockFollows;

import java.util.List;

/**
 * Author: zhangxin
 * Date:   15-12-29
 */
public interface StockFollowsDao {

    int insert(String user, String code);
    int delete(String user, String code);

    List<StockFollows> getFollows(String user);
}


text:
import Ember from 'ember';

const { Controller } = Ember;

export default Controller.extend({
  booleanProp1: true,
  booleanProp2: false,
  booleanProp3: false,
  booleanProp4: false,
  booleanProp5: false,

  actions: {
    changeBooleanProp(which, newValue) {
      this.set(`booleanProp${which}`, newValue);
    }
  }

});


text:
Effects Browser for JC2MP
====================

A simple client effects browser for Just Cause 2 Multiplayer Mod.

When loaded, the camera will position itself at the Panau International Airport. Use the Left/Right arrow keys to switch
between effects. Use Up/Down to jump by 50. Press or hold the Spacebar to fire the current effect again.


text:
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.

#ifndef OPC_TREEBUILDERS_H
#define OPC_TREEBUILDERS_H

#include "PxPhysXCommonConfig.h"
#include "PsUserAllocated.h"
#include "PsVecMath.h"
#include "PxBounds3.h"
#include "CmPhysXCommon.h"

namespace physx
{
using namespace shdfnd::aos;
namespace Sq
{
	class MeshInterface;

	//! Tree splitting rules
	enum SplittingRules
	{
		// Primitive split
		SPLIT_LARGEST_AXIS		= (1<<0),		//!< Split along the largest axis
		SPLIT_SPLATTER_POINTS	= (1<<1),		//!< Splatter primitive centers (QuickCD-style)
		SPLIT_BEST_AXIS			= (1<<2),		//!< Try largest axis, then second, then last
		SPLIT_BALANCED			= (1<<3),		//!< Try to keep a well-balanced tree
		SPLIT_FIFTY				= (1<<4),		//!< Arbitrary 50-50 split
		//
		SPLIT_FORCE_DWORD		= 0x7fffffff
	};

	//! Simple wrapper around build-related settings [Opcode 1.3]
	struct BuildSettings
	{
		PX_FORCE_INLINE	BuildSettings() : mLimit(1), mRules(SPLIT_FORCE_DWORD) {}

		PxU32		mLimit;				//!< Limit number of primitives / node. If limit is 1, build a complete tree (2*N-1 nodes)
		PxU32		mRules;				//!< Building/Splitting rules (a combination of SplittingRules flags)
	};

	class AABBTreeNode;

	class AABBTreeBuilder : public Ps::UserAllocated
	{
		public:
									AABBTreeBuilder() : mAABBArray(NULL) { reset(); }
									~AABBTreeBuilder() {}

		PX_FORCE_INLINE	void		reset()
									{
										mTotalPrims			= 0;
										mNbPrimitives		= 0;
										mNodeBase			= NULL;
										mCount				= 0;
										mNbInvalidSplits	= 0;
									}

		/**
		 *	Computes the AABB of a set of primitives.
		 *	\param		primitives	[in] list of indices of primitives
		 *	\param		nbPrims		[in] number of indices
		 *	\param		global_box	[out] global AABB enclosing the set of input primitives
		 *	\return		true if success
		 */
		PX_FORCE_INLINE void computeGlobalBox(const PxU32* primitives, PxU32 nbPrims, PxBounds3& result, Vec3V* mn, Vec3V* mx) const
		{
			PX_ASSERT(primitives && nbPrims);

			// Initialize global box
			Vec3V resultMin = V3LoadU(mAABBArray[primitives[0]].minimum);
			Vec3V resultMax = V3LoadU(mAABBArray[primitives[0]].maximum);

			// Loop through boxes
			for(PxU32 i=1;i<nbPrims;i++)
			{
				const PxBounds3& b = mAABBArray[primitives[i]];
				resultMin = V3Min(resultMin, V3LoadU(b.minimum));
				resultMax = V3Max(resultMax, V3LoadU(b.maximum));
			}

			*mn = resultMin;
			*mx = resultMax;
			V3StoreU(resultMin, result.minimum);
			V3StoreU(resultMax, result.maximum);
		}

		/**
		 *	Computes the splitting value along a given axis for a given primitive.
		 *	\param		index	[in] index of the primitive to split
		 *	\param		axis	[in] axis index (0,1,2)
		 *	\return		splitting value
		 */
		PX_FORCE_INLINE float getSplittingValue(PxU32 index, PxU32 axis) const
		{
			// For an AABB, the splitting value is the middle of the given axis,
			// i.e. the corresponding component of the center point
			return mAABBArray[index].getCenter(axis);
		}

		PX_FORCE_INLINE Vec3V getSplittingValues(PxU32 index) const
		{
			const PxBounds3& b = mAABBArray[index];
			const Vec3V half_ = V3Load(0.5f);
			return V3Mul(half_, V3Add(V3LoadU(b.minimum), V3LoadU(b.maximum)));
		}

		/**
		 *	Computes the splitting value along a given axis for a given node.
		 *	\param		primitives	[in] list of indices of primitives
		 *	\param		nbPrims		[in] number of indices
		 *	\param		global_box	[in] global AABB enclosing the set of input primitives
		 *	\param		axis		[in] axis index (0,1,2)
		 *	\return		splitting value
		 */
		PX_FORCE_INLINE	float		getSplittingValue(const PxBounds3& global_box, PxU32 axis)	const
									{
										// Default split value = middle of the axis (using only the box)
										return global_box.getCenter(axis);
									}

		/**
		 *	Validates node subdivision. This is called each time a node is considered for subdivision, during tree building.
		 *	\param		primitives	[in] list of indices of primitives
		 *	\param		nbPrims		[in] number of indices
		 *	\param		global_box	[in] global AABB enclosing the set of input primitives
		 *	\return		Ps::IntTrue if the node should be subdivised
		 */
		PX_FORCE_INLINE	Ps::IntBool	validateSubdivision(PxU32 nbPrims)
									{
										// Check the user-defined limit
										if(nbPrims<=mSettings.mLimit)
											return Ps::IntFalse;

										return Ps::IntTrue;
									}

					BuildSettings	mSettings;			//!< Splitting rules & split limit [Opcode 1.3]
					PxU32			mNbPrimitives;		//!< Total number of primitives.
					AABBTreeNode*	mNodeBase;			//!< Address of node pool [Opcode 1.3]
		// Stats
		PX_FORCE_INLINE	void		setCount(PxU32 nb)				{ mCount=nb;				}
		PX_FORCE_INLINE	void		increaseCount(PxU32 nb)			{ mCount+=nb;				}
		PX_FORCE_INLINE	PxU32		getCount()				const	{ return mCount;			}
		PX_FORCE_INLINE	void		setNbInvalidSplits(PxU32 nb)	{ mNbInvalidSplits=nb;		}
		PX_FORCE_INLINE	void		increaseNbInvalidSplits()		{ mNbInvalidSplits++;		}
		PX_FORCE_INLINE	PxU32		getNbInvalidSplits()	const	{ return mNbInvalidSplits;	}

						PxU32		mTotalPrims;
				const	PxBounds3*	mAABBArray;			//!< Shortcut to an app-controlled array of AABBs.
		private:
						PxU32		mCount;				//!< Stats: number of nodes created
						PxU32		mNbInvalidSplits;	//!< Stats: number of invalid splits
	};

} // namespace Gu

}

#endif // OPC_TREEBUILDERS_H


text:
package distuv

import (
	"math"

	"golang.org/x/exp/rand"
)

// UnitUniform is an instantiation of the uniform distribution with Min = 0
// and Max = 1.
var UnitUniform = Uniform{Min: 0, Max: 1}

// Uniform represents a continuous uniform distribution (https://en.wikipedia.org/wiki/Uniform_distribution_%28continuous%29).
type Uniform struct {
	Min float64
	Max float64
	Src rand.Source
}

// CDF computes the value of the cumulative density function at x.
func (u Uniform) CDF(x float64) float64 {
	if x < u.Min {
		return 0
	}
	if x > u.Max {
		return 1
	}
	return (x - u.Min) / (u.Max - u.Min)
}

// Uniform doesn't have any of the DLogProbD? because the derivative is 0 everywhere
// except where it's undefined

// Entropy returns the entropy of the distribution.
func (u Uniform) Entropy() float64 {
	return math.Log(u.Max - u.Min)
}

// ExKurtosis returns the excess kurtosis of the distribution.
func (Uniform) ExKurtosis() float64 {
	return -6.0 / 5.0
}

// Uniform doesn't have Fit because it's a bad idea to fit a uniform from data.

// LogProb computes the natural logarithm of the value of the probability density function at x.
func (u Uniform) LogProb(x float64) float64 {
	if x < u.Min {
		return math.Inf(-1)
	}
	if x > u.Max {
		return math.Inf(-1)
	}
	return -math.Log(u.Max - u.Min)
}

// MarshalParameters implements the ParameterMarshaler interface
func (u Uniform) MarshalParameters(p []Parameter) {
	if len(p) != u.NumParameters() {
		panic("uniform: improper parameter length")
	}
	p[0].Name = "Min"
	p[0].Value = u.Min
	p[1].Name = "Max"
	p[1].Value = u.Max
}

// Mean returns the mean of the probability distribution.
func (u Uniform) Mean() float64 {
	return (u.Max + u.Min) / 2
}

// Median returns the median of the probability distribution.
func (u Uniform) Median() float64 {
	return (u.Max + u.Min) / 2
}

// Uniform doesn't have a mode because it's any value in the distribution

// NumParameters returns the number of parameters in the distribution.
func (Uniform) NumParameters() int {
	return 2
}

// Prob computes the value of the probability density function at x.
func (u Uniform) Prob(x float64) float64 {
	if x < u.Min {
		return 0
	}
	if x > u.Max {
		return 0
	}
	return 1 / (u.Max - u.Min)
}

// Quantile returns the inverse of the cumulative probability distribution.
func (u Uniform) Quantile(p float64) float64 {
	if p < 0 || p > 1 {
		panic(badPercentile)
	}
	return p*(u.Max-u.Min) + u.Min
}

// Rand returns a random sample drawn from the distribution.
func (u Uniform) Rand() float64 {
	var rnd float64
	if u.Src == nil {
		rnd = rand.Float64()
	} else {
		rnd = rand.New(u.Src).Float64()
	}
	return rnd*(u.Max-u.Min) + u.Min
}

// Skewness returns the skewness of the distribution.
func (Uniform) Skewness() float64 {
	return 0
}

// StdDev returns the standard deviation of the probability distribution.
func (u Uniform) StdDev() float64 {
	return math.Sqrt(u.Variance())
}

// Survival returns the survival function (complementary CDF) at x.
func (u Uniform) Survival(x float64) float64 {
	if x < u.Min {
		return 1
	}
	if x > u.Max {
		return 0
	}
	return (u.Max - x) / (u.Max - u.Min)
}

// UnmarshalParameters implements the ParameterMarshaler interface
func (u *Uniform) UnmarshalParameters(p []Parameter) {
	if len(p) != u.NumParameters() {
		panic("uniform: incorrect number of parameters to set")
	}
	if p[0].Name != "Min" {
		panic("uniform: " + panicNameMismatch)
	}
	if p[1].Name != "Max" {
		panic("uniform: " + panicNameMismatch)
	}

	u.Min = p[0].Value
	u.Max = p[1].Value
}

// Variance returns the variance of the probability distribution.
func (u Uniform) Variance() float64 {
	return 1.0 / 12.0 * (u.Max - u.Min) * (u.Max - u.Min)
}


text:
// Copyright CommonsForNET.
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You 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.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Commons.Test.Json
{
    public enum PostState
    {
        Draft,
        Published,
        Hidden,
    }

    public class DeletePost : IEquatable<DeletePost>
    {
        private static DateTime NOW = DateTime.UtcNow;
        private static readonly Guid[] GUIDS = Enumerable.Range(0, 100).Select(it => Guid.NewGuid()).ToArray();

        public int postID { get; set; }
        public Guid? referenceId { get; set; }
        public DateTime lastModified { get; set; }
        public long deletedBy { get; set; }
        public string reason { get; set; }
        public long[] versions { get; set; }
        public PostState? state { get; set; }
        public List<bool?> votes { get; set; }
        public override int GetHashCode() { return postID; }
        public override bool Equals(object obj) { return Equals(obj as DeletePost); }
        public bool Equals(DeletePost other)
        {
            return other != null && other.postID == this.postID && other.referenceId == this.referenceId
                && other.lastModified == this.lastModified && other.deletedBy == this.deletedBy
                && other.reason == this.reason
                && (other.versions == this.versions || other.versions != null && Enumerable.SequenceEqual(other.versions, this.versions))
                && other.state == this.state
                && (other.votes == this.votes || other.votes != null && Enumerable.SequenceEqual(other.votes, this.votes));
        }
        public static TD Factory<TD, TS>(int i, Func<int, TS> cast)
            where TD : new()
            where TS : struct
        {
            dynamic delete = new TD();
            delete.postID = i;
            delete.deletedBy = i / 100;
            delete.lastModified = NOW.AddSeconds(i);
            delete.reason = "no reason";
            if (i % 3 == 0) delete.referenceId = GUIDS[i % 100];
            if (i % 5 == 0) delete.state = cast(i % 3);
            if (i % 7 == 0)
            {
                delete.versions = new long[i % 100 + 1];//ProtoBuf hack - always add object since Protobuf can't differentiate
                for (int x = 0; x <= i % 100; x++)
                    delete.versions[x] = i * x + x;
            }
            if (i % 2 == 0 && i % 10 != 0)
            {
                delete.votes = new List<bool?>();
                for (int j = 0; j < i % 10; j++)
                    delete.votes.Add((i + j) % 3 == 0 ? true : j % 2 == 0 ? (bool?)false : null);
            }
            return delete;
        }
    }
    public class Post : IEquatable<Post>
    {
        private static DateTime NOW = DateTime.UtcNow;
        private static DateTime TODAY = DateTime.UtcNow.Date;
        private static string[][] TAGS = new[] { new string[0], new[] { "JSON" }, new[] { ".NET", "Java", "benchmark" } };

        public Post()
        {
            comments = new List<Comment>();
        }

        public int ID { get; set; }
        public string title { get; set; }
        public string text { get; set; }
        public DateTime created { get; set; }
        public HashSet<string> tags { get; set; }
        public DateTime? approved { get; set; }
        public List<Comment> comments { get; set; }
        public Vote votes { get; set; }
        public List<string> notes { get; set; }
        public PostState state { get; set; }
        public override int GetHashCode() { return ID; }
        public override bool Equals(object obj) { return Equals(obj as Post); }
        public bool Equals(Post other)
        {
            var otherTags = other == null || other.tags == null ? null : other.tags.ToList();
            var thisTags = this.tags != null ? this.tags.ToList() : null;
            if (thisTags != null) thisTags.Sort();
            if (otherTags != null) otherTags.Sort();
            return other != null && other.ID == this.ID && other.title == this.title
                && other.text == this.text && other.created == this.created
                && (otherTags == thisTags || otherTags != null && thisTags != null && Enumerable.SequenceEqual(otherTags, thisTags))
                && other.approved == this.approved
                && Enumerable.SequenceEqual(other.comments, this.comments)
                && other.votes.Equals(this.votes)
                && (other.notes == this.notes || other.notes != null && Enumerable.SequenceEqual(other.notes, this.notes))
                && other.state == this.state;
        }
        public static TP Factory<TP, TV, TS, TC>(int i, Func<int, TS> cast)
            where TP : new()
            where TV : new()
            where TC : new()
            where TS : struct
        {
            dynamic post = new TP();
            post.ID = -i;
            post.approved = i % 2 == 0 ? null : (DateTime?)NOW.AddMilliseconds(i);
            dynamic votes = new TV();
            votes.downvote = i / 3;
            votes.upvote = i / 2;
            post.votes = votes;
            post.text = "some text describing post " + i;
            post.title = "post title " + i;
            post.state = cast(i % 3);
            post.tags = new HashSet<string>(TAGS[i % 3]);
            post.created = TODAY.AddDays(i);
            for (int j = 0; j < i % 100; j++)
            {
                dynamic comment = new TC();
                comment.created = TODAY.AddDays(i + j);
                comment.message = "comment number " + i + " for " + j;
                dynamic v = new TV();
                v.upvote = j;
                v.downvote = j * 2;
                comment.votes = v;
                comment.approved = j % 3 != 0 ? null : (DateTime?)NOW.AddMilliseconds(i);
                comment.user = "some random user " + i;
                post.comments.Add(comment);
            }
            return post;
        }
    }
    public class Comment : IEquatable<Comment>
    {
        public DateTime created { get; set; }
        public DateTime? approved { get; set; }
        public string user { get; set; }
        public string message { get; set; }
        public Vote votes { get; set; }
        public override int GetHashCode() { return created.GetHashCode(); }
        public override bool Equals(object obj) { return Equals(obj as Comment); }
        public bool Equals(Comment other)
        {
            return other != null
                && other.created == this.created && other.approved == this.approved && other.user == this.user
                && other.message == this.message && other.votes.Equals(this.votes);
        }
    }
    public class Vote : IEquatable<Vote>
    {
        public int upvote { get; set; }
        public int downvote { get; set; }
        public override int GetHashCode() { return upvote ^ downvote; }
        public override bool Equals(object obj) { return Equals(obj as Vote); }
        public bool Equals(Vote other)
        {
            return other != null && other.upvote == this.upvote && other.downvote == this.downvote;
        }
    }
}


text:
(function() {
    'use strict';
    /* globals SockJS, Stomp */

    angular
        .module('simpleWebrtcServerApp')
        .factory('TaskFinderService', TaskFinderService);

    TaskFinderService.$inject = ['Task'];

    function TaskFinderService(Task) {

        var service = {
            getNextTask: getNextTask,
            getPreviousTask: getPreviousTask,
            findFirstTask: findFirstTask,
            initTasksForScenarioId: initTasksForScenarioId,
            hasNextTask: hasNextTask,
            hasPreviousTask: hasPreviousTask,
            findById: findById
        };
        return service;

        function findById(taskId, tasks) {
            return tasks.find(function(element) {
                return taskId == element.id;
            });
        }

        function getNextTask(task, tasks) {
            return tasks.find(function(element) {
                return task.nextTaskId == element.id;
            });
        }

        function getPreviousTask(task, tasks) {
            return tasks.find(function(element) {
                return task.id == element.nextTaskId;
            });
        }

        function findFirstTask(tasks) {
            if (tasks.length == 1) {
                return tasks[0];
            }
            var lastTask = tasks.find(function(element) {
                if (element.nextTaskId) {
                    return false;
                } else {
                    return true;
                }
            });
            return recursiveFindFirst(lastTask, tasks);
        }

        function recursiveFindFirst(task, tasks) {
            var previousTask = getPreviousTask(task, tasks);
            if (previousTask) {
                return recursiveFindFirst(previousTask, tasks);
            } else {
                return task;
            }
        }

        function initTasksForScenarioId(scenarioId) {
            var tasks = Task.query({
                scenarioId: scenarioId
            });
            return tasks;
        }

        function hasNextTask(task, tasks) {
            if (!task || !tasks) {
                return false;
            }
            if (!task.nextTaskId) {
                return false;
            }
            if (tasks.lenth == 1 || tasks.length == 0) {
                return false;
            }
            return tasks.some(function(element) {
                return task.nextTaskId == element.id;
            });
        }

        function hasPreviousTask(task, tasks) {
            if (!task || !tasks) {
                return false;
            }
            if (tasks.lenth == 1 || tasks.length == 0) {
                return false;
            }
            return tasks.some(function(element) {
                return task.id == element.nextTaskId;
            });
        }
    }
})();


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Services.Installer.Writers
{
    using System.Collections.Generic;
    using System.IO;
    using System.Xml;

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The CleanupComponentWriter class handles creating the manifest for Cleanup
    /// Component(s).
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// -----------------------------------------------------------------------------
    public class CleanupComponentWriter
    {
        private readonly SortedList<string, InstallFile> files;
        private string basePath;

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="CleanupComponentWriter"/> class.
        /// Constructs the ContainerComponentWriter.
        /// </summary>
        /// <param name="basePath">Base Path.</param>
        /// <param name="files">A Dictionary of files.</param>
        /// -----------------------------------------------------------------------------
        public CleanupComponentWriter(string basePath, SortedList<string, InstallFile> files)
        {
            this.files = files;
            this.basePath = basePath;
        }

        public virtual void WriteManifest(XmlWriter writer)
        {
            foreach (KeyValuePair<string, InstallFile> kvp in this.files)
            {
                // Start component Element
                writer.WriteStartElement("component");
                writer.WriteAttributeString("type", "Cleanup");
                writer.WriteAttributeString("fileName", kvp.Value.Name);
                writer.WriteAttributeString("version", Path.GetFileNameWithoutExtension(kvp.Value.Name));

                // End component Element
                writer.WriteEndElement();
            }
        }
    }
}


text:
module.exports = {
  up: function(migration, DataTypes, done) {
    // add altering commands here, calling 'done' when finished
     migration.createTable(
  'countries',
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    createdAt: {
      type: DataTypes.DATE
    },
    updatedAt: {
      type: DataTypes.DATE
    },
    name: DataTypes.STRING
  }
)
    done()
  },
  down: function(migration, DataTypes, done) {
    // add reverting commands here, calling 'done' when finished
    migration.dropTable('countries');
    done()
  }
}


text:
package ubic.gemma.core.apps;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.compass.gps.spi.CompassGpsInterfaceDevice;
import ubic.gemma.core.apps.GemmaCLI.CommandGroup;
import ubic.gemma.core.util.AbstractCLI;
import ubic.gemma.core.util.AbstractCLIContextCLI;
import ubic.gemma.persistence.util.CompassUtils;

/**
 * Simple command line to index the gemma db. Can index gene's, Expression experiments or array Designs
 *
 * @author klc
 */
public class IndexGemmaCLI extends AbstractCLIContextCLI {

    private boolean indexAD = false;
    private boolean indexB = false;
    private boolean indexEE = false;
    private boolean indexG = false;
    private boolean indexP = false;
    private boolean indexQ = false;
    private boolean indexX = false;
    private boolean indexY = false;

    @Override
    public CommandGroup getCommandGroup() {
        return CommandGroup.SYSTEM;
    }

    @Override
    public String getCommandName() {
        return "searchIndex";
    }

    @SuppressWarnings("static-access")
    @Override
    protected void buildOptions( Options options ) {
        Option geneOption = Option.builder( "g" ).desc( "Index genes" ).longOpt( "genes" ).build();
        options.addOption( geneOption );

        Option eeOption = Option.builder( "g" ).desc( "Index Expression Experiments" )
                .longOpt( "ExpressionExperiments" ).build();
        options.addOption( eeOption );

        Option adOption = Option.builder( "a" ).desc( "Index Array Designs" ).longOpt( "ArrayDesigns" )
                .build();
        options.addOption( adOption );

        Option bibliographicOption = Option.builder( "b" ).desc( "Index Bibliographic References" )
                .longOpt( "Bibliographic" ).build();
        options.addOption( bibliographicOption );

        Option probeOption = Option.builder( "s" ).desc( "Index probes" ).longOpt( "probes" ).build();
        options.addOption( probeOption );

        Option sequenceOption = Option.builder( "q" ).desc( "Index sequences" ).longOpt( "sequences" )
                .build();
        options.addOption( sequenceOption );

        options.addOption( Option.builder( "x" ).desc( "Index EE sets" ).longOpt( "eesets" ).build() );

        options.addOption( Option.builder( "y" ).desc( "Index gene sets" ).longOpt( "genesets" ).build() );
    }

    @Override
    protected void doWork() throws Exception {
        /*
         * These beans are defined in Spring XML.
         */
        if ( this.indexG ) {
            this.rebuildIndex( this.getBean( "geneGps", CompassGpsInterfaceDevice.class ), "Gene index" );
        }
        if ( this.indexEE ) {
            this.rebuildIndex( this.getBean( "expressionGps", CompassGpsInterfaceDevice.class ),
                    "Expression Experiment index" );
        }
        if ( this.indexAD ) {
            this.rebuildIndex( this.getBean( "arrayGps", CompassGpsInterfaceDevice.class ), "Array Design index" );
        }
        if ( this.indexB ) {
            this.rebuildIndex( this.getBean( "bibliographicGps", CompassGpsInterfaceDevice.class ),
                    "Bibliographic Reference Index" );
        }
        if ( this.indexP ) {
            this.rebuildIndex( this.getBean( "probeGps", CompassGpsInterfaceDevice.class ),
                    "Probe Reference Index" );
        }
        if ( this.indexQ ) {
            this.rebuildIndex( this.getBean( "biosequenceGps", CompassGpsInterfaceDevice.class ),
                    "BioSequence Index" );
        }

        if ( this.indexY ) {
            this.rebuildIndex( this.getBean( "experimentSetGps", CompassGpsInterfaceDevice.class ),
                    "Experiment set Index" );
        }

        if ( this.indexX ) {
            this.rebuildIndex( this.getBean( "geneSetGps", CompassGpsInterfaceDevice.class ), "Gene set Index" );
        }
    }

    @Override
    public String getShortDesc() {
        return "Create or update the searchable indexes for a Gemma production system";
    }

    @Override
    protected void processOptions( CommandLine commandLine ) {
        if ( commandLine.hasOption( 'e' ) )
            indexEE = true;

        if ( commandLine.hasOption( 'a' ) )
            indexAD = true;

        if ( commandLine.hasOption( 'g' ) )
            indexG = true;

        if ( commandLine.hasOption( 'b' ) )
            indexB = true;

        if ( commandLine.hasOption( 's' ) )
            indexP = true;

        if ( commandLine.hasOption( 'q' ) )
            indexQ = true;
        if ( commandLine.hasOption( 'x' ) )
            indexX = true;
        if ( commandLine.hasOption( 'y' ) )
            indexY = true;

    }

    private void rebuildIndex( CompassGpsInterfaceDevice device, String whatIndexingMsg ) {

        long time = System.currentTimeMillis();

        AbstractCLI.log.info( "Rebuilding " + whatIndexingMsg );
        CompassUtils.rebuildCompassIndex( device );
        time = System.currentTimeMillis() - time;

        AbstractCLI.log.info( "Finished rebuilding " + whatIndexingMsg + ".  Took (ms): " + time );
        AbstractCLI.log.info( " \n " );

    }
}


text:
require 'spec_helper'

describe Enscalator::Plugins::VPCPeeringConnection do
  describe '#parameter_vpc_id' do
    let(:test_param_name) { 'somename' }
    let(:test_param_description) { 'this is somename parameter' }
    let(:test_param_vpc_id) { 'vpc-12345678' }
    let(:template_fixture) do
      gen_richtemplate('sometemplate'.humanize, Enscalator::RichTemplateDSL, [described_class], &proc {})
    end
    let(:cmd_opts) { default_cmd_opts(template_fixture.name, template_fixture.name.underscore) }

    context 'when vpc id is given' do
      it 'uses all fields to generate parameter' do
        test_template = template_fixture.new(cmd_opts)
        dict = test_template.instance_variable_get(:@dict)
        expect(dict).to be_empty

        test_template.parameter_vpc_id(test_param_name, test_param_description, test_param_vpc_id)
        expect(dict).to include(:Parameters)
        expect(dict[:Parameters]).to include(test_param_name)
        test_params = dict[:Parameters][test_param_name]
        expect(test_params[:Description]).to eq(test_param_description)
        expect(test_params[:Default]).to eq(test_param_vpc_id)
      end
    end

    context 'when vpc id is not given' do
      it 'uses only name and description to generate parameter' do
        test_template = template_fixture.new(cmd_opts)
        dict = test_template.instance_variable_get(:@dict)
        expect(dict).to be_empty

        test_template.parameter_vpc_id(test_param_name, test_param_description)
        expect(dict[:Parameters][test_param_name]).not_to include(:Default)
      end
    end
  end

  describe '#vpc_peering_init' do
    let(:conn_name) { 'test_conn' }

    context 'when default invoked with default parameters' do
      let(:template_fixture) do
        vpc_peering_test_conn_name = conn_name
        vpc_peering_test_template_name = conn_name.humanize.delete(' ')
        gen_richtemplate(vpc_peering_test_template_name,
                         Enscalator::RichTemplateDSL,
                         [described_class]) do
          mock_availability_zones
          vpc_peering_init(vpc_peering_test_conn_name)
        end
      end

      it 'creates template for VPC Peering Connection' do
        cmd_opts = default_cmd_opts(template_fixture.name, template_fixture.name.underscore)
        vpc_peering_template = template_fixture.new(cmd_opts)
        dict = vpc_peering_template.instance_variable_get(:@dict)

        resource_under_test = dict[:Resources]
        expect(resource_under_test).to include(conn_name)
        expect(resource_under_test[conn_name][:Type]).to eq('AWS::EC2::VPCPeeringConnection')
        resource_props = resource_under_test[conn_name][:Properties]
        expected_props = {
          VpcId: ref("#{conn_name}VpcId"),
          PeerVpcId: ref("#{conn_name}PeerVpcId")
        }
        expect { expected_props.fetch(:Tags) }.to raise_error(KeyError)
        expect(resource_props).to include(expected_props)
      end
    end

    context 'when custom tags' do
      let(:tags) do
        [
          {
            Key: 'TestKey',
            Value: 'TestValue'
          }
        ]
      end
      let(:template_fixture) do
        vpc_peering_test_conn_name = conn_name
        vpc_peering_test_template_name = conn_name.humanize.delete(' ')
        vpc_peering_test_tags = tags
        gen_richtemplate(vpc_peering_test_template_name,
                         Enscalator::RichTemplateDSL,
                         [described_class]) do
          mock_availability_zones
          vpc_peering_init(vpc_peering_test_conn_name, tags: vpc_peering_test_tags)
        end
      end

      it 'creates template with custom tags included' do
        cmd_opts = default_cmd_opts(template_fixture.name, template_fixture.name.underscore)
        vpc_peering_template = template_fixture.new(cmd_opts)
        dict = vpc_peering_template.instance_variable_get(:@dict)
        resource_under_test = dict[:Resources]
        expect(resource_under_test[conn_name][:Properties][:Tags]).to include(*tags)
      end
    end
  end
end


text:
class CountAllocDealloc {
  public:
      CountAllocDealloc(int* alloc_count, int* dealloc_count)
          : _alloc_count(alloc_count), _dealloc_count(dealloc_count) {
        (*_alloc_count)++;
      }
      ~CountAllocDealloc() {
        (*_dealloc_count)++;
      }
  private:
    int* _alloc_count;
    int* _dealloc_count;
};

template<typename T>
struct FreePtr {
  void operator()( T * t ) noexcept
  {
    if(t != nullptr) {
      delete t;
      t=nullptr;
    }
  }
};


text:
package com.alibaba.nacos.api.exception.runtime;

/**
 * Nacos load exception.
 *
 * @author hujun
 */
public class NacosLoadException extends RuntimeException {

    private static final long serialVersionUID = 3513491993982295562L;

    public NacosLoadException(String errMsg) {
        super(errMsg);
    }

}


text:
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var sio = require('socket.io');
var SioSocket = require('./siosocket');

var PKG_ID_BYTES = 4;
var PKG_ROUTE_LENGTH_BYTES = 1;
var PKG_HEAD_BYTES = PKG_ID_BYTES + PKG_ROUTE_LENGTH_BYTES;

var curId = 1;

/**
 * Connector that manager low level connection and protocol bewteen server and client.
 * Develper can provide their own connector to switch the low level prototol, such as tcp or probuf.
 */
var Connector = function(port, host, opts) {
  if (!(this instanceof Connector)) {
    return new Connector(port, host, opts);
  }

  EventEmitter.call(this);
  this.port = port;
  this.host = host;
  this.opts = opts;
};

util.inherits(Connector, EventEmitter);

module.exports = Connector;

/**
 * Start connector to listen the specified port
 */
Connector.prototype.start = function(cb) {
  var self = this;
  // issue https://github.com/NetEase/pomelo-cn/issues/174
  if(!!this.opts.transports) {
    this.wsocket = sio.listen(this.port, this.opts.transports);
  }
  else {
    this.wsocket = sio.listen(this.port, {
      transports: [
      'websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling', 'flashsocket'
      ]
    });
  }
  this.wsocket.set('log level', 1);
  this.wsocket.sockets.on('connection', function (socket) {
    var siosocket = new SioSocket(curId++, socket);
    self.emit('connection', siosocket);
    siosocket.on('closing', function(reason) {
      siosocket.send({route: 'onKick', reason: reason});
    });
  });

  process.nextTick(cb);
};

/**
 * Stop connector
 */
Connector.prototype.stop = function(force, cb) {
  this.wsocket.server.close();
  process.nextTick(cb);
};

Connector.encode = Connector.prototype.encode = function(reqId, route, msg) {
  if(reqId) {
    return composeResponse(reqId, route, msg);
  } else {
    return composePush(route, msg);
  }
};

/**
 * Decode client message package.
 *
 * Package format:
 *   message id: 4bytes big-endian integer
 *   route length: 1byte
 *   route: route length bytes
 *   body: the rest bytes
 *
 * @param  {String} data socket.io package from client
 * @return {Object}      message object
 */
Connector.decode = Connector.prototype.decode = function(msg) {
  var index = 0;

  var id = parseIntField(msg, index, PKG_ID_BYTES);
  index += PKG_ID_BYTES;

  var routeLen = parseIntField(msg, index, PKG_ROUTE_LENGTH_BYTES);

  var route = msg.substr(PKG_HEAD_BYTES, routeLen);
  var body = msg.substr(PKG_HEAD_BYTES + routeLen);

  return {
    id: id,
    route: route,
    body: JSON.parse(body)
  };
};

var composeResponse = function(msgId, route, msgBody) {
  return {
    id: msgId,
    body: msgBody
  };
};

var composePush = function(route, msgBody) {
  return JSON.stringify({route: route, body: msgBody});
};

var parseIntField = function(str, offset, len) {
  var res = 0;
  for(var i=0; i<len; i++) {
    if(i > 0) {
      res <<= 8;
    }
    res |= str.charCodeAt(offset + i) & 0xff;
  }

  return res;
};


text:
<?php
/**
 * Stores site-side plugin settings as private data.
 *
 * This class is currently a stub, allowing a plugin to
 * save settings in an object's private settings for each site.
 *
 * @package    Elgg.Core
 * @subpackage Plugins.Settings
 */
class ElggPlugin extends \ElggObject {
	private $package;
	private $manifest;

	private $path;
	private $errorMsg = '';

	/**
	 * Set subtype to 'plugin'
	 *
	 * @return void
	 */
	protected function initializeAttributes() {
		parent::initializeAttributes();

		$this->attributes['subtype'] = "plugin";

		// plugins must be public.
		$this->access_id = ACCESS_PUBLIC;
	}

	/**
	 * Creates a new plugin from path
	 *
	 * @note Internal: also supports database objects
	 *
	 * @warning Unlike other \ElggEntity objects, you cannot null instantiate
	 *          \ElggPlugin. You must provide the path to the plugin directory.
	 *
	 * @param string $path The absolute path of the plugin
	 *
	 * @throws PluginException
	 */
	public function __construct($path) {
		if (!$path) {
			throw new \PluginException("ElggPlugin cannot be null instantiated. You must pass a full path.");
		}

		if (is_object($path)) {
			// database object
			parent::__construct($path);
			$this->path = _elgg_services()->config->getPluginsPath() . $this->getID();
		} else if (is_numeric($path)) {
			// guid
			// @todo plugins with directory names of '12345'
			elgg_deprecated_notice("Use elgg_get_plugin_from_id() to load a plugin.", 1.9);
			parent::__construct($path);
			$this->path = _elgg_services()->config->getPluginsPath() . $this->getID();
		} else {
			$this->initializeAttributes();

			$mod_dir = _elgg_services()->config->getPluginsPath();

			// not a full path, so assume a directory name and use the default path
			if (strpos($path, $mod_dir) !== 0) {
				elgg_deprecated_notice("You should pass a full path to ElggPlugin.", 1.9);
				$path = $mod_dir . $path;
			}

			// path checking is done in the package
			$path = sanitise_filepath($path);
			$this->path = $path;
			$path_parts = explode('/', rtrim($path, '/'));
			$plugin_id = array_pop($path_parts);
			$this->title = $plugin_id;

			// check if we're loading an existing plugin
			$existing_plugin = elgg_get_plugin_from_id($plugin_id);

			if ($existing_plugin) {
				$this->load($existing_plugin->guid);
			}
		}

		_elgg_cache_plugin_by_id($this);
	}

	/**
	 * Save the plugin object.  Make sure required values exist.
	 *
	 * @see \ElggObject::save()
	 * @return bool
	 */
	public function save() {
		// own by the current site so users can be deleted without affecting plugins
		$site = _elgg_services()->configTable->get('site');
		$this->attributes['site_guid'] = $site->guid;
		$this->attributes['owner_guid'] = $site->guid;
		$this->attributes['container_guid'] = $site->guid;

		if (parent::save()) {
			// make sure we have a priority
			$priority = $this->getPriority();
			if ($priority === false || $priority === null) {
				return $this->setPriority('last');
			}
		} else {
			return false;
		}
	}

	// Plugin ID and path

	/**
	 * Returns the ID (dir name) of this plugin
	 *
	 * @return string
	 */
	public function getID() {
		return $this->title;
	}

	/**
	 * Returns the manifest's name if available, otherwise the ID.
	 *
	 * @return string
	 * @since 1.8.1
	 */
	public function getFriendlyName() {
		$manifest = $this->getManifest();
		if ($manifest) {
			return $manifest->getName();
		}

		return $this->getID();
	}

	/**
	 * Returns the plugin's full path with trailing slash.
	 *
	 * @return string
	 */
	public function getPath() {
		return sanitise_filepath($this->path);
	}

	/**
	 * Sets the location of this plugin.
	 *
	 * @param string $id The path to the plugin's dir.
	 * @return bool
	 */
	public function setID($id) {
		return $this->attributes['title'] = $id;
	}

	/**
	 * Returns an array of available markdown files for this plugin
	 *
	 * @return array
	 */
	public function getAvailableTextFiles() {
		$filenames = $this->getPackage()->getTextFilenames();

		$files = array();
		foreach ($filenames as $filename) {
			if ($this->canReadFile($filename)) {
				$files[$filename] = "$this->path/$filename";
			}
		}

		return $files;
	}

	// Load Priority

	/**
	 * Gets the plugin's load priority.
	 *
	 * @return int
	 */
	public function getPriority() {
		$name = _elgg_namespace_plugin_private_setting('internal', 'priority');
		return $this->$name;
	}

	/**
	 * Sets the priority of the plugin
	 *
	 * @param mixed $priority  The priority to set. One of +1, -1, first, last, or a number.
	 *                         If given a number, this will displace all plugins at that number
	 *                         and set their priorities +1
	 * @param mixed $site_guid Optional site GUID.
	 * @return bool
	 */
	public function setPriority($priority, $site_guid = null) {
		if (!$this->guid) {
			return false;
		}

		$db_prefix = _elgg_services()->configTable->get('dbprefix');
		$name = _elgg_namespace_plugin_private_setting('internal', 'priority');
		// if no priority assume a priority of 1
		$old_priority = (int) $this->getPriority();
		$old_priority = (!$old_priority) ? 1 : $old_priority;
		$max_priority = _elgg_get_max_plugin_priority();

		// can't use switch here because it's not strict and
		// php evaluates +1 == 1
		if ($priority === '+1') {
			$priority = $old_priority + 1;
		} elseif ($priority === '-1') {
			$priority = $old_priority - 1;
		} elseif ($priority === 'first') {
			$priority = 1;
		} elseif ($priority === 'last') {
			$priority = $max_priority;
		}

		// should be a number by now
		if ($priority > 0) {
			if (!is_numeric($priority)) {
				return false;
			}

			// there's nothing above the max.
			if ($priority > $max_priority) {
				$priority = $max_priority;
			}

			// there's nothing below 1.
			if ($priority < 1) {
				$priority = 1;
			}

			if ($priority > $old_priority) {
				$op = '-';
				$where = "CAST(value as unsigned) BETWEEN $old_priority AND $priority";
			} else {
				$op = '+';
				$where = "CAST(value as unsigned) BETWEEN $priority AND $old_priority";
			}

			// displace the ones affected by this change
			$q = "UPDATE {$db_prefix}private_settings
				SET value = CAST(value as unsigned) $op 1
				WHERE entity_guid != $this->guid
				AND name = '$name'
				AND $where";

			if (!$this->getDatabase()->updateData($q)) {
				return false;
			}

			// set this priority
			if ($this->setPrivateSetting($name, $priority)) {
				return true;
			} else {
				return false;
			}
		}

		return false;
	}

	// Plugin settings

	/**
	 * Returns a plugin setting
	 *
	 * @param string $name    The setting name
	 * @param mixed  $default The default value to return if none is set
	 * @return mixed
	 */
	public function getSetting($name, $default = null) {
		$val = $this->$name;
		return $val !== null ? $val : $default;
	}

	/**
	 * Returns an array of all settings saved for this plugin.
	 *
	 * @note Unlike user settings, plugin settings are not namespaced.
	 *
	 * @return array An array of key/value pairs.
	 */
	public function getAllSettings() {
		if (!$this->guid) {
			return false;
		}

		$db_prefix = _elgg_services()->config->get('dbprefix');
		// need to remove all namespaced private settings.
		$us_prefix = _elgg_namespace_plugin_private_setting('user_setting', '', $this->getID());
		$is_prefix = _elgg_namespace_plugin_private_setting('internal', '', $this->getID());

		// Get private settings for user
		$q = "SELECT * FROM {$db_prefix}private_settings
			WHERE entity_guid = $this->guid
			AND name NOT LIKE '$us_prefix%'
			AND name NOT LIKE '$is_prefix%'";

		$private_settings = $this->getDatabase()->getData($q);

		$return = array();

		if ($private_settings) {
			foreach ($private_settings as $setting) {
				$return[$setting->name] = $setting->value;
			}
		}

		return $return;
	}

	/**
	 * Set a plugin setting for the plugin
	 *
	 * @todo This will only work once the plugin has a GUID.
	 *
	 * @param string $name  The name to set
	 * @param string $value The value to set
	 *
	 * @return bool
	 */
	public function setSetting($name, $value) {
		if (!$this->guid) {
			return false;
		}

		// Hook to validate setting
		$value = elgg_trigger_plugin_hook('setting', 'plugin', array(
			'plugin_id' => $this->getID(),
			'plugin' => $this,
			'name' => $name,
			'value' => $value,
		), $value);

		return $this->setPrivateSetting($name, $value);
	}

	/**
	 * Removes a plugin setting name and value.
	 *
	 * @param string $name The setting name to remove
	 *
	 * @return bool
	 */
	public function unsetSetting($name) {
		return remove_private_setting($this->guid, $name);
	}

	/**
	 * Removes all settings for this plugin.
	 *
	 * @todo Should be a better way to do this without dropping to raw SQL.
	 * @todo If we could namespace the plugin settings this would be cleaner.
	 * @todo this shouldn't work because ps_prefix will be empty string
	 * @return bool
	 */
	public function unsetAllSettings() {
		$db_prefix = _elgg_services()->configTable->get('dbprefix');
		$us_prefix = _elgg_namespace_plugin_private_setting('user_setting', '', $this->getID());
		$is_prefix = _elgg_namespace_plugin_private_setting('internal', '', $this->getID());

		$q = "DELETE FROM {$db_prefix}private_settings
			WHERE entity_guid = $this->guid
			AND name NOT LIKE '$us_prefix%'
			AND name NOT LIKE '$is_prefix%'";

		return $this->getDatabase()->deleteData($q);
	}

	// User settings

	/**
	 * Returns a user's setting for this plugin
	 *
	 * @param string $name      The setting name
	 * @param int    $user_guid The user GUID
	 * @param mixed  $default   The default value to return if none is set
	 *
	 * @return mixed The setting string value, the default value or false if there is no user
	 */
	public function getUserSetting($name, $user_guid = 0, $default = null) {
		$user_guid = (int)$user_guid;

		if ($user_guid) {
			$user = get_entity($user_guid);
		} else {
			$user = _elgg_services()->session->getLoggedInUser();
		}

		if (!($user instanceof \ElggUser)) {
			return false;
		}

		$name = _elgg_namespace_plugin_private_setting('user_setting', $name, $this->getID());

		$val = get_private_setting($user->guid, $name);
		return $val !== null ? $val : $default;
	}

	/**
	 * Returns an array of all user settings saved for this plugin for the user.
	 *
	 * @note Plugin settings are saved with a prefix. This removes that prefix.
	 *
	 * @param int $user_guid The user GUID. Defaults to logged in.
	 * @return array An array of key/value pairs.
	 */
	public function getAllUserSettings($user_guid = 0) {
		$user_guid = (int)$user_guid;

		if ($user_guid) {
			$user = get_entity($user_guid);
		} else {
			$user = _elgg_services()->session->getLoggedInUser();
		}

		if (!($user instanceof \ElggUser)) {
			return false;
		}

		$db_prefix = _elgg_services()->config->get('dbprefix');
		// send an empty name so we just get the first part of the namespace
		$ps_prefix = _elgg_namespace_plugin_private_setting('user_setting', '', $this->getID());
		$ps_prefix_len = strlen($ps_prefix);

		// Get private settings for user
		$q = "SELECT * FROM {$db_prefix}private_settings
			WHERE entity_guid = {$user->guid}
			AND name LIKE '$ps_prefix%'";

		$private_settings = $this->getDatabase()->getData($q);

		$return = array();

		if ($private_settings) {
			foreach ($private_settings as $setting) {
				$name = substr($setting->name, $ps_prefix_len);
				$value = $setting->value;

				$return[$name] = $value;
			}
		}

		return $return;
	}

	/**
	 * Sets a user setting for a plugin
	 *
	 * @param string $name      The setting name
	 * @param string $value     The setting value
	 * @param int    $user_guid The user GUID
	 *
	 * @return mixed The new setting ID or false
	 */
	public function setUserSetting($name, $value, $user_guid = 0) {
		$user_guid = (int)$user_guid;

		if ($user_guid) {
			$user = get_entity($user_guid);
		} else {
			$user = _elgg_services()->session->getLoggedInUser();
		}

		if (!($user instanceof \ElggUser)) {
			return false;
		}

		// Hook to validate setting
		// note: this doesn't pass the namespaced name
		$value = _elgg_services()->hooks->trigger('usersetting', 'plugin', array(
			'user' => $user,
			'plugin' => $this,
			'plugin_id' => $this->getID(),
			'name' => $name,
			'value' => $value
		), $value);

		// set the namespaced name.
		$name = _elgg_namespace_plugin_private_setting('user_setting', $name, $this->getID());

		return set_private_setting($user->guid, $name, $value);
	}

	/**
	 * Removes a user setting name and value.
	 *
	 * @param string $name      The user setting name
	 * @param int    $user_guid The user GUID
	 * @return bool
	 */
	public function unsetUserSetting($name, $user_guid = 0) {
		$user_guid = (int)$user_guid;

		if ($user_guid) {
			$user = get_entity($user_guid);
		} else {
			$user = _elgg_services()->session->getLoggedInUser();
		}

		if (!($user instanceof \ElggUser)) {
			return false;
		}

		// set the namespaced name.
		$name = _elgg_namespace_plugin_private_setting('user_setting', $name, $this->getID());

		return remove_private_setting($user->guid, $name);
	}

	/**
	 * Removes all User Settings for this plugin for a particular user
	 *
	 * Use {@link removeAllUsersSettings()} to remove all user
	 * settings for all users.  (Note the plural 'Users'.)
	 *
	 * @warning 0 does not equal logged in user for this method!
	 * @todo fix that
	 *
	 * @param int $user_guid The user GUID to remove user settings.
	 * @return bool
	 */
	public function unsetAllUserSettings($user_guid) {
		$db_prefix = _elgg_services()->configTable->get('dbprefix');
		$ps_prefix = _elgg_namespace_plugin_private_setting('user_setting', '', $this->getID());

		$q = "DELETE FROM {$db_prefix}private_settings
			WHERE entity_guid = $user_guid
			AND name LIKE '$ps_prefix%'";

		return $this->getDatabase()->deleteData($q);
	}

	/**
	 * Removes this plugin's user settings for all users.
	 *
	 * Use {@link removeAllUserSettings()} if you just want to remove
	 * settings for a single user.
	 *
	 * @return bool
	 */
	public function unsetAllUsersSettings() {
		$db_prefix = _elgg_services()->configTable->get('dbprefix');
		$ps_prefix = _elgg_namespace_plugin_private_setting('user_setting', '', $this->getID());

		$q = "DELETE FROM {$db_prefix}private_settings
			WHERE name LIKE '$ps_prefix%'";

		return $this->getDatabase()->deleteData($q);
	}

	// validation

	/**
	 * Returns if the plugin is complete, meaning has all required files
	 * and Elgg can read them and they make sense.
	 *
	 * @todo bad name? This could be confused with isValid() from \ElggPluginPackage.
	 *
	 * @return bool
	 */
	public function isValid() {
		if (!$this->getID()) {
			$this->errorMsg = _elgg_services()->translator->translate('ElggPlugin:MissingID', array($this->guid));
			return false;
		}

		if (!$this->getPackage() instanceof \ElggPluginPackage) {
			$this->errorMsg = _elgg_services()->translator->translate('ElggPlugin:NoPluginPackagePackage', array($this->getID(), $this->guid));
			return false;
		}

		if (!$this->getPackage()->isValid()) {
			$this->errorMsg = $this->getPackage()->getError();
			return false;
		}

		return true;
	}

	/**
	 * Is this plugin active?
	 *
	 * @param int $site_guid Optional site guid.
	 * @return bool
	 */
	public function isActive($site_guid = null) {
		if (!$this->guid) {
			return false;
		}

		if ($site_guid) {
			$site = get_entity($site_guid);
		} else {
			$site = _elgg_services()->configTable->get('site');
		}

		if (!($site instanceof \ElggSite)) {
			return false;
		}

		return check_entity_relationship($this->guid, 'active_plugin', $site->guid);
	}

	/**
	 * Checks if this plugin can be activated on the current
	 * Elgg installation.
	 *
	 * @todo remove $site_guid param or implement it
	 *
	 * @param mixed $site_guid Optional site guid
	 * @return bool
	 */
	public function canActivate($site_guid = null) {
		if ($this->getPackage()) {
			$result = $this->getPackage()->isValid() && $this->getPackage()->checkDependencies();
			if (!$result) {
				$this->errorMsg = $this->getPackage()->getError();
			}

			return $result;
		}

		return false;
	}

	// activating and deactivating

	/**
	 * Actives the plugin for the current site.
	 *
	 * @param mixed $site_guid Optional site GUID.
	 * @return bool
	 */
	public function activate($site_guid = null) {
		if ($this->isActive($site_guid)) {
			return false;
		}

		if (!$this->canActivate()) {
			return false;
		}

		// set in the db, now perform tasks and emit events
		if ($this->setStatus(true, $site_guid)) {
			// emit an event. returning false will make this not be activated.
			// we need to do this after it's been fully activated
			// or the deactivate will be confused.
			$params = array(
				'plugin_id' => $this->getID(),
				'plugin_entity' => $this,
			);

			$return = _elgg_services()->events->trigger('activate', 'plugin', $params);

			// if there are any on_enable functions, start the plugin now and run them
			// Note: this will not run re-run the init hooks!
			if ($return) {
				if ($this->canReadFile('activate.php')) {
					$flags = ELGG_PLUGIN_INCLUDE_START | ELGG_PLUGIN_REGISTER_CLASSES |
							ELGG_PLUGIN_REGISTER_LANGUAGES | ELGG_PLUGIN_REGISTER_VIEWS;

					$this->start($flags);

					$return = $this->includeFile('activate.php');
				}
			}

			if ($return === false) {
				$this->deactivate($site_guid);
			}

			return $return;
		}

		return false;
	}

	/**
	 * Deactivates the plugin.
	 *
	 * @param mixed $site_guid Optional site GUID.
	 * @return bool
	 */
	public function deactivate($site_guid = null) {
		if (!$this->isActive($site_guid)) {
			return false;
		}

		// emit an event. returning false will cause this to not be deactivated.
		$params = array(
			'plugin_id' => $this->getID(),
			'plugin_entity' => $this,
		);

		$return = _elgg_services()->events->trigger('deactivate', 'plugin', $params);

		// run any deactivate code
		if ($return) {
			if ($this->canReadFile('deactivate.php')) {
				$return = $this->includeFile('deactivate.php');
			}
		}

		if ($return === false) {
			return false;
		} else {
			return $this->setStatus(false, $site_guid);
		}
	}

	/**
	 * Start the plugin.
	 *
	 * @param int $flags Start flags for the plugin. See the constants in lib/plugins.php for details.
	 * @return true
	 * @throws PluginException
	 */
	public function start($flags) {
		//if (!$this->canActivate()) {
		//	return false;
		//}

		// include classes
		if ($flags & ELGG_PLUGIN_REGISTER_CLASSES) {
			$this->registerClasses();
		}

		// include start file
		if ($flags & ELGG_PLUGIN_INCLUDE_START) {
			$this->includeFile('start.php');
		}

		// include views
		if ($flags & ELGG_PLUGIN_REGISTER_VIEWS) {
			$this->registerViews();
		}

		// include languages
		if ($flags & ELGG_PLUGIN_REGISTER_LANGUAGES) {
			$this->registerLanguages();
		}

		return true;
	}

	// start helpers

	/**
	 * Get the config object in a deprecation wrapper
	 *
	 * @return \Elgg\DeprecationWrapper
	 */
	protected static function getConfigWrapper() {
		static $wrapper;
		if (null === $wrapper) {
			global $CONFIG;
			$warning = 'Do not rely on local $CONFIG being available in start.php';
			$wrapper = new \Elgg\DeprecationWrapper($CONFIG, $warning, "1.10");
		}
		return $wrapper;
	}

	/**
	 * Includes one of the plugins files
	 *
	 * @param string $filename The name of the file
	 *
	 * @throws PluginException
	 * @return mixed The return value of the included file (or 1 if there is none)
	 */
	protected function includeFile($filename) {
		// This needs to be here to be backwards compatible for 1.0-1.7.
		// They expect the global config object to be available in start.php.
		if ($filename == 'start.php') {
			$CONFIG = self::getConfigWrapper();
		}

		$filepath = "$this->path/$filename";

		if (!$this->canReadFile($filename)) {
			$msg = _elgg_services()->translator->translate('ElggPlugin:Exception:CannotIncludeFile',
							array($filename, $this->getID(), $this->guid, $this->path));
			throw new \PluginException($msg);
		}

		return include $filepath;
	}

	/**
	 * Checks whether a plugin file with the given name exists
	 *
	 * @param string $filename The name of the file
	 * @return bool
	 */
	protected function canReadFile($filename) {
		return is_readable($this->path . '/' . $filename);
	}

	/**
	 * Registers the plugin's views
	 *
	 * @throws PluginException
	 * @return void
	 */
	protected function registerViews() {
		if (!_elgg_services()->views->registerPluginViews($this->path, $failed_dir)) {
			$msg = _elgg_services()->translator->translate('ElggPlugin:Exception:CannotRegisterViews',
				array($this->getID(), $this->guid, $failed_dir));
			throw new \PluginException($msg);
		}
	}

	/**
	 * Registers the plugin's languages
	 *
	 * @throws PluginException
	 * @return true
	 */
	protected function registerLanguages() {
		$languages_path = "$this->path/languages";

		// don't need to have classes
		if (!is_dir($languages_path)) {
			return true;
		}

		// but need to have working ones.
		if (!_elgg_services()->translator->registerTranslations($languages_path)) {
			$msg = _elgg_services()->translator->translate('ElggPlugin:Exception:CannotRegisterLanguages',
							array($this->getID(), $this->guid, $languages_path));
			throw new \PluginException($msg);
		}

		return true;
	}

	/**
	 * Registers the plugin's classes
	 *
	 * @throws PluginException
	 * @return true
	 */
	protected function registerClasses() {
		$classes_path = "$this->path/classes";

		if (is_dir($classes_path)) {
			_elgg_services()->autoloadManager->addClasses($classes_path);
		}

		return true;
	}

	/**
	 * Get an attribute or private setting value
	 *
	 * @param string $name Name of the attribute or private setting
	 * @return mixed
	 */
	public function __get($name) {
		// rewrite for old and inaccurate plugin:setting
		if (strstr($name, 'plugin:setting:')) {
			$msg = 'Direct access of user settings is deprecated. Use ElggPlugin->getUserSetting()';
			elgg_deprecated_notice($msg, 1.8);
			$name = str_replace('plugin:setting:', '', $name);
			$name = _elgg_namespace_plugin_private_setting('user_setting', $name, $this->getID());
		}

		// See if its in our base attribute
		if (array_key_exists($name, $this->attributes)) {
			return $this->attributes[$name];
		}

		// @todo clean below - getPrivateSetting() should return null now
		// No, so see if its in the private data store.
		// get_private_setting() returns false if it doesn't exist
		$meta = $this->getPrivateSetting($name);

		if ($meta === false) {
			// Can't find it, so return null
			return null;
		}

		return $meta;
	}

	/**
	 * Get a value from private settings.
	 *
	 * @param string $name Name
	 * @return mixed
	 * @deprecated 1.9
	 */
	public function get($name) {
		elgg_deprecated_notice("Use -> instead of get()", 1.9);
		return $this->__get($name);
	}

	/**
	 * Set a value as private setting or attribute.
	 *
	 * Attributes include title and description.
	 *
	 * @param string $name  Name of the attribute or private_setting
	 * @param mixed  $value Value to be set
	 * @return void
	 */
	public function __set($name, $value) {
		if (array_key_exists($name, $this->attributes)) {
			// Check that we're not trying to change the guid!
			if ((array_key_exists('guid', $this->attributes)) && ($name == 'guid')) {
				return;
			}

			$this->attributes[$name] = $value;
		} else {
			// to make sure we trigger the correct hooks
			$this->setSetting($name, $value);
		}
	}

	/**
	 * Save a value as private setting or attribute.
	 *
	 * Attributes include title and description.
	 *
	 * @param string $name  Name
	 * @param mixed  $value Value
	 * @return bool
	 */
	public function set($name, $value) {
		elgg_deprecated_notice("Use -> instead of set()", 1.9);
		$this->__set($name, $value);

		return true;
	}

	/**
	 * Sets the plugin to active or inactive for $site_guid.
	 *
	 * @param bool  $active    Set to active or inactive
	 * @param mixed $site_guid Int for specific site, null for current site.
	 *
	 * @return bool
	 */
	private function setStatus($active, $site_guid = null) {
		if (!$this->guid) {
			return false;
		}

		if ($site_guid) {
			$site = get_entity($site_guid);

			if (!($site instanceof \ElggSite)) {
				return false;
			}
		} else {
			$site = _elgg_services()->configTable->get('site');
		}

		if ($active) {
			$result = add_entity_relationship($this->guid, 'active_plugin', $site->guid);
		} else {
			$result = remove_entity_relationship($this->guid, 'active_plugin', $site->guid);
		}

		_elgg_invalidate_plugins_provides_cache();

		return $result;
	}

	/**
	 * Returns the last error message registered.
	 *
	 * @return string|null
	 */
	public function getError() {
		return $this->errorMsg;
	}

	/**
	 * Returns this plugin's \ElggPluginManifest object
	 *
	 * @return \ElggPluginManifest
	 */
	public function getManifest() {
		if ($this->manifest instanceof \ElggPluginManifest) {
			return $this->manifest;
		}

		try {
			$this->manifest = $this->getPackage()->getManifest();
		} catch (Exception $e) {
			_elgg_services()->logger->warn("Failed to load manifest for plugin $this->guid. " . $e->getMessage());
			$this->errorMsg = $e->getmessage();
		}

		return $this->manifest;
	}

	/**
	 * Returns this plugin's \ElggPluginPackage object
	 *
	 * @return \ElggPluginPackage
	 */
	public function getPackage() {
		if ($this->package instanceof \ElggPluginPackage) {
			return $this->package;
		}

		try {
			$this->package = new \ElggPluginPackage($this->path, false);
		} catch (Exception $e) {
			_elgg_services()->logger->warn("Failed to load package for $this->guid. " . $e->getMessage());
			$this->errorMsg = $e->getmessage();
		}

		return $this->package;
	}
}


text:
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved.							  */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib.  */
/*----------------------------------------------------------------------------*/

#ifndef __INTERNAL_BUTTON_H__
#define __INTERNAL_BUTTON_H__

#include "Buttons/Button.h"

class InternalButton : public Button
{
public:
	InternalButton();
	InternalButton(bool inverted);
	virtual ~InternalButton() {}

	void SetInverted(bool inverted);
	void SetPressed(bool pressed);

	virtual bool Get();

private:
	bool m_pressed;
	bool m_inverted;
};

#endif


text:
'use strict';

/** @const */
var INPUT_DATE_STEP_DEFAULT = 1;

/** @const */
var INPUT_DATE_STEP_SCALE_FACTOR = 86400000;

function inputDateDomValueGet(element) {
  return inputDateGetRfc3339(element);
}

function inputDateDomValueSet(element, value) {
  var date;

  if (value !== '') {
    date = getDateFromRfc3339FullDateString(value);
  }

  if (date) {
    inputDateComponentsSet(element, date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
  }
  else {
    //console.warn("The specified value '" + value + "' does not conform to the required format, 'yyyy-MM-dd'.");
    inputDateComponentsSet(element, INPUT_DATE_YEAR_EMPTY, INPUT_DATE_MONTH_EMPTY, INPUT_DATE_DAY_EMPTY);
  }

  return value;
}

function inputDateDomValueAsDateGet(element) {
  return inputDateGetDate(element);
}

function inputDateDomValueAsDateSet(element, value) {
  inputDateComponentsSet(element, value.getUTCFullYear(), value.getUTCMonth(), value.getUTCDate());
}


text:
// This file is automatically generated.

package adila.db;

/*
 * Vivo V3Max A
 *
 * DEVICE: PD1523
 * MODEL: vivo PD1523A
 */
final class pd1523_vivo20pd1523a {
    public static final String DATA = "Vivo|V3Max A|";
}


text:
import * as path from 'path'
import { runTests } from '@vscode/test-electron'
import { linterValues } from '../linterValues'

async function main (): Promise<void> {
  for (const linter of linterValues) {
    const extensionDevelopmentPath = path.resolve(__dirname, '../../../')
    const extensionTestsPath = path.resolve(__dirname, linter, 'index')
    const testWorkspace = path.resolve(__dirname, '../../testFixture', linter)
    await runTests({
      extensionDevelopmentPath,
      extensionTestsPath,
      launchArgs: [testWorkspace, '--disable-extensions']
    })
  }
}

main().catch(err => {
  console.error(err)
  console.error('Failed to run tests')
  process.exit(1)
})


text:
package de.oliver_heger.linedj

import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.testkit.TestProbe

import scala.language.implicitConversions

/**
  * A module providing support for ''TestProbe''s that can be stopped.
  *
  * The Akka testkit obviously does not like it if test probes are stopped.
  * This can cause strange behavior in test cases executed later, even up to
  * failures of the test actor system. Nevertheless, when testing actors that
  * use death watch for actors they collaborate with, it is useful to have a
  * ''TestProbe'' in place to simulate the collaborator and to stop it to check
  * whether watching is handled correctly.
  *
  * This module solves this problem by introducing a class that mainly combines
  * a ''TestProbe'' with a regular actor. The actor simply forwards all
  * messages it receives to the ''TestProbe''. Its reference is passed to the
  * actor under test. It can also be stopped without affecting the
  * ''TestProbe''.
  */
object StoppableTestProbe {
  /**
    * Creates a new instance of ''StoppableTestProbe''.
    *
    * @param system the actor system
    * @return the ''StoppableTestProbe'' instance
    */
  def apply()(implicit system: ActorSystem): StoppableTestProbe = {
    val probe = TestProbe()
    val forwarder = system.actorOf(Props(new ForwardingActor(probe)))
    new StoppableTestProbe(forwarder, probe)
  }

  /**
    * An implicit conversion from a ''StoppableTestProbe'' to an ''ActorRef''.
    * This function allows treating the probe object as a regular actor.
    *
    * @param probe the ''StoppableTestProbe''
    * @return the ''ActorRef'' of this probe
    */
  implicit def toActorRef(probe: StoppableTestProbe): ActorRef = probe.ref

  /**
    * An implicit conversion from a ''StoppableTestProbe'' to a ''TestProbe''.
    * This function allows applying the typical ''expectXXX()'' functions to an
    * instance without having to reference the probe part.
    *
    * @param probe the ''StoppableTestProbe''
    * @return the ''TestProbe'' of this probe
    */
  implicit def toTestProbe(probe: StoppableTestProbe): TestProbe = probe.probe

  /**
    * An internal actor class that simply forwards all messages to the given
    * ''TestProbe''.
    *
    * @param probe the ''TestProbe'' to forward messages to
    */
  private class ForwardingActor(probe: TestProbe) extends Actor {
    override def receive: Receive = {
      case msg => probe.ref forward msg
    }
  }
}

/**
  * A class representing a ''TestProbe'' that can be stopped safely.
  *
  * @param ref   the ''ActorRef'' to be used for the outside
  * @param probe the ''TestProbe''
  */
class StoppableTestProbe(val ref: ActorRef,
                         val probe: TestProbe) {
  /**
    * Stops the actor of this probe.
    *
    * @param system the actor system
    */
  def stop()(implicit system: ActorSystem): Unit = {
    system stop ref
  }
}


text:
'use strict';

ApplicationConfiguration.registerModule('core');
angular.module('core')
    .config(function(staticRoot, $stateProvider){
        /**
         * PROJECT ROUTES
         *
         * Use `yo djangularjs:angular-route <route-name>` to create new routes
         *
         * NOTE: routes are centralized here to make sure they are processed in the right order
         **/
        var staticPath = function (path) {return staticRoot + path; };
		$stateProvider
            .state('home', {  // main page once logged in
                url: '/',
                templateUrl: staticPath('core/views/core.home.view.html'),
                controller: 'HomeController as ctrl',
                resolve: {
                }
            })
            .state('signin', {
                url: '/signin',
                templateUrl: staticPath('auth/views/auth.signin.view.html'),
                controller: 'SigninController as ctrl',
                resolve: {
                    // Optional: inject stuffs into SigninController from here
                }
            })
            .state('signup', {
                url: '/signup',
                templateUrl: staticPath('auth/views/auth.signup.view.html'),
                controller: 'SignupController as ctrl',
                resolve: {
                    // Optional: inject stuffs into SignupController from here
                }
            })
            /* leave me here */;
    })
    .run(function ($rootScope, $log, format) {
        $rootScope.$on('$stateChangeError',  function(event, toState, toParams, fromState, fromParams, error){
            $log.warn(format('Cannot navigate from {} to {}.\nError: {}', fromState.url, toState.url, error));
        });
    });


text:
using DatabaseCleaner.Properties;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace DatabaseCleaner
{
    public class TableCleaner
    {
        private DbContext context;
        private string tableName;

        public TableCleaner(string tableName, DbContext context)
        {
            this.context = context;
            this.tableName = tableName;
        }

        public List<string> TablesWithForeignKeys()
        {
            string sql = string.Format(Resources.TablesWithKeys, this.tableName);
            return this.context.Database.SqlQuery<string>(sql).ToList();
        }

        public void Clean()
        {
            context.Database.ExecuteSqlCommand(string.Format("DELETE FROM [{0}]", this.tableName));
        }
    }
}


text:
<?php

namespace Symfony\Component\Intl\Data\Generator;

use Symfony\Component\Intl\Data\Bundle\Compiler\BundleCompilerInterface;
use Symfony\Component\Intl\Data\Bundle\Reader\BundleEntryReaderInterface;
use Symfony\Component\Intl\Data\Util\ArrayAccessibleResourceBundle;
use Symfony\Component\Intl\Data\Util\LocaleScanner;
use Symfony\Component\Intl\Exception\RuntimeException;

/**
 * The rule for compiling the region bundle.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 *
 * @see http://source.icu-project.org/repos/icu/icu4j/trunk/main/classes/core/src/com/ibm/icu/util/Region.java
 *
 * @internal
 */
class RegionDataGenerator extends AbstractDataGenerator
{
    /**
     * Source: https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes.
     */
    private static $preferredAlpha2ToAlpha3Mapping = [
        'CD' => 'COD',
        'DE' => 'DEU',
        'FR' => 'FRA',
        'MM' => 'MMR',
        'TL' => 'TLS',
        'YE' => 'YEM',
    ];

    private static $blacklist = [
        // Exceptional reservations
        'AC' => true, // Ascension Island
        'CP' => true, // Clipperton Island
        'DG' => true, // Diego Garcia
        'EA' => true, // Ceuta & Melilla
        'EU' => true, // European Union
        'EZ' => true, // Eurozone
        'IC' => true, // Canary Islands
        'TA' => true, // Tristan da Cunha
        'UN' => true, // United Nations
        // User-assigned
        'QO' => true, // Outlying Oceania
        'XA' => true, // Pseudo-Accents
        'XB' => true, // Pseudo-Bidi
        'XK' => true, // Kosovo
        // Misc
        'ZZ' => true, // Unknown Region
    ];

    /**
     * Collects all available language codes.
     *
     * @var string[]
     */
    private $regionCodes = [];

    public static function isValidCountryCode($region)
    {
        if (isset(self::$blacklist[$region])) {
            return false;
        }

        // WORLD/CONTINENT/SUBCONTINENT/GROUPING
        if (ctype_digit($region) || \is_int($region)) {
            return false;
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function scanLocales(LocaleScanner $scanner, string $sourceDir): array
    {
        return $scanner->scanLocales($sourceDir.'/region');
    }

    /**
     * {@inheritdoc}
     */
    protected function compileTemporaryBundles(BundleCompilerInterface $compiler, string $sourceDir, string $tempDir)
    {
        $compiler->compile($sourceDir.'/region', $tempDir);
        $compiler->compile($sourceDir.'/misc/metadata.txt', $tempDir);
    }

    /**
     * {@inheritdoc}
     */
    protected function preGenerate()
    {
        $this->regionCodes = [];
    }

    /**
     * {@inheritdoc}
     */
    protected function generateDataForLocale(BundleEntryReaderInterface $reader, string $tempDir, string $displayLocale): ?array
    {
        $localeBundle = $reader->read($tempDir, $displayLocale);

        // isset() on \ResourceBundle returns true even if the value is null
        if (isset($localeBundle['Countries']) && null !== $localeBundle['Countries']) {
            $data = [
                'Names' => $this->generateRegionNames($localeBundle),
            ];

            $this->regionCodes = array_merge($this->regionCodes, array_keys($data['Names']));

            return $data;
        }

        return null;
    }

    /**
     * {@inheritdoc}
     */
    protected function generateDataForRoot(BundleEntryReaderInterface $reader, string $tempDir): ?array
    {
        return null;
    }

    /**
     * {@inheritdoc}
     */
    protected function generateDataForMeta(BundleEntryReaderInterface $reader, string $tempDir): ?array
    {
        $metadataBundle = $reader->read($tempDir, 'metadata');

        $this->regionCodes = array_unique($this->regionCodes);

        sort($this->regionCodes);

        $alpha2ToAlpha3 = $this->generateAlpha2ToAlpha3Mapping(array_flip($this->regionCodes), $metadataBundle);
        $alpha3ToAlpha2 = array_flip($alpha2ToAlpha3);
        asort($alpha3ToAlpha2);

        return [
            'Regions' => $this->regionCodes,
            'Alpha2ToAlpha3' => $alpha2ToAlpha3,
            'Alpha3ToAlpha2' => $alpha3ToAlpha2,
        ];
    }

    protected function generateRegionNames(ArrayAccessibleResourceBundle $localeBundle): array
    {
        $unfilteredRegionNames = iterator_to_array($localeBundle['Countries']);
        $regionNames = [];

        foreach ($unfilteredRegionNames as $region => $regionName) {
            if (!self::isValidCountryCode($region)) {
                continue;
            }

            $regionNames[$region] = $regionName;
        }

        return $regionNames;
    }

    private function generateAlpha2ToAlpha3Mapping(array $countries, ArrayAccessibleResourceBundle $metadataBundle): array
    {
        $aliases = iterator_to_array($metadataBundle['alias']['territory']);
        $alpha2ToAlpha3 = [];

        foreach ($aliases as $alias => $data) {
            $country = $data['replacement'];
            if (2 === \strlen($country) && 3 === \strlen($alias) && 'overlong' === $data['reason']) {
                if (isset(self::$preferredAlpha2ToAlpha3Mapping[$country])) {
                    // Validate to prevent typos
                    if (!isset($aliases[self::$preferredAlpha2ToAlpha3Mapping[$country]])) {
                        throw new RuntimeException('The statically set three-letter mapping '.self::$preferredAlpha2ToAlpha3Mapping[$country].' for the country code '.$country.' seems to be invalid. Typo?');
                    }

                    $alpha3 = self::$preferredAlpha2ToAlpha3Mapping[$country];
                    $alpha2 = $aliases[$alpha3]['replacement'];

                    if ($country !== $alpha2) {
                        throw new RuntimeException('The statically set three-letter mapping '.$alpha3.' for the country code '.$country.' seems to be an alias for '.$alpha2.'. Wrong mapping?');
                    }

                    $alpha2ToAlpha3[$country] = $alpha3;
                } elseif (isset($alpha2ToAlpha3[$country])) {
                    throw new RuntimeException('Multiple three-letter mappings exist for the country code '.$country.'. Please add one of them to the property $preferredAlpha2ToAlpha3Mapping.');
                } elseif (isset($countries[$country]) && self::isValidCountryCode($alias)) {
                    $alpha2ToAlpha3[$country] = $alias;
                }
            }
        }

        asort($alpha2ToAlpha3);

        return $alpha2ToAlpha3;
    }
}