text:
<?php

namespace Oro\Bundle\SecurityBundle\Acl\Extension;

use Oro\Bundle\SecurityBundle\Acl\AccessLevel;
use Oro\Bundle\SecurityBundle\Metadata\EntitySecurityMetadataProvider;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Exception\InvalidDomainObjectException;
use Symfony\Component\Security\Acl\Model\ObjectIdentityInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Oro\Bundle\EntityBundle\ORM\EntityClassAccessor;
use Oro\Bundle\SecurityBundle\Acl\Domain\ObjectIdAccessor;
use Oro\Bundle\SecurityBundle\Acl\Extension\OwnershipDecisionMakerInterface;
use Oro\Bundle\EntityBundle\ORM\EntityClassResolver;
use Oro\Bundle\SecurityBundle\Owner\Metadata\OwnershipMetadataProvider;
use Oro\Bundle\SecurityBundle\Owner\Metadata\OwnershipMetadata;
use Oro\Bundle\SecurityBundle\Acl\Exception\InvalidAclMaskException;
use Oro\Bundle\SecurityBundle\Acl\Domain\ObjectIdentityFactory;
use Oro\Bundle\SecurityBundle\Annotation\Acl as AclAnnotation;

/**
 * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
 */
class EntityAclExtension extends AbstractAclExtension
{
    /**
     * @var EntityClassAccessor
     */
    protected $entityClassAccessor;

    /**
     * @var ObjectIdAccessor
     */
    protected $objectIdAccessor;

    /**
     * @var EntityClassResolver
     */
    protected $entityClassResolver;

    /**
     * @var OwnershipMetadataProvider
     */
    protected $metadataProvider;

    /**
     * @var EntitySecurityMetadataProvider
     */
    protected $entityMetadataProvider;

    /**
     * @var OwnershipDecisionMakerInterface
     */
    protected $decisionMaker;

    /**
     * key = Permission
     * value = The identity of a permission mask builder
     *
     * @var int[]
     */
    protected $permissionToMaskBuilderIdentity = array();

    /**
     * key = The identity of a permission mask builder
     * value = The full class name of a permission mask builder
     *
     * @var string[]
     */
    protected $maskBuilderClassNames = array();

    /**
     * Constructor
     *
     * @param EntityClassAccessor $entityClassAccessor
     * @param ObjectIdAccessor $objectIdAccessor
     * @param EntityClassResolver $entityClassResolver
     * @param EntitySecurityMetadataProvider $entityMetadataProvider
     * @param OwnershipMetadataProvider $metadataProvider
     * @param OwnershipDecisionMakerInterface $decisionMaker
     */
    public function __construct(
        EntityClassAccessor $entityClassAccessor,
        ObjectIdAccessor $objectIdAccessor,
        EntityClassResolver $entityClassResolver,
        EntitySecurityMetadataProvider $entityMetadataProvider,
        OwnershipMetadataProvider $metadataProvider,
        OwnershipDecisionMakerInterface $decisionMaker
    ) {
        $this->entityClassAccessor = $entityClassAccessor;
        $this->objectIdAccessor = $objectIdAccessor;
        $this->entityClassResolver = $entityClassResolver;
        $this->entityMetadataProvider = $entityMetadataProvider;
        $this->metadataProvider = $metadataProvider;
        $this->decisionMaker = $decisionMaker;

        $this->maskBuilderClassNames[EntityMaskBuilder::IDENTITY]
            = 'Oro\Bundle\SecurityBundle\Acl\Extension\EntityMaskBuilder';

        $this->permissionToMaskBuilderIdentity['VIEW'] = EntityMaskBuilder::IDENTITY;
        $this->permissionToMaskBuilderIdentity['CREATE'] = EntityMaskBuilder::IDENTITY;
        $this->permissionToMaskBuilderIdentity['EDIT'] = EntityMaskBuilder::IDENTITY;
        $this->permissionToMaskBuilderIdentity['DELETE'] = EntityMaskBuilder::IDENTITY;
        $this->permissionToMaskBuilderIdentity['ASSIGN'] = EntityMaskBuilder::IDENTITY;
        $this->permissionToMaskBuilderIdentity['SHARE'] = EntityMaskBuilder::IDENTITY;

        $this->map = array(
            'VIEW' => array(
                EntityMaskBuilder::MASK_VIEW_BASIC,
                EntityMaskBuilder::MASK_VIEW_LOCAL,
                EntityMaskBuilder::MASK_VIEW_DEEP,
                EntityMaskBuilder::MASK_VIEW_GLOBAL,
                EntityMaskBuilder::MASK_VIEW_SYSTEM,
            ),
            'CREATE' => array(
                EntityMaskBuilder::MASK_CREATE_BASIC,
                EntityMaskBuilder::MASK_CREATE_LOCAL,
                EntityMaskBuilder::MASK_CREATE_DEEP,
                EntityMaskBuilder::MASK_CREATE_GLOBAL,
                EntityMaskBuilder::MASK_CREATE_SYSTEM,
            ),
            'EDIT' => array(
                EntityMaskBuilder::MASK_EDIT_BASIC,
                EntityMaskBuilder::MASK_EDIT_LOCAL,
                EntityMaskBuilder::MASK_EDIT_DEEP,
                EntityMaskBuilder::MASK_EDIT_GLOBAL,
                EntityMaskBuilder::MASK_EDIT_SYSTEM,
            ),
            'DELETE' => array(
                EntityMaskBuilder::MASK_DELETE_BASIC,
                EntityMaskBuilder::MASK_DELETE_LOCAL,
                EntityMaskBuilder::MASK_DELETE_DEEP,
                EntityMaskBuilder::MASK_DELETE_GLOBAL,
                EntityMaskBuilder::MASK_DELETE_SYSTEM,
            ),
            'ASSIGN' => array(
                EntityMaskBuilder::MASK_ASSIGN_BASIC,
                EntityMaskBuilder::MASK_ASSIGN_LOCAL,
                EntityMaskBuilder::MASK_ASSIGN_DEEP,
                EntityMaskBuilder::MASK_ASSIGN_GLOBAL,
                EntityMaskBuilder::MASK_ASSIGN_SYSTEM,
            ),
            'SHARE' => array(
                EntityMaskBuilder::MASK_SHARE_BASIC,
                EntityMaskBuilder::MASK_SHARE_LOCAL,
                EntityMaskBuilder::MASK_SHARE_DEEP,
                EntityMaskBuilder::MASK_SHARE_GLOBAL,
                EntityMaskBuilder::MASK_SHARE_SYSTEM,
            ),
        );
    }

    /**
     * {@inheritdoc}
     */
    public function supports($type, $id)
    {
        if ($type === ObjectIdentityFactory::ROOT_IDENTITY_TYPE && $id === $this->getExtensionKey()) {
            return true;
        }

        if ($id === $this->getExtensionKey()) {
            $type = $this->entityClassResolver->getEntityClass($this->entityClassAccessor->getClass($type));
        } else {
            $type = $this->entityClassAccessor->getClass($type);
        }

        return $this->entityMetadataProvider->isProtectedEntity($type);
    }

    /**
     * {@inheritdoc}
     */
    public function getExtensionKey()
    {
        return 'entity';
    }

    /**
     * {@inheritdoc}
     */
    public function validateMask($mask, $object, $permission = null)
    {
        if (0 === $this->removeServiceBits($mask)) {
            // zero mask
            return;
        }

        $permissions = $permission === null
            ? $this->getPermissions($mask, true)
            : array($permission);

        foreach ($permissions as $permission) {
            $validMasks = $this->getValidMasks($permission, $object);
            if (($mask | $validMasks) === $validMasks) {
                $identity = $this->permissionToMaskBuilderIdentity[$permission];
                foreach ($this->permissionToMaskBuilderIdentity as $p => $i) {
                    if ($identity === $i) {
                        $this->validateMaskAccessLevel($p, $mask, $object);
                    }
                }

                return;
            }
        }

        throw $this->createInvalidAclMaskException($mask, $object);
    }

    /**
     * {@inheritdoc}
     */
    public function getObjectIdentity($val)
    {
        if (is_string($val)) {
            return $this->fromDescriptor($val);
        } elseif ($val instanceof AclAnnotation) {
            return new ObjectIdentity(
                $val->getType(),
                $this->entityClassResolver->getEntityClass($val->getClass())
            );
        }

        return $this->fromDomainObject($val);
    }

    /**
     * {@inheritdoc}
     */
    public function getMaskBuilder($permission)
    {
        if (empty($permission)) {
            $permission = 'VIEW';
        }

        $identity = $this->permissionToMaskBuilderIdentity[$permission];
        $maskBuilderClassName = $this->maskBuilderClassNames[$identity];

        return new $maskBuilderClassName();
    }

    /**
     * {@inheritdoc}
     */
    public function getAllMaskBuilders()
    {
        $result = array();
        foreach ($this->maskBuilderClassNames as $maskBuilderClassName) {
            $result[] = new $maskBuilderClassName();
        }

        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function getMaskPattern($mask)
    {
        $maskBuilderClassName = $this->maskBuilderClassNames[$this->getServiceBits($mask)];

        return $maskBuilderClassName::getPatternFor($mask);
    }

    /**
     * {@inheritdoc}
     */
    public function adaptRootMask($rootMask, $object)
    {
        $permissions = $this->getPermissions($rootMask, true);
        if (!empty($permissions)) {
            $metadata = $this->getMetadata($object);
            $identity = $this->getServiceBits($rootMask);
            foreach ($permissions as $permission) {
                $permissionMask = $this->getMaskBuilderConst($identity, 'GROUP_' . $permission);
                $mask = $rootMask & $permissionMask;
                $accessLevel = $this->getAccessLevel($mask);
                if (!$metadata->hasOwner()) {
                    if ($identity === EntityMaskBuilder::IDENTITY
                        && ($permission === 'ASSIGN' || $permission === 'SHARE')
                    ) {
                        $rootMask &= ~$this->removeServiceBits($mask);
                    } elseif ($accessLevel < AccessLevel::SYSTEM_LEVEL) {
                        $rootMask &= ~$this->removeServiceBits($mask);
                        $rootMask |= $this->getMaskBuilderConst($identity, 'MASK_' . $permission . '_SYSTEM');
                    }
                } elseif ($metadata->isOrganizationOwned()) {
                    if ($accessLevel < AccessLevel::GLOBAL_LEVEL) {
                        $rootMask &= ~$this->removeServiceBits($mask);
                        $rootMask |= $this->getMaskBuilderConst($identity, 'MASK_' . $permission . '_GLOBAL');
                    }
                } elseif ($metadata->isBusinessUnitOwned()) {
                    if ($accessLevel < AccessLevel::LOCAL_LEVEL) {
                        $rootMask &= ~$this->removeServiceBits($mask);
                        $rootMask |= $this->getMaskBuilderConst($identity, 'MASK_' . $permission . '_LOCAL');
                    }
                }
            }
        }

        return $rootMask;
    }

    /**
     * {@inheritdoc}
     */
    public function getServiceBits($mask)
    {
        return $mask & BaseEntityMaskBuilder::SERVICE_BITS;
    }

    /**
     * {@inheritdoc}
     */
    public function removeServiceBits($mask)
    {
        return $mask & BaseEntityMaskBuilder::REMOVE_SERVICE_BITS;
    }

    /**
     * {@inheritdoc}
     */
    public function getAccessLevel($mask, $permission = null)
    {
        if (0 === $this->removeServiceBits($mask)) {
            return AccessLevel::NONE_LEVEL;
        }

        $identity = $this->getServiceBits($mask);
        if ($permission !== null) {
            $permissionMask = $this->getMaskBuilderConst($identity, 'GROUP_' . $permission);
            $mask = $mask & $permissionMask;
        }

        $result = AccessLevel::NONE_LEVEL;
        foreach (AccessLevel::$allAccessLevelNames as $accessLevel) {
            if (0 !== ($mask & $this->getMaskBuilderConst($identity, 'GROUP_' . $accessLevel))) {
                $result = AccessLevel::getConst($accessLevel . '_LEVEL');
            }
        }

        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function getPermissions($mask = null, $setOnly = false)
    {
        if ($mask === null) {
            return array_keys($this->permissionToMaskBuilderIdentity);
        }

        $result = array();
        if (!$setOnly) {
            $identity = $this->getServiceBits($mask);
            foreach ($this->permissionToMaskBuilderIdentity as $permission => $id) {
                if ($id === $identity) {
                    $result[] = $permission;
                }
            }
        } elseif (0 !== $this->removeServiceBits($mask)) {
            $identity = $this->getServiceBits($mask);
            foreach ($this->permissionToMaskBuilderIdentity as $permission => $id) {
                if ($id === $identity) {
                    if (0 !== ($mask & $this->getMaskBuilderConst($identity, 'GROUP_' . $permission))) {
                        $result[] = $permission;
                    }
                }
            }
        }

        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function getAllowedPermissions(ObjectIdentity $oid)
    {
        if ($oid->getType() === ObjectIdentityFactory::ROOT_IDENTITY_TYPE) {
            $result = array_keys($this->permissionToMaskBuilderIdentity);
        } else {
            $config = $this->entityMetadataProvider->getMetadata($oid->getType());
            $result = $config->getPermissions();
            if (empty($result)) {
                $result = array_keys($this->map);
            }

            $metadata = $this->getMetadata($oid);
            if (!$metadata->hasOwner()) {
                foreach ($result as $key => $value) {
                    if (in_array($value, array('ASSIGN', 'SHARE'))) {
                        unset($result[$key]);
                    }
                }
            }
        }

        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function getClasses()
    {
        return $this->entityMetadataProvider->getEntities();
    }

    /**
     * {@inheritdoc}
     */
    public function decideIsGranting($triggeredMask, $object, TokenInterface $securityToken)
    {
        $accessLevel = $this->getAccessLevel($triggeredMask);
        if ($accessLevel === AccessLevel::SYSTEM_LEVEL) {
            return true;
        }

        // check whether we check permissions for a domain object
        if ($object === null || !is_object($object) || $object instanceof ObjectIdentityInterface) {
            return true;
        }

        $metadata = $this->getMetadata($object);
        if (!$metadata->hasOwner()) {
            return true;
        }

        $result = false;
        if (AccessLevel::BASIC_LEVEL === $accessLevel) {
            $result = $this->decisionMaker->isAssociatedWithUser($securityToken->getUser(), $object);
        } else {
            if ($metadata->isUserOwned()) {
                $result = $this->decisionMaker->isAssociatedWithUser($securityToken->getUser(), $object);
            }
            if (!$result) {
                if (AccessLevel::LOCAL_LEVEL === $accessLevel) {
                    $result = $this->decisionMaker->isAssociatedWithBusinessUnit($securityToken->getUser(), $object);
                } elseif (AccessLevel::DEEP_LEVEL === $accessLevel) {
                    $result = $this->decisionMaker->isAssociatedWithBusinessUnit(
                        $securityToken->getUser(),
                        $object,
                        true
                    );
                } elseif (AccessLevel::GLOBAL_LEVEL === $accessLevel) {
                    $result = $this->decisionMaker->isAssociatedWithOrganization($securityToken->getUser(), $object);
                }
            }
        }

        return $result;
    }

    /**
     * Constructs an ObjectIdentity for the given domain object
     *
     * @param string $descriptor
     * @return ObjectIdentity
     * @throws \InvalidArgumentException
     */
    protected function fromDescriptor($descriptor)
    {
        $type = $id = null;
        $this->parseDescriptor($descriptor, $type, $id);

        if ($id === $this->getExtensionKey()) {
            return new ObjectIdentity(
                $id,
                $this->entityClassResolver->getEntityClass($this->entityClassAccessor->getClass($type))
            );
        }

        throw new \InvalidArgumentException(
            sprintf('Unsupported object identity descriptor: %s.', $descriptor)
        );
    }

    /**
     * Constructs an ObjectIdentity for the given domain object
     *
     * @param object $domainObject
     * @return ObjectIdentity
     * @throws InvalidDomainObjectException
     */
    protected function fromDomainObject($domainObject)
    {
        if (!is_object($domainObject)) {
            throw new InvalidDomainObjectException('$domainObject must be an object.');
        }

        try {
            return new ObjectIdentity(
                $this->objectIdAccessor->getId($domainObject),
                $this->entityClassAccessor->getClass($domainObject)
            );
        } catch (\InvalidArgumentException $invalid) {
            throw new InvalidDomainObjectException($invalid->getMessage(), 0, $invalid);
        }
    }

    /**
     * Checks that the given mask represents only one access level
     *
     * @param string $permission
     * @param int $mask
     * @param mixed $object
     * @throws InvalidAclMaskException
     */
    protected function validateMaskAccessLevel($permission, $mask, $object)
    {
        $identity = $this->permissionToMaskBuilderIdentity[$permission];
        if (0 !== ($mask & $this->getMaskBuilderConst($identity, 'GROUP_' . $permission))) {
            $maskAccessLevels = array();
            foreach (AccessLevel::$allAccessLevelNames as $accessLevel) {
                if (0 !== ($mask & $this->getMaskBuilderConst($identity, 'MASK_' . $permission . '_' . $accessLevel))) {
                    $maskAccessLevels[] = $accessLevel;
                }
            }
            if (count($maskAccessLevels) > 1) {
                $msg = sprintf(
                    'The %s mask must be in one access level only, but it is in %s access levels.',
                    $permission,
                    implode(', ', $maskAccessLevels)
                );
                throw $this->createInvalidAclMaskException($mask, $object, $msg);
            }
        }
    }

    /**
     * Gets all valid bitmasks for the given object
     *
     * @param string $permission
     * @param mixed $object
     * @return int
     */
    protected function getValidMasks($permission, $object)
    {
        if ($object instanceof ObjectIdentity && $object->getType() === ObjectIdentityFactory::ROOT_IDENTITY_TYPE) {
            $identity = $this->permissionToMaskBuilderIdentity[$permission];

            return
                $this->getMaskBuilderConst($identity, 'GROUP_SYSTEM')
                | $this->getMaskBuilderConst($identity, 'GROUP_GLOBAL')
                | $this->getMaskBuilderConst($identity, 'GROUP_DEEP')
                | $this->getMaskBuilderConst($identity, 'GROUP_LOCAL')
                | $this->getMaskBuilderConst($identity, 'GROUP_BASIC');
        }

        $metadata = $this->getMetadata($object);
        if (!$metadata->hasOwner()) {
            if ($this->permissionToMaskBuilderIdentity[$permission] === EntityMaskBuilder::IDENTITY) {
                return EntityMaskBuilder::GROUP_CRUD_SYSTEM;
            }

            return $this->permissionToMaskBuilderIdentity[$permission];
        }

        $identity = $this->permissionToMaskBuilderIdentity[$permission];
        if ($metadata->isOrganizationOwned()) {
            return
                $this->getMaskBuilderConst($identity, 'GROUP_SYSTEM')
                | $this->getMaskBuilderConst($identity, 'GROUP_GLOBAL');
        } elseif ($metadata->isBusinessUnitOwned()) {
            return
                $this->getMaskBuilderConst($identity, 'GROUP_SYSTEM')
                | $this->getMaskBuilderConst($identity, 'GROUP_GLOBAL')
                | $this->getMaskBuilderConst($identity, 'GROUP_DEEP')
                | $this->getMaskBuilderConst($identity, 'GROUP_LOCAL');
        } elseif ($metadata->isUserOwned()) {
            return
                $this->getMaskBuilderConst($identity, 'GROUP_SYSTEM')
                | $this->getMaskBuilderConst($identity, 'GROUP_GLOBAL')
                | $this->getMaskBuilderConst($identity, 'GROUP_DEEP')
                | $this->getMaskBuilderConst($identity, 'GROUP_LOCAL')
                | $this->getMaskBuilderConst($identity, 'GROUP_BASIC');
        }

        return $this->permissionToMaskBuilderIdentity[$permission];
    }

    /**
     * Gets metadata for the given object
     *
     * @param mixed $object
     * @return OwnershipMetadata
     */
    protected function getMetadata($object)
    {
        if ($object instanceof ObjectIdentity) {
            $className = $object->getType();
        } elseif (is_string($object)) {
            $className = $id = null;
            $this->parseDescriptor($object, $className, $id);
        } else {
            $className = $this->entityClassAccessor->getClass($object);
        }

        return $this->metadataProvider->getMetadata($className);
    }

    /**
     * Gets the constant value defined in the given permission mask builder
     *
     * @param int $maskBuilderIdentity The permission mask builder identity
     * @param string $constName
     * @return int
     */
    protected function getMaskBuilderConst($maskBuilderIdentity, $constName)
    {
        $maskBuilderClassName = $this->maskBuilderClassNames[$maskBuilderIdentity];

        return $maskBuilderClassName::getConst($constName);
    }
}


text:
package me.realized.tokenmanager.util.compat;

import java.util.HashMap;
import java.util.Map;
import org.bukkit.Material;

public final class Terracottas {

    private static final Map<Short, String> DATA_TO_TERRACOTTA = new HashMap<>();

    static {
        DATA_TO_TERRACOTTA.put((short) 0, "WHITE_TERRACOTTA");
        DATA_TO_TERRACOTTA.put((short) 1, "ORANGE_TERRACOTTA");
        DATA_TO_TERRACOTTA.put((short) 2, "MAGENTA_TERRACOTTA");
        DATA_TO_TERRACOTTA.put((short) 3, "LIGHT_BLUE_TERRACOTTA");
        DATA_TO_TERRACOTTA.put((short) 4, "YELLOW_TERRACOTTA");
        DATA_TO_TERRACOTTA.put((short) 5, "LIME_TERRACOTTA");
        DATA_TO_TERRACOTTA.put((short) 6, "PINK_TERRACOTTA");
        DATA_TO_TERRACOTTA.put((short) 7, "GRAY_TERRACOTTA");
        DATA_TO_TERRACOTTA.put((short) 8, "LIGHT_GRAY_TERRACOTTA");
        DATA_TO_TERRACOTTA.put((short) 9, "CYAN_TERRACOTTA");
        DATA_TO_TERRACOTTA.put((short) 10, "PURPLE_TERRACOTTA");
        DATA_TO_TERRACOTTA.put((short) 11, "BLUE_TERRACOTTA");
        DATA_TO_TERRACOTTA.put((short) 12, "BROWN_TERRACOTTA");
        DATA_TO_TERRACOTTA.put((short) 13, "GREEN_TERRACOTTA");
        DATA_TO_TERRACOTTA.put((short) 14, "RED_TERRACOTTA");
        DATA_TO_TERRACOTTA.put((short) 15, "BLACK_TERRACOTTA");
    }

    public static Material from(final short data) {
        return Material.getMaterial(DATA_TO_TERRACOTTA.get(data));
    }

    private Terracottas() {}
}

redpajama_set_name: RedPajamaGithub


text:
using Emc.Documentum.Rest.Net;
using Emc.Documentum.Rest.Http.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using Emc.Documentum.Rest.DataModel.D2;

namespace Emc.Documentum.Rest.DataModel
{
    public partial class Folder
    {
        /// <summary>
        /// Whether the folder has parent folders
        /// </summary>
        /// <returns>Returns Boolean value</returns>
        public bool HasParent()
        {
            return LinkRelations.FindLinkAsString(GetFullLinks(), LinkRelations.PARENT.Rel) != null;
        }

        /// <summary>
        /// Get child folders from this folder
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="options"></param>
        /// <returns>Returns Rest Feed for the object</returns>
        public Feed<T> GetFolders<T>(FeedGetOptions options)
        {
            return Client.GetFeed<T>(
                GetFullLinks(),
                LinkRelations.FOLDERS.Rel,
                options);
        }

        /// <summary>
        /// Get child documents from this folder
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="options"></param>
        /// <returns>Returns Rest Feed for object</returns>
        public Feed<T> GetDocuments<T>(FeedGetOptions options)
        {
            return Client.GetFeed<T>(
                GetFullLinks(),
                LinkRelations.DOCUMENTS.Rel,
                options);
        }

        /// <summary>
        /// Get the cabinet resource where this folder locates at
        /// </summary>
        /// <param name="options"></param>
        /// <returns>Returns Cabinet object</returns>
        public new Cabinet GetCabinet(SingleGetOptions options)
        {
            return Client.GetSingleton<Cabinet>(
                GetFullLinks(),
                LinkRelations.CABINET.Rel,
                options);
        }

        /// <summary>
        /// Get the parent folder of this folder
        /// </summary>
        /// <param name="options"></param>
        /// <returns>Returns Folder object</returns>
        public new Folder GetParentFolder(SingleGetOptions options)
        {
            return Client.GetSingleton<Folder>(
                GetFullLinks(),
                LinkRelations.PARENT.Rel,
                options);
        }

        /// <summary>
        /// Create a folder resource under this folder
        /// </summary>
        /// <param name="newObj"></param>
        /// <param name="options"></param>
        /// <returns>Returns Folder object</returns>
        public Folder CreateSubFolder(Folder newObj, GenericOptions options)
        {
            return Client.Post<Folder>(
                GetFullLinks(),
                LinkRelations.FOLDERS.Rel,
                newObj,
                options);
        }

        /// <summary>
        /// Create a document resource under this folder
        /// </summary>
        /// <param name="newObj"></param>
        /// <param name="options"></param>
        /// <returns>Returns RestDocument object</returns>
        public Document CreateSubDocument(Document newObj, GenericOptions options)
        {
            return Client.Post<Document>(
                GetFullLinks(),
                LinkRelations.DOCUMENTS.Rel,
                newObj,
                options);
        }

        /// <summary>
        /// Create a PersistentObject resource under this folder
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="newObj"></param>
        /// <param name="options"></param>
        /// <returns>Returns Type object</returns>
        public T CreateSubObject<T>(T newObj, GenericOptions options) where T : PersistentObject
        {
            return Client.Post<T>(
                GetFullLinks(),
                LinkRelations.OBJECTS.Rel,
                newObj,
                options);
        }

        /// <summary>
        /// Import a contentful document with content stream under this folder
        /// </summary>
        /// <param name="newObj"></param>
        /// <param name="otherPartStream"></param>
        /// <param name="otherPartMime"></param>
        /// <param name="options"></param>
        /// <returns>Returns RestDocument object</returns>
        public Document ImportDocumentWithContent(Document newObj, Stream otherPartStream, string otherPartMime, GenericOptions options)
        {
            Dictionary<Stream, string> otherParts = new Dictionary<Stream, string>();
            otherParts.Add(otherPartStream, otherPartMime);
            return Client.Post<Document>(
                GetFullLinks(),
                LinkRelations.DOCUMENTS.Rel,
                newObj,
                otherParts,
                options);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="repositoryUri"></param>
        /// <param name="newObj"></param>
        /// <param name="otherPartStream"></param>
        /// <param name="otherPartMime"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public EmailPackage ImportEmail(Document newObj, Stream otherPartStream, string otherPartMime, GenericOptions options)
        {
            Dictionary<Stream, string> otherParts = new Dictionary<Stream, string>();
            otherParts.Add(otherPartStream, otherPartMime);
            options.SetQuery("folderId", this.GetPropertyValue("r_object_id"));
            Feed<Document> feed = Client.Post<Document, Feed<Document>>(
                Client.RepositoryBaseUri + LinkRelations.EMAILIMPORT,
                newObj,
                otherParts,
                options);
            return ObjectUtil.getFeedAsEmailPackage(feed);

        }

        /// <summary>
        /// Link a PersistentObject resource to this folder
        /// </summary>
        /// <param name="newObj"></param>
        /// <param name="options"></param>
        /// <returns>Returns Folder link </returns>
        public FolderLink LinkFrom(Document newObj, GenericOptions options)
        {
            return Client.Post<Document, FolderLink>(
                GetFullLinks(),
                LinkRelations.CHILD_LINKS.Rel,
                newObj,
                options);
        }
    }
}


text:
static int hydra_uuid(lua_State* L) {
    lua_pushstring(L, [[[NSUUID UUID] UUIDString] UTF8String]);
    return 1;
}


text:
package com.nativelibs4java.opencl.demos.sobelfilter;
import com.nativelibs4java.opencl.CLAbstractUserProgram;
import com.nativelibs4java.opencl.CLBuffer;
import com.nativelibs4java.opencl.CLBuildException;
import com.nativelibs4java.opencl.CLContext;
import com.nativelibs4java.opencl.CLEvent;
import com.nativelibs4java.opencl.CLImage2D;
import com.nativelibs4java.opencl.CLKernel;
import com.nativelibs4java.opencl.CLProgram;
import com.nativelibs4java.opencl.CLQueue;
import java.io.IOException;
/** Wrapper around the OpenCL program SimpleSobel */
public class SimpleSobel extends CLAbstractUserProgram {
	public SimpleSobel(CLContext context) throws IOException {
		super(context, readRawSourceForClass(SimpleSobel.class));
	}
	public SimpleSobel(CLProgram program) throws IOException {
		super(program, readRawSourceForClass(SimpleSobel.class));
	}
	CLKernel simpleSobel_kernel;
	public synchronized CLEvent simpleSobel(CLQueue commandQueue, CLImage2D input, int width, int height, CLBuffer<Float > gradientOutput, CLBuffer<Float > directionOutput, int globalWorkSizes[], int localWorkSizes[], CLEvent... eventsToWaitFor) throws CLBuildException {
		if ((simpleSobel_kernel == null))
			simpleSobel_kernel = createKernel("simpleSobel");
		simpleSobel_kernel.setArgs(input, width, height, gradientOutput, directionOutput);
		return simpleSobel_kernel.enqueueNDRange(commandQueue, globalWorkSizes, localWorkSizes, eventsToWaitFor);
	}
	CLKernel normalizeImage_kernel;
	public synchronized CLEvent normalizeImage(CLQueue commandQueue, CLBuffer<Float > input, float maxValue, CLBuffer<Byte > output, int globalWorkSizes[], int localWorkSizes[], CLEvent... eventsToWaitFor) throws CLBuildException {
		if ((normalizeImage_kernel == null))
			normalizeImage_kernel = createKernel("normalizeImage");
		normalizeImage_kernel.setArgs(input, maxValue, output);
		return normalizeImage_kernel.enqueueNDRange(commandQueue, globalWorkSizes, localWorkSizes, eventsToWaitFor);
	}
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MX_NW = (int)1;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MX_N = (int)2;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MX_NE = (int)1;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MX_W = (int)0;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MX_C = (int)0;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MX_E = (int)0;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MX_SW = (int)-1;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MX_S = (int)-2;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MX_SE = (int)-1;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MY_NW = (int)1;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MY_N = (int)0;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MY_NE = (int)-1;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MY_W = (int)2;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MY_C = (int)0;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MY_E = (int)-2;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MY_SW = (int)1;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MY_S = (int)0;
	/** native declaration : com\nativelibs4java\opencl\demos\sobelfilter\SimpleSobel.cl */
	public static final int MY_SE = (int)-1;
}


text:
layout: page
title: Hopkins Industries Party
date: 2016-05-24
author: Scott Fuller
tags: weekly links, java
status: published
summary: Aliquam consectetur vestibulum libero vel luctus. Suspendisse id.
banner: images/banner/people.jpg
booking:
  startDate: 05/21/2016
  endDate: 05/22/2016
  ctyhocn: MKCSMHX
  groupCode: HIP
published: true
---
Phasellus mi ante, efficitur non dapibus a, lacinia non nunc. Nulla at auctor ex. Donec volutpat urna vitae ornare blandit. Morbi eu turpis eu massa convallis cursus at semper velit. Nulla facilisi. Nulla quis efficitur dolor. Nulla quis mi mi. Phasellus dapibus ex sed ante feugiat, eget bibendum quam consectetur. Fusce commodo non ligula quis tempus. Nam nunc justo, sodales in dui eu, tristique viverra tellus. Quisque facilisis fermentum erat, eu varius lacus iaculis eget. Suspendisse quis vestibulum ante.

* Sed interdum odio id mollis imperdiet
* Duis rhoncus erat a risus faucibus tincidunt.

Cras in sapien et neque suscipit posuere eu id mi. Mauris accumsan in eros in consequat. Aliquam nisi metus, suscipit nec commodo in, posuere eget dui. Sed hendrerit, nulla vel maximus vestibulum, nisi tortor dapibus nisi, vel lobortis quam arcu dignissim tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vestibulum dapibus lacinia. Quisque vel risus nec augue malesuada maximus a ullamcorper tellus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget enim semper, vehicula purus sed, mollis tortor. Phasellus tempus ornare neque eu auctor. In eget hendrerit diam, eu condimentum augue. Nulla laoreet vel quam et blandit. Fusce vel tellus orci.


text:
layout: page
title: Red Foundation Executive Retreat
date: 2016-05-24
author: Jeffrey Little
tags: weekly links, java
status: published
summary: Quisque placerat tempus lorem quis placerat. Sed iaculis quam.
banner: images/banner/people.jpg
booking:
  startDate: 08/12/2018
  endDate: 08/17/2018
  ctyhocn: PNSGBHX
  groupCode: RFER
published: true
---
Nulla suscipit nibh vitae nibh bibendum, vitae pharetra justo commodo. Nulla consectetur aliquet turpis at pellentesque. In nisl nisi, facilisis quis luctus sit amet, auctor id nibh. Morbi non tincidunt erat. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus elementum felis ultricies lacus suscipit, vitae dictum metus faucibus. Aliquam lorem libero, tincidunt et laoreet nec, condimentum in lorem. Fusce consectetur, orci ac vulputate tempor, augue velit vulputate nisi, eu euismod lectus elit at enim. Integer luctus ut libero eu eleifend. Pellentesque et tincidunt libero. Donec pretium eros quis ex interdum placerat. Curabitur a mi arcu. Sed sollicitudin finibus imperdiet.

* Aliquam sodales dolor malesuada velit pellentesque volutpat
* Proin sed elit sed magna cursus interdum
* Donec rutrum tellus ut leo elementum auctor
* Phasellus ornare nisi quis dui ullamcorper, sit amet mollis leo dapibus
* Fusce id dolor ac urna euismod feugiat.

Maecenas quis dapibus sem, sit amet bibendum nisl. Mauris a arcu ac neque rutrum bibendum sed sed quam. Phasellus eros purus, posuere nec vestibulum eu, sodales et massa. Integer faucibus purus blandit consequat rhoncus. Ut viverra, velit eget molestie sollicitudin, ante nisi auctor sapien, ut tempus dolor nibh id metus. Sed vulputate, elit sit amet luctus luctus, augue nisi dapibus ligula, a vestibulum magna dui ut diam. Etiam dictum dapibus tellus ut maximus. Quisque arcu lorem, mollis at diam vel, ornare luctus ex.
Nunc semper bibendum commodo. Maecenas mauris eros, laoreet et varius non, vestibulum eget erat. Integer posuere ultrices nunc eget fermentum. Vivamus ullamcorper vitae magna in posuere. Praesent at accumsan sapien. Cras porta ligula sed scelerisque eleifend. Cras arcu nibh, cursus id condimentum id, consectetur in massa. Nulla varius ante eu pharetra condimentum. Nam tellus augue, ultricies non eros eu, sagittis maximus ligula. Maecenas pharetra turpis ac libero rutrum tempor.


text:
<?php
/**
 * Configuration options for Snapshot class. Attention, configs might include runtime code which
 * depended on environment values only.
 *
 * @see SnapshotConfig
 */

return [
    /*
     * View to render snapshot/exception information, please note that "slow" view will dump all
     * track arguments which can lead to much longer executing time.
     */
    'view'      => env('EXCEPTION_VIEW', 'spiral:exceptions/light/fast.php'),

    /*
     * Automatic snapshot reporting options. You can define your own SnapshotInterface in order
     * to create custom handler OR add Monolog handler to default log channel.
     */
    'reporting' => [
        'enabled'      => true,
        'maxSnapshots' => 5,
        'directory'    => directory('runtime') . 'snapshots',
        'filename'     => '{date}-{name}.html',
        'dateFormat'   => 'd.m.Y-Hi.s',
    ]
];


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

package search.twitter

import scala.collection.JavaConversions._
import scala.collection.mutable
import twitter4j._
import twitter4j.conf.{Configuration, ConfigurationBuilder}
import utils.Constants
import search.Searcher

/** A Twitter searcher that uses the twitter4j API to search for relevant tweets.
  *
  * See [[search.web.RunTwitterSearcher]] for an example usage.
  *
  * @constructor Create a Twitter searcher using twitter4j.
  * @param config The twitter connection configuration to use.
  * @param params Additional search-specific parameters (stored as key-value pairs).
  *
  * @author trananh
  */
class TwitterSearcher(
    var config: Configuration = new ConfigurationBuilder()
      .setDebugEnabled(Constants.DEBUG)
      .setOAuthConsumerKey(Constants.TwitterProperties.oauthConsumerKey)
      .setOAuthConsumerSecret(Constants.TwitterProperties.oauthConsumerSecret)
      .setOAuthAccessToken(Constants.TwitterProperties.oauthAccessToken)
      .setOAuthAccessTokenSecret(Constants.TwitterProperties.oauthAccessTokenSecret)
      .build(),
    var params: mutable.HashMap[String,Any] = new mutable.HashMap[String,Any]())
  extends Searcher {

  /** Creates a TwitterFactory with the given configuration. */
  val twitterFactory = new TwitterFactory(config)

  /** Returns tweets that match a specified query.
    * @param query The query.
    * @return List of tweet results.
    */
  def search(query: String): java.util.List[Status] = {
    val twitter = twitterFactory.getInstance()
    val result = twitter.search(new Query(query))
    result.getTweets
  }

  /******** Searcher implementation starts here ********/

  /** Close all open streams and clear memory usage */
  def close() { /* nothing to close for now */ }

  /** Return the term frequency (i.e., the total number of time the term is found).
    *
    * @param term The query term.
    *
    * @return Total occurrence count of the term.
    */
  def termFreq(term: String): Long = search(term).length

  /** Return the document frequency for the term.
    *
    * @param term The query term.
    *
    * @return Number of documents containing the term.
    */
  def docFreq(term: String): Long = search(term).length

  /** Search and return highlighted snippets from the results.
    *
    * @param queryStr The query string.
    * @param numHits Maximum number of search hits to return.
    *
    * @return Array of highlighted text snippets from the results.
    */
  def searchHighlight(queryStr: String, numHits: Integer): Array[String] = {
    val results = search(queryStr).map(status => "@" + status.getUser.getScreenName + ": " + status.getText)
    results.slice(0, numHits).toArray[String]
  }

}

/** Search twitter. */
object RunTwitterSearcher {

  def main(args: Array[String]) {

    // Query string
    val queryStr = "twitter search api"

    // Search twitter and print results
    val searcher = new TwitterSearcher()
    val results = searcher.search(queryStr)
    results.foreach(status => println("@" + status.getUser.getScreenName + ": " + status.getText))
  }

}


text:
import { document, Element } from '../mocks';

describe('document Mock', () => {
    it('creates an element with createElement', () => {
        expect(document.createElement('div')).to.be.an.instanceof(Element);
    });

    it('creates an element with createElement that has the right nodeName', () => {
        expect(document.createElement('div').nodeName).to.equal('DIV');
    });

    it('throws when calling querySelector', () => {
        expect(() => document.querySelector('#myElement')).to.throw();
    });
});


text:
package org.fiteagle.adapters.Exceptions;

public class ConfigureException extends RuntimeException{

  public ConfigureException(String message){
    super(message);
  }

}


text:
package com.tanchaoyin.diandian.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Point;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.socks.library.KLog;
import com.tanchaoyin.diandian.R;

/**
 * Created by TanChaoyin on 2016/3/8.
 */
public class MeasureUtil {

    /**
     * 获取状态栏的高度
     *
     * @param context 上下文
     * @return 状态栏高度
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources()
                .getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 获取ToolBar的高度
     *
     * @param context
     * @return
     */
    public static int getToolbarHeight(Context context) {
        final TypedArray styledAttributes = context.getTheme()
                .obtainStyledAttributes(new int[]{R.attr.actionBarSize});
        int toolbarHeight = (int) styledAttributes.getDimension(0, 0);
        styledAttributes.recycle();

        return toolbarHeight;
    }

    public static int getNavigationBarHeight(Activity activity) {

        Resources resources = activity.getResources();

        int rid = resources.getIdentifier("config_showNavigationBar", "bool", "android");
        if (rid > 0) {
            KLog.e("获取导航栏是否显示true or false" + resources
                    .getBoolean(rid) + ""); //获取导航栏是否显示true or false
        }

        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0) {
            KLog.e("获取导航栏高度 " + resources.getDimensionPixelSize(resourceId) + ""); //获取高度
            return resources.getDimensionPixelSize(resourceId);
        }

        //获取NavigationBar的高度
        return 0;
    }

    /**
     * 获取屏幕尺寸
     *
     * @param context 上下文
     * @return 屏幕尺寸像素值,下标为0的值为宽,下标为1的值为高
     */
    public static Point getScreenSize(Context context) {

        // 获取屏幕宽高
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Point screenSize = new Point();
        wm.getDefaultDisplay().getSize(screenSize);
        return screenSize;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将px值转换为sp值,保证文字大小不变
     *
     * @param pxValue
     * @param context (DisplayMetrics类中属性scaledDensity)
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值,保证文字大小不变
     *
     * @param spValue
     * @param context (DisplayMetrics类中属性scaledDensity)
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 动态测量listview item的高度
     *
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            if (listItem instanceof ViewGroup) {
                listItem.setLayoutParams(
                        new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT));
            }
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    /**
     * 动态测量listview item的高度
     *
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren1(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int desiredWidth = View.MeasureSpec
                .makeMeasureSpec(listView.getWidth(), View.MeasureSpec.AT_MOST);
        int totalHeight = 0;
        View view = null;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            view = listAdapter.getView(i, view, listView);
            if (i == 0) {
                view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
            }
            view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
            totalHeight += view.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }
}


text:
<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Default Database Connection Name
	|--------------------------------------------------------------------------
	|
	| Here you may specify which of the database connections below you wish
	| to use as your default connection for all database work. Of course
	| you may use many connections at once using the Database library.
	|
	*/

	'default' => 'sqlite',

	/*
	|--------------------------------------------------------------------------
	| Database Connections
	|--------------------------------------------------------------------------
	|
	| Here are each of the database connections setup for your application.
	| Of course, examples of configuring each database platform that is
	| supported by Laravel is shown below to make development simple.
	|
	|
	| All database work in Laravel is done through the PHP PDO facilities
	| so make sure you have the driver for your particular database of
	| choice installed on your machine before you begin development.
	|
	*/

	'connections' => array(

		'sqlite' => array(
			'driver'   => 'sqlite',
			'database' => ':memory:',
			'prefix'   => '',
		),

	),

);


text:
package com.ctrip.ops.sysdev.filters;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.ctrip.ops.sysdev.baseplugin.BaseFilter;
import lombok.extern.log4j.Log4j2;

@Log4j2
public class KV extends BaseFilter {

    private String source;
    private String target;
    private String field_split;
    private String value_split;
    private String trim;
    private String trimkey;

    private ArrayList<String> excludeKeys, includeKeys;

    @SuppressWarnings("rawtypes")
    public KV(Map config) {
        super(config);
    }

    @SuppressWarnings("unchecked")
    protected void prepare() {

        if (this.config.containsKey("source")) {
            this.source = (String) this.config.get("source");
        } else {
            this.source = "message";
        }

        if (this.config.containsKey("target")) {
            this.target = (String) this.config.get("target");
        }

        if (this.config.containsKey("field_split")) {
            this.field_split = (String) this.config.get("field_split");
        } else {
            this.field_split = " ";
        }
        if (this.config.containsKey("value_split")) {
            this.value_split = (String) this.config.get("value_split");
        } else {
            this.value_split = "=";
        }

        if (this.config.containsKey("trim")) {
            this.trim = (String) this.config.get("trim");
            this.trim = "^[" + this.trim + "]+|[" + this.trim + "]+$";
        }

        if (this.config.containsKey("trimkey")) {
            this.trimkey = (String) this.config.get("trimkey");
            this.trimkey = "^[" + this.trimkey + "]+|[" + this.trimkey + "]+$";
        }

        if (this.config.containsKey("tag_on_failure")) {
            this.tagOnFailure = (String) this.config.get("tag_on_failure");
        } else {
            this.tagOnFailure = "KVfail";
        }

        this.excludeKeys = (ArrayList<String>) this.config.get("exclude_keys");
        this.includeKeys = (ArrayList<String>) this.config.get("include_keys");

    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    protected Map filter(Map event) {
        if (!event.containsKey(this.source)) {
            return event;
        }
        boolean success = true;

        HashMap targetObj = new HashMap();

        try {
            String sourceStr = (String) event.get(this.source);
            for (String kv : sourceStr.split(this.field_split)) {
                String[] kandv = kv.split(this.value_split, 2);
                if (kandv.length != 2) {
                    success = false;
                    continue;
                }

                String k = kandv[0];
                if (this.includeKeys != null && !this.includeKeys.contains(k)
                        || this.excludeKeys != null
                        && this.excludeKeys.contains(k)) {
                    continue;
                }

                String v = kandv[1];

                if (this.trim != null) {
                    v = v.replaceAll(this.trim, "");
                }
                if (this.trimkey != null) {
                    k = k.replaceAll(this.trimkey, "");
                }

                if (this.target != null) {
                    targetObj.put(k, v);
                } else {
                    event.put(k, v);
                }
            }

            if (this.target != null) {
                event.put(this.target, targetObj);
            }
        } catch (Exception e) {
            log.warn(event + "kv faild");
            success = false;
        }

        this.postProcess(event, success);

        return event;
    }
}


text:
from __future__ import unicode_literals

from django.contrib.sites.managers import CurrentSiteManager
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _

@python_2_unicode_compatible
class BaseEntry(models.Model):

    site = models.ForeignKey(
            'sites.Site',
            on_delete=models.CASCADE,
            verbose_name=_('Site'))
    key = models.CharField(
            max_length=63,
            verbose_name=_('Key'))

    objects = CurrentSiteManager()
    all_objects = models.Manager()

    class Meta:
        abstract = True

    def __str__(self):
        return self.key

    @staticmethod
    def autocomplete_search_fields():
        return ('key__icontains', )

    def natural_key(self):
        return (self.key, )


text:
package org.lwjgl.vulkan;

/** Applications may wish to export memory to other Vulkan instances or other APIs, or import memory from other Vulkan instances or other APIs to enable Vulkan workloads to be split up across application module, process, or API boundaries. This extension enables applications to create exportable Vulkan memory objects such that the underlying resources can be referenced outside the Vulkan instance that created them. */
public final class NVExternalMemory {

	/** The extension specification version. */
	public static final int VK_NV_EXTERNAL_MEMORY_SPEC_VERSION = 1;

	/** The extension name. */
	public static final String VK_NV_EXTERNAL_MEMORY_EXTENSION_NAME = "VK_NV_external_memory";

	/**
	 * Extends {@code VkStructureType}.
	 *
	 *
Enum values:

	 *
	 *

	 *
{@link #VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_NV STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_NV}

	 *
{@link #VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_NV STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_NV}

	 *

	 */
	public static final int
		VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_NV = 1000056000,
		VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_NV       = 1000056001;

	private NVExternalMemory() {}

}


text:
module Rtris::Scenes
  class Empty
    def initialize(sound)
    end

    def terminate
    end

    def update
    end

    def draw
    end

    def button_down(id)
    end

    def button_up(id)
    end
  end
end


text:
"""A collection of hemodynamic response functions."""
import numpy as np
import scipy.stats as stats

def double_gamma(width=32, TR=1, a1=6.0, a2=12., b1=0.9, b2=0.9, c=0.35):
    """
    Returns a HRF.  Defaults are the canonical parameters.
    """

    x_range = np.arange(0,width,TR)
    d1 = a1*b1
    d2 = a2*b2

    # Vectorized
    hrf = ((x_range / d1) ** a1 * np.exp((d1 - x_range) / b1)) - (
            c * (x_range / d2) ** a2 *np.exp((d2 - x_range) / b2))

    return hrf

def preturb_canonical(fraction, width, TR, prng=None):
    """
    Add scaled (by <fraction> (0-1)) white noise to a randomly selected
    canonical double gamma HRF parameter.  Returns a dict of new HRF
    parameters, all but the perturbed one match canonical values.  It also
    returns a numpy RandomState() object.

    If a RandomState() was passed via prng it is returned, having been used for
    sampling by this function.  If <prng> was None or a number, a RandomState()
    was created and is (also) now returned.

    <width> and <TR> are not used here but are needed for HRF calculations
    downstream.
    """

    prng = process_prng(prng)

    np.random.set_state(prng.get_state())
        ## Pass random state from prng to np so that
        ## stats.<> will inherit the right state.
        ## There does not seem to be a way to set random
        ## state of stats.* functions directly.

    params = {a1:6.0, a2:12.0, b1:0.9, b2:0.9, c:0.35}
        ## The conanoical parameters

    keys = params.keys()
    np.random.shuffle(keys)
    par = params[keys[0]]

    params[keys[0]] = stats.norm.rvs(loc=par, scale=par/(1.*fraction))
        ## Grab a random value from the normal curve
        ## with its SD reduced by 0.fraction

    params['width'] = width
    params['TR'] = TR
        ## Add the remaining (unpreturbed) params

    prng.set_state(np.random.get_state())
        ## Pass the seed state from np back to
        ## prng, then we can use prng again...

    return params, prng


text:
"""Utility to display a summary of JSON-format GM results, and exit with
a nonzero errorcode if there were non-ignored failures in the GM results.

Usage:
  python display_json_results.py <filename>

TODO(epoger): We may want to add flags to set the following:
- which error types cause a nonzero return code
- maximum number of tests to list for any one ResultAccumulator
  (to keep the output reasonably short)
"""

__author__ = 'Elliot Poger'

import json
import sys

# These constants must be kept in sync with the kJsonKey_ constants in
# gm_expectations.cpp !
JSONKEY_ACTUALRESULTS = 'actual-results'
JSONKEY_ACTUALRESULTS_FAILED = 'failed'
JSONKEY_ACTUALRESULTS_FAILUREIGNORED = 'failure-ignored'
JSONKEY_ACTUALRESULTS_NOCOMPARISON = 'no-comparison'
JSONKEY_ACTUALRESULTS_SUCCEEDED = 'succeeded'

class ResultAccumulator(object):
  """Object that accumulates results of a given type, and can generate a
     summary upon request."""

  def __init__(self, name, do_list, do_fail):
    """name: name of the category this result type falls into
       do_list: whether to list all of the tests with this results type
       do_fail: whether to return with nonzero exit code if there are any
                results of this type
    """
    self._name = name
    self._do_list = do_list
    self._do_fail = do_fail
    self._testnames = []

  def AddResult(self, testname):
    """Adds a result of this particular type.
       testname: (string) name of the test"""
    self._testnames.append(testname)

  def ShouldSignalFailure(self):
    """Returns true if this result type is serious (self._do_fail is True)
       and there were any results of this type."""
    if self._do_fail and self._testnames:
      return True
    else:
      return False

  def GetSummaryLine(self):
    """Returns a single-line string summary of all results added to this
       accumulator so far."""
    summary = ''
    if self._do_fail:
      summary += '[*] '
    else:
      summary += '[ ] '
    summary += str(len(self._testnames))
    summary += ' '
    summary += self._name
    if self._do_list:
      summary += ': '
      for testname in self._testnames:
        summary += testname
        summary += ' '
    return summary

def Display(filepath):
  """Displays a summary of the results in a JSON file.
     Returns True if the results are free of any significant failures.
     filepath: (string) path to JSON file"""

  # Map labels within the JSON file to the ResultAccumulator for each label.
  results_map = {
    JSONKEY_ACTUALRESULTS_FAILED:
        ResultAccumulator(name='ExpectationsMismatch',
                          do_list=True, do_fail=True),
    JSONKEY_ACTUALRESULTS_FAILUREIGNORED:
        ResultAccumulator(name='IgnoredExpectationsMismatch',
                          do_list=True, do_fail=False),
    JSONKEY_ACTUALRESULTS_NOCOMPARISON:
        ResultAccumulator(name='MissingExpectations',
                          do_list=False, do_fail=False),
    JSONKEY_ACTUALRESULTS_SUCCEEDED:
        ResultAccumulator(name='Passed',
                          do_list=False, do_fail=False),
  }

  success = True
  json_dict = json.load(open(filepath))
  actual_results = json_dict[JSONKEY_ACTUALRESULTS]
  for label, accumulator in results_map.iteritems():
    results = actual_results[label]
    if results:
      for result in results:
        accumulator.AddResult(result)
    print accumulator.GetSummaryLine()
    if accumulator.ShouldSignalFailure():
      success = False
  print '(results marked with [*] will cause nonzero return value)'
  return success

if '__main__' == __name__:
  if len(sys.argv) != 2:
    raise Exception('usage: %s <input-json-filepath>' % sys.argv[0])
  sys.exit(0 if Display(sys.argv[1]) else 1)


text:
package org.datatransferproject.security;

import com.google.common.base.Preconditions;
import org.datatransferproject.api.launcher.Monitor;

import javax.crypto.SecretKey;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * Methods for creating {@link Decrypter} classes for given types of encryption keys and algorithms.
 */
public class DecrypterFactory {
  private Monitor monitor;

  public DecrypterFactory(Monitor monitor) {
    this.monitor = monitor;
  }

  /**
   * Creates a {@link DecrypterImpl} with the given {@link SecretKey} for use with "AES"-based
   * symmetric encryption.
   */
  public Decrypter create(SecretKey key) {
    Preconditions.checkArgument(key.getAlgorithm().equals("AES"));
    return new DecrypterImpl(CryptoTransformation.AES_CBC_NOPADDING, key, monitor);
  }

  /**
   * Creates a {@link DecrypterImpl} with the given {@link PublicKey} for use with "RSA"-based
   * asymmetric encryption.
   */
  public Decrypter create(PublicKey key) {
    Preconditions.checkArgument(key.getAlgorithm().equals("RSA"));
    return new DecrypterImpl(CryptoTransformation.RSA_ECB_PKCS1, key, monitor);
  }

  /**
   * Creates a {@link DecrypterImpl} with the given {@link PrivateKey} for use with "RSA"-based
   * asymmetric encryption.
   */
  public Decrypter create(PrivateKey key) {
    Preconditions.checkArgument(key.getAlgorithm().equals("RSA"));
    return new DecrypterImpl(CryptoTransformation.RSA_ECB_PKCS1, key, monitor);
  }
}


text:
require 'optparse'
require_relative '../puppet_check'

# the command line interface for PuppetCheck
class PuppetCheck::CLI
  # run method for the cli
  def self.run(args)
    # gather the user arguments
    settings = parse(args)
    raise 'puppet-check: no paths specified; try using --help' if args.empty?

    # run PuppetCheck with specified paths
    PuppetCheck.new.run(settings, args)
  end

  # parse the user arguments
  def self.parse(args)
    # show help message if no args specified
    args = %w[-h] if args.empty?

    # initialize settings hash
    settings = {}

    opt_parser = OptionParser.new do |opts|
      # usage
      opts.banner = 'usage: puppet-check [options] paths'

      # base options
      opts.on('--version', 'Display the current version.') do
        puts 'puppet-check 2.2.0'
        exit 0
      end

      # bool options
      opts.on('--fail-on-warnings', 'Fail on warnings') { settings[:fail_on_warnings] = true }
      opts.on('-s', '--style', 'Enable style checks') { settings[:style] = true }
      opts.on('--smoke', 'Enable smoke testing') { settings[:smoke] = true }
      opts.on('-r', '--regression', 'Enable regression testing (in progress, do not use)') { settings[:regression] = true }

      # ssl key options for eyaml checks
      opts.on('--public cert.pem', String, 'Public key for EYAML checks') { |arg| settings[:public] = arg }
      opts.on('--private cert.pem', String, 'Private key for EYAML checks') { |arg| settings[:private] = arg }

      # formatting options
      opts.on('-o', '--output format', String, 'Format for results output (default is text): text, json, or yaml') { |arg| settings[:output_format] = arg }

      # octocatalog-diff options
      opts.on('--octoconfig config_file', String, 'Octocatalog-diff configuration file to use') { |arg| settings[:octoconfig] = arg }
      opts.on('-n', '--octonodes node1.example.com,node2.example.com', Array, 'Octocatalog-diff nodes to test catalog on') { |arg| settings[:octonodes] = arg }

      # arguments to style checkers
      opts.on('--puppet-lint arg_one,arg_two', Array, 'Arguments for PuppetLint ignored checks') do |puppetlint_args|
        settings[:puppetlint_args] = puppetlint_args.map { |arg| "--#{arg}" }
      end
      opts.on('-c', '--config file', String, 'Load PuppetLint options from file') do |file|
        settings[:puppetlint_args] = File.read(file).split("\n")
      end
      opts.on('--rubocop arg_one,arg_two', String, 'Arguments for Rubocop disabled cops') { |arg| settings[:rubocop_args] = ['--except', arg] }
    end

    # remove atched args and return settings
    opt_parser.parse!(args)
    settings
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Sabio.Web.Models.Requests
{
    public class HomeStatisticsUpdateRequest
    {
        public string Title1 { get; set; }
        public string Number1 { get; set; }
        public bool AutoPopulate1 { get; set; }
        public string Title2 { get; set; }
        public string Number2 { get; set; }
        public bool AutoPopulate2 { get; set; }
        public string Title3 { get; set; }
        public string Number3 { get; set; }
        public bool AutoPopulate3 { get; set; }
        public string Title4 { get; set; }
        public string Number4 { get; set; }
        public bool AutoPopulate4 { get; set; }
    }
}


text:
from jnpr.junos.utils.fs import FS
from jnpr.junos.exception import RpcError
from jnpr.junos.jxml import INHERIT
from lxml.builder import E

def facts_domain(junos, facts):
    """
    The following facts are required:
        facts['hostname']

    The following facts are assigned:
        facts['domain']
        facts['fqdn']
    """

    try:
        domain_filter_xml = E('configuration', E('system', E('domain-name')))
        domain = junos.rpc.get_config(filter_xml=domain_filter_xml,
                                      options=INHERIT)
        domain_name = domain.xpath('.//domain-name')
        if len(domain_name) > 0:
            facts['domain'] = domain_name[0].text
            facts['fqdn'] = facts['hostname'] + '.' + facts['domain']
            return
    except RpcError:
        pass

    fs = FS(junos)
    file_content = fs.cat('/etc/resolv.conf') or fs.cat('/var/etc/resolv.conf')
    words = file_content.split() if file_content is not None else ''
    if 'domain' not in words:
        facts['domain'] = None
        facts['fqdn'] = facts['hostname']
    else:
        idx = words.index('domain') + 1
        facts['domain'] = words[idx]
        facts['fqdn'] = facts['hostname'] + '.' + facts['domain']


text:
'use strict';

const fs          = require('fs');

const Promise 		= require('bluebird');
const SilentError = require('silent-error');

const Command     = require('../../models/command');
const debug 		  = require('debug')('rstc:commands/command/send-redis-command')

// Sub-command of Command.
module.exports = Command.extend({
	name: 'send-redis-command',
	description: 'Send a Redis command specified in a JSON file.',
	works: 'everywhere',
	availableOptions: [],
	anonymousOptions: [
    '<redis-command-file>'
  ],

	run: function(commandOptions, rawArgs) {
		debug('commandOptions: %o', commandOptions)
		debug('rawArgs: ', rawArgs);

		if (!this.superCommand.request) {
			const message = 'System error: Either a request was not' +
											' succesfully created in command "' + this.superCommand.name +
											'" or it wasn\'t passed down to command "' + this.name + '".';
			throw Error(message);
		}

    commandOptions.url = commandOptions.headers.Origin + '/commands/sendRedisCommand';

    commandOptions.path = rawArgs.shift();
		if(!commandOptions.path) {
			this.printBasicHelp();
			const message = 'Please provide a path to the JSON file containing the Redis command.';
			return Promise.reject(new SilentError(message));
		}

    let command;
		try {
      command = JSON.parse(fs.readFileSync(commandOptions.path, 'utf-8'));
		} catch(e) {
			const message = 'Invalid JSON in the command file:\n' + e;
			return Promise.reject(new SilentError(message));
		}

    commandOptions.body = command;

		const Task = this.availableTasks.SendRedisCommand;
		const task = new Task({
      request: this.superCommand.request,
      settings: this.settings,
      cli: this.cli,
			ui: this.ui
		});

		return task.run(commandOptions);
	}
});


text:
namespace base {

// Returns a filesystem-safe key that corresponds to the application whose start
// URL is |url|. Returns nullopt if |url| is not a valid URL.
Optional<std::string> GetApplicationKey(const GURL& url);

}  // namespace base

#endif  // COBALT_BASE_GET_APPLICATION_KEY_H_


text:
package org.apache.beam.sdk.values.reflect;

import java.util.List;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.utils.POJOUtils;

/** A factory for creating {@link FieldValueGetter} objects for a POJO. */
public class PojoValueGetterFactory implements FieldValueGetterFactory {
  @Override
  public List<FieldValueGetter> createGetters(Class<?> targetClass, Schema schema) {
    return POJOUtils.getGetters(targetClass, schema);
  }
}


text:
© <time datetime="{{ site.time | date_to_xmlschema }}">2015-{{ site.time | date: '%Y' }}</time> {{ site.title }}

    {% include blogroll.html %}


text:
class Instance::AsCopier < Instance
  def copy_with_new_name_id(new_name_id, as_username)
    raise "Copied record would have same name id." if new_name_id.eql?(name_id)
    new = dup
    new.name_id = new_name_id
    new.created_by = new.updated_by = as_username
    new.save!
    new
  end

  def copy_with_citations_to_new_reference(params, as_username)
    new = nil
    raise "Need a reference" if params[:reference_id].blank?
    raise "Ref must be different" if params[:reference_id].to_i == reference.id
    raise "Unrecognized reference id" if params[:reference_id].to_i <= 0
    raise "No such ref" if Reference.find(params[:reference_id].to_i).blank?
    new_reference_id_string = params[:reference_id]
    new_page = params[:page]
    new_instance_type_id = params[:instance_type_id]
    new_is_draft = params[:draft]
    ActiveRecord::Base.transaction do
      new = dup
      new_reference_id = new_reference_id_string.to_i
      new.reference_id = new_reference_id
      new.instance_type_id = new_instance_type_id
      new.page = new_page
      new.draft = new_is_draft
      new.created_by = new.updated_by = as_username
      new.uri = nil
      new.save!
      reverse_of_this_is_cited_by.each do |citer|
        new_citer = Instance.new
        new_citer.name_id = citer.name.id
        new_citer.reference_id = new_reference_id
        new_citer.cited_by_id = new.id
        new_citer.cites_id = citer.cites_id
        new_citer.instance_type_id = citer.instance_type_id
        new_citer.verbatim_name_string = citer.verbatim_name_string
        new_citer.bhl_url = citer.bhl_url
        new_citer.page = new_page
        new_citer.created_by = new_citer.updated_by = as_username
        new_citer.save!
      end
    end
    new
  end
end


text:
/* eslint-disable global-require */
import main from './client';

function run() {
  // Run the application when both DOM is ready and page content is loaded
  if (['complete', 'loaded', 'interactive'].includes(document.readyState) && document.body) {
    main();
  } else {
    document.addEventListener('DOMContentLoaded', main, false);
  }
}

if (!global.Intl) {
  // You can show loading banner here

  require.ensure(
    [
      // Add all large polyfills here
      'intl',
      'intl/locale-data/jsonp/fr.js',
      // POLYFILLS FOR GENERATOR
    ],
    require => {
      // and require them here
      require('intl');
      require('intl/locale-data/jsonp/fr.js');
      // REQUIRE FOR GENERATOR
      run();
    },
    'polyfills',
  );
} else {
  run();
}


text:
import { NgModule } from '@angular/core';
import { PublicFeatureComponent } from './public-feature.component';
import { PublicRoutingModule } from './public-feature.router';

/**
 * Registers all public features and routes which require no authentication
 */
@NgModule({
  imports: [
    PublicRoutingModule
  ],
  declarations: [
    PublicFeatureComponent
  ]
})
export class PublicFeatureModule {
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_15.c
Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml
Template File: sources-sinks-15.tmpl.c
*/
/*
 * @description
 * CWE: 789 Uncontrolled Memory Allocation
 * BadSource: rand Set data to result of rand(), which may be zero
 * GoodSource: Small number greater than zero
 * Sinks:
 *    GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated
 *    BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated
 * Flow Variant: 15 Control flow: switch(6) and switch(7)
 *
 * */

#include "std_testcase.h"

#ifndef _WIN32
#include <wchar.h>
#endif

#define HELLO_STRING "hello"

#ifndef OMITBAD

void CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_15_bad()
{
    size_t data;
    /* Initialize data */
    data = 0;
    switch(6)
    {
    case 6:
        /* POTENTIAL FLAW: Set data to a random value */
        data = rand();
        break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
    switch(7)
    {
    case 7:
    {
        char * myString;
        /* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
         * for the strcpy() function to not cause a buffer overflow */
        /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
        if (data > strlen(HELLO_STRING))
        {
            myString = (char *)malloc(data*sizeof(char));
            /* Copy a small string into myString */
            strcpy(myString, HELLO_STRING);
            printLine(myString);
            free(myString);
        }
        else
        {
            printLine("Input is less than the length of the source string");
        }
    }
    break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G1() - use badsource and goodsink by changing the second switch to switch(8) */
static void goodB2G1()
{
    size_t data;
    /* Initialize data */
    data = 0;
    switch(6)
    {
    case 6:
        /* POTENTIAL FLAW: Set data to a random value */
        data = rand();
        break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
    switch(8)
    {
    case 7:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    default:
    {
        char * myString;
        /* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough
         * for the strcpy() function to not cause a buffer overflow */
        /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
        if (data > strlen(HELLO_STRING) && data < 100)
        {
            myString = (char *)malloc(data*sizeof(char));
            /* Copy a small string into myString */
            strcpy(myString, HELLO_STRING);
            printLine(myString);
            free(myString);
        }
        else
        {
            printLine("Input is less than the length of the source string or too large");
        }
    }
    break;
    }
}

/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second switch */
static void goodB2G2()
{
    size_t data;
    /* Initialize data */
    data = 0;
    switch(6)
    {
    case 6:
        /* POTENTIAL FLAW: Set data to a random value */
        data = rand();
        break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
    switch(7)
    {
    case 7:
    {
        char * myString;
        /* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough
         * for the strcpy() function to not cause a buffer overflow */
        /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
        if (data > strlen(HELLO_STRING) && data < 100)
        {
            myString = (char *)malloc(data*sizeof(char));
            /* Copy a small string into myString */
            strcpy(myString, HELLO_STRING);
            printLine(myString);
            free(myString);
        }
        else
        {
            printLine("Input is less than the length of the source string or too large");
        }
    }
    break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
}

/* goodG2B1() - use goodsource and badsink by changing the first switch to switch(5) */
static void goodG2B1()
{
    size_t data;
    /* Initialize data */
    data = 0;
    switch(5)
    {
    case 6:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    default:
        /* FIX: Use a relatively small number for memory allocation */
        data = 20;
        break;
    }
    switch(7)
    {
    case 7:
    {
        char * myString;
        /* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
         * for the strcpy() function to not cause a buffer overflow */
        /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
        if (data > strlen(HELLO_STRING))
        {
            myString = (char *)malloc(data*sizeof(char));
            /* Copy a small string into myString */
            strcpy(myString, HELLO_STRING);
            printLine(myString);
            free(myString);
        }
        else
        {
            printLine("Input is less than the length of the source string");
        }
    }
    break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
}

/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first switch */
static void goodG2B2()
{
    size_t data;
    /* Initialize data */
    data = 0;
    switch(6)
    {
    case 6:
        /* FIX: Use a relatively small number for memory allocation */
        data = 20;
        break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
    switch(7)
    {
    case 7:
    {
        char * myString;
        /* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
         * for the strcpy() function to not cause a buffer overflow */
        /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
        if (data > strlen(HELLO_STRING))
        {
            myString = (char *)malloc(data*sizeof(char));
            /* Copy a small string into myString */
            strcpy(myString, HELLO_STRING);
            printLine(myString);
            free(myString);
        }
        else
        {
            printLine("Input is less than the length of the source string");
        }
    }
    break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
}

void CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_15_good()
{
    goodB2G1();
    goodB2G2();
    goodG2B1();
    goodG2B2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_15_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_15_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
export const toggleEventTypeDisplay = (state, eventType) => {
  const newState = Object.assign({}, state);
  const selected = [];
  let eventCount = 0;

  Object.values(newState.eventTypes).forEach((type) => {
    eventCount += 1;
    if (type.display) {
      selected.push(type.id);
    }
  });

  if (selected.length === 1 && eventType.id === selected[0]) {
    // If only one event is selected and is being deselected,
    // then show all and set dirty to false
    Object.assign(state, { dirty: false });

    Object.values(newState.eventTypes).forEach((type) => {
      Object.assign(type, {
        display: true,
      });
    });
  } else if (selected.length === eventCount - 1 && selected.indexOf(eventType.id) === -1) {
    // If only one event is unselected and is being selected,
    // then show all and set dirty to true
    Object.assign(state, { dirty: true });

    Object.values(newState.eventTypes).forEach((type) => {
      Object.assign(type, {
        display: true,
      });
    });
  } else if (selected.length === eventCount && !state.dirty) {
    // If all events are selected and dirty is false,
    // then deselect the all other than the selected and set dirty to true
    Object.assign(state, { dirty: true });

    Object.values(newState.eventTypes)
      .filter(type => type.id !== eventType.id)
      .forEach((type) => {
        Object.assign(type, {
          display: false,
        });
      });
  } else {
    // If none of the edge cases above, then toggle as usual
    Object.assign(newState.eventTypes, {
      [eventType.id]: Object.assign({}, eventType, {
        display: !eventType.display,
      }),
    });
  }

  return Object.assign({}, state.eventTypes, newState.eventTypes);
};

export const setEventsForEventTypeId = (state, eventTypeId, events) => (
  Object.assign({}, state.eventTypes, {
    [eventTypeId]: Object.assign({}, state.eventTypes[eventTypeId], {
      events,
      loaded: true,
    }),
  })
);


text:
using System.Runtime.InteropServices;
using System.Timers;
using System;

namespace VBScripting
{
    ///  Wraps the  System.Timers.Timer class for VBScript.
    [ProgId( "VBScripting.Timer" ),
        ClassInterface(ClassInterfaceType.None),
        Guid("2650C2AB-C020-495F-AB4D-6C61BD463EA4")]
    public class Timer : ITimer
    {
        private System.Timers.Timer timer;

        ///  Gets or sets the number of milliseconds between when the Start method is called and when the callback is invoked. Default is 60,000. Max is 2,147,483,647 milliseconds, or 24 days 20 hours 31 minutes 23.647 seconds.
        public int Interval { get; set; }
        ///  Gets or sets a reference to the VBScript Sub that is called when the interval has elapsed.
        public object Callback { get; set; }
        ///  Gets or sets a boolean determining whether to repeatedly invoke the callback. Default is False. If False, the callback is invoked only once, until the timer is restarted with the Start method.
        public bool AutoReset { get; set; }

        ///  Constructor
        public Timer()
        {
            Interval = 60000;
        }
        ///  Starts or restarts the timer.
        public void Start()
        {
            if (timer != null)
                timer.Stop();

            timer = new System.Timers.Timer();
            timer.Interval = Interval;
            timer.AutoReset = AutoReset;
            timer.Elapsed += Elapsed;
            timer.Start();
        }
        private void Elapsed(object sender, ElapsedEventArgs e)
        {
            if (Callback != null)
                ComEvent.InvokeComCallback(Callback);
        }
        ///  Stops the timer.
        public void Stop()
        {
            Dispose();
        }
        ///  Disposes of the timer's resources.
        public void Dispose()
        {
            if (timer != null)
            {
                timer.Stop();
                timer.Dispose();
            }
        }
        ///  Gets or sets the interval in hours.
        public float IntervalInHours
        {
            get { return (float) Interval/3600000; }
            set { Interval = Convert.ToInt32(value*3600000); }
        }
    }
    ///  COM interface for VBScripting.Timer
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch),
        Guid("2650C2AB-C021-495F-AB4D-6C61BD463EA4")]
    public interface ITimer
    {
        ///
        [DispId(0)]
        int Interval { get; set; }
        ///
        [DispId(1)]
        object Callback { get; set; }
        ///
        [DispId(2)]
        bool AutoReset { get; set; }
        ///
        [DispId(3)]
        void Start();
        ///
        [DispId(4)]
        void Stop();
        ///
        [DispId(5)]
        void Dispose ();
        ///
        [DispId(6)]
        float IntervalInHours { get; set; }
    }
}


text:
import { SourceResolver } from '../src/source-resolver';
import { expect } from 'chai';
import { describe, it } from 'mocha';

describe('SourceResolver', () => {
  it('should be constructible', () => {
    const a: SourceResolver = new SourceResolver();
    expect(a.sources.length).to.equal(0);
  });
});


text:
<?php

use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel backend\models\search\UserHistorySearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('common', 'User History');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-history-index">

	<?php // echo $this->render('_search', ['model' => $searchModel]); ?>

	<?php echo GridView::widget([
		'dataProvider' => $dataProvider,
		'filterModel' => $searchModel,
		'columns' => [
			['class' => 'yii\grid\SerialColumn'],

			//'id',
			[
				'attribute' => 'user_id',
				'value' => function ($model)
				{
					return $model->user->username;
				},
			],
			[
				'attribute' => 'game_id',
				'value' => function ($model)
				{
					return $model->game->name;
				},
				'filter' => ArrayHelper::map(\common\models\Game::find()->all(), 'id', 'name'),
			],
			[
				'attribute' => 'server_id',
				'value' => function ($model)
				{
					return $model->server->server_name;
				},
				'filter' => ArrayHelper::map(\common\models\GameServer::find()->all(), 'id', 'server_name'),
			],
			'created_at:datetime',
			[
				'class' => \common\grid\EnumColumn::className(),
				'attribute' => 'status',
				'enum' => \common\models\UserHistory::getStatus(),
			],

			[
				'class' => 'yii\grid\ActionColumn',
				'template' => '{view}{delete}',
			],
		],
	]); ?>

</div>


text:
A small remake inspired by the old classic game Missile Command

The repository project is missing some Unity Store audio and art which I'm yet to replace with placeholders. Expect missing materials and no audio for now.


text:
package alluxio.cli.fs.command;

import alluxio.client.file.FileSystem;
import alluxio.client.lineage.AlluxioLineage;
import alluxio.client.lineage.LineageContext;
import alluxio.client.lineage.options.DeleteLineageOptions;
import alluxio.exception.AlluxioException;

import org.apache.commons.cli.CommandLine;

import java.io.IOException;

import javax.annotation.concurrent.ThreadSafe;

/**
 * Deletes a lineage by its id. If the cascade flag is set to true it performs a cascading delete.
 */
@ThreadSafe
public final class DeleteLineageCommand extends AbstractFileSystemCommand {

  /**
   * @param fs the filesystem of Alluxio
   */
  public DeleteLineageCommand(FileSystem fs) {
    super(fs);
  }

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

  @Override
  protected int getNumOfArgs() {
    return 2;
  }

  @Override
  public int run(CommandLine cl) throws AlluxioException, IOException {
    String[] args = cl.getArgs();
    AlluxioLineage tl = AlluxioLineage.get(LineageContext.INSTANCE);
    long lineageId = Long.parseLong(args[0]);
    boolean cascade = Boolean.parseBoolean(args[1]);
    DeleteLineageOptions options = DeleteLineageOptions.defaults().setCascade(cascade);
    tl.deleteLineage(lineageId, options);
    System.out.println("Lineage " + lineageId + " has been deleted.");
    return 0;
  }

  @Override
  public String getUsage() {
    return "deleteLineage <lineageId> <cascade(true|false)>";
  }

  @Override
  public String getDescription() {
    return "Deletes a lineage. If cascade is specified as true, "
      + "dependent lineages will also be deleted.";
  }
}


text:
FactoryGirl.define do
  factory :post do
    title 'Awesome title'
    body "The *quick brown* fox `jumps` over the lazy dog.\n" * 20
    public_scope 'admin'
  end
end


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * Object.prototype.hasOwnProperty can't be used as a constructor
 *
 * @path ch15/15.2/15.2.4/15.2.4.5/S15.2.4.5_A7.js
 * @description Checking if creating "new Object.prototype.hasOwnProperty" fails
 */

var FACTORY = Object.prototype.hasOwnProperty;

try {
  instance = new FACTORY;
  $FAIL('#1: Object.prototype.hasOwnProperty can\'t be used as a constructor');
} catch (e) {
  $PRINT(e);

}


text:
//
//  MSZIntValidator.h
//  MSZValidatorFramework
//
// Created by Marek Szczypinski on 06/04/16.
// Copyright (c) 2016 Marek Szczypiński. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "MSZValidator.h"

/**
 *  The MSZIntValidator class provides a validator that ensures a string contains a valid integer within a specified range.
 */
@interface MSZIntValidator : NSObject <MSZValidator>

/**
 *  Holds the validator's lowest acceptable value.
 *
 *  By default, this property's value is derived from the lowest signed integer available (typically -2147483647).
 */
@property (nonatomic) NSInteger minimum;

/**
 *  Holds the validator's highest acceptable value.
 *
 *  By default, this property's value is derived from the highest signed integer available (typically 2147483647).
 */
@property (nonatomic) NSInteger maximum;

/**
 *  The locale that will be used for the validator.
 *  Unless locale has been set, the validator will use the default locale set with [NSLocale currentLocale].
 */
@property (nonatomic, strong) NSLocale *locale;

/**
 *  Designated initializer
 *
 *  @param minimum minimum value that will be accepted
 *  @param maximum maximum value that will be accepted
 *
 *  @return new MSZIntValidator instance
 */
- (instancetype)initWithMinimum:(NSInteger)minimum andMaximum:(NSInteger)maximum NS_DESIGNATED_INITIALIZER;

/**
 *  Sets the range of the validator to only accept integers between minimum and maximum inclusive.
 *
 *  @param minimum minimum value that will be accepted
 *  @param maximum maximum value that will be accepted
 */
- (void)setRangeWithMinimum:(NSInteger)minimum andMaximum:(NSInteger)maximum;
@end


text:
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.outlook.impl;
import com.wilutions.com.*;

@SuppressWarnings("all")
@CoClass(guid="{C091A980-A463-DB41-5DAE-69E7A5F7FCBC}")
public class _ContactsModuleImpl extends Dispatch implements com.wilutions.mslib.outlook._ContactsModule {
  @DeclDISPID(61440)  public com.wilutions.mslib.outlook._Application getApplication() throws ComException {
    final Object obj = this._dispatchCall(61440,"Application", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return Dispatch.as(obj, com.wilutions.mslib.outlook.impl._ApplicationImpl.class);
  }
  @DeclDISPID(61450)  public com.wilutions.mslib.outlook.OlObjectClass getClass_() throws ComException {
    final Object obj = this._dispatchCall(61450,"Class", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return com.wilutions.mslib.outlook.OlObjectClass.valueOf((Integer)obj);
  }
  @DeclDISPID(61451)  public com.wilutions.mslib.outlook._NameSpace getSession() throws ComException {
    final Object obj = this._dispatchCall(61451,"Session", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return Dispatch.as(obj, com.wilutions.mslib.outlook.impl._NameSpaceImpl.class);
  }
  @DeclDISPID(61441)  public IDispatch getParent() throws ComException {
    final Object obj = this._dispatchCall(61441,"Parent", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return (IDispatch)obj;
  }
  @DeclDISPID(64441)  public com.wilutions.mslib.outlook.OlNavigationModuleType getNavigationModuleType() throws ComException {
    final Object obj = this._dispatchCall(64441,"NavigationModuleType", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return com.wilutions.mslib.outlook.OlNavigationModuleType.valueOf((Integer)obj);
  }
  @DeclDISPID(8450)  public String getName() throws ComException {
    final Object obj = this._dispatchCall(8450,"Name", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return (String)obj;
  }
  @DeclDISPID(64442)  public Integer getPosition() throws ComException {
    final Object obj = this._dispatchCall(64442,"Position", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return (Integer)obj;
  }
  @DeclDISPID(64442)  public void setPosition(final Integer value) throws ComException {
    assert(value != null);
    this._dispatchCall(64442,"Position", DISPATCH_PROPERTYPUT,value);
  }
  @DeclDISPID(64443)  public Boolean getVisible() throws ComException {
    final Object obj = this._dispatchCall(64443,"Visible", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return (Boolean)obj;
  }
  @DeclDISPID(64443)  public void setVisible(final Boolean value) throws ComException {
    assert(value != null);
    this._dispatchCall(64443,"Visible", DISPATCH_PROPERTYPUT,value);
  }
  @DeclDISPID(64444)  public com.wilutions.mslib.outlook._NavigationGroups getNavigationGroups() throws ComException {
    final Object obj = this._dispatchCall(64444,"NavigationGroups", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return Dispatch.as(obj, com.wilutions.mslib.outlook.impl._NavigationGroupsImpl.class);
  }
  public _ContactsModuleImpl(String progId) throws ComException {
    super(progId, "{000630EB-0000-0000-C000-000000000046}");
  }
  protected _ContactsModuleImpl(long ndisp) {
    super(ndisp);
  }
  public String toString() {
    return "[_ContactsModuleImpl" + super.toString() + "]";
  }
}


text:
[![Build Status](https://travis-ci.org/PatrickCmd/Yummy-Recipes-App.svg?branch=master)](https://travis-ci.org/PatrickCmd/Yummy-Recipes-App)
[![Coverage Status](https://coveralls.io/repos/github/PatrickCmd/Yummy-Recipes-App/badge.svg?branch=master)](https://coveralls.io/github/PatrickCmd/Yummy-Recipes-App?branch=master)
# Yummy-Recipes-App
Yummy recipes app is an application that allows users  to create, save and share meeting the needs of keeping track of awesome food recipes.

## Functionality
- `Signup` Enables user to create an account
- `Signin` Enables user to login and access his/her dashboard
- `View Account Details` Enables to view his/her account details
- `Add Recipe category` Enables user to create his/her recipe categories
- `Edit Recipe category` Enables user to edit recipe category
- `Delete Recipe Category` User can delete recipe category
- `Add Recipe in category` Enables user to add recipe in category
- `View Recipes in categories` User can view recipes in category
- `Edit Recipe in category`  User edits recipe in category
- `Delete recipe in category` User deletes recipe in category

## Requirements
`python 3.4+, python-pip, virtualenv, flask`

## Installation
First clone this repository
```
$ git clone https://github.com/PatrickCmd/Yummy-Recipes-App.git
$ cd Yummy-Recipes-App
```
Create virtual environment and install it
```
$ virtualenv env
$ source/env/bin/activate
```
Then install all the necessary dependencies
```
pip install -r requirements.txt
```

## Run the application
At the terminal or console type
```
python run.py
```
To run tests run this command at the console/terminal
```
nosetests
```


text:
// Copyright (c) 2011-2015 The Cryptonote developers
// Copyright (c) 2014-2015 XDN developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "SignalHandler.h"

#include <mutex>
#include <sstream>

// epee
#include "include_base_utils.h"

namespace tools {
  std::function<void(void)> SignalHandler::m_handler;

#if defined(WIN32)
  BOOL WINAPI SignalHandler::winHandler(DWORD type) {
    if (CTRL_C_EVENT == type || CTRL_BREAK_EVENT == type) {
      handleSignal();
      return TRUE;
    } else {
      LOG_PRINT_RED_L0("Got control signal " << type << ". Exiting without saving...");
      return FALSE;
    }
    return TRUE;
  }

#else

  void SignalHandler::posixHandler(int /*type*/) {
    handleSignal();
  }
#endif

  void SignalHandler::handleSignal() {
    static std::mutex m_mutex;
    std::unique_lock<std::mutex> lock(m_mutex);
    m_handler();
  }
}