text:
<?php

//// Shared ////
use API\REST\V1\Shared\Functions\HttpResponse;
use API\REST\V1\Shared\Functions\HttpRequest;
use API\REST\V1\Shared\Functions\ArrayManage;
use API\REST\V1\Shared\Functions\ResourceManager;
use API\REST\V1\Shared\Functions\ArrayResponse;

//// Form ////
use API\REST\V1\ACL\Salesforce\Marketingchannel\Form\MarketingchannelFormGET;
use API\REST\V1\ACL\Salesforce\Marketingcampaign\Form\MarketingcampaignFormGET;
use API\REST\V1\ACL\Salesforce\Marketingcampaign\Form\MarketingcampaignFormPostPut;
use API\REST\V1\ACL\Salesforce\Marketingcampaign\Form\MarketingcampaignFormToShowUpdate;

//// Filter ////
use API\REST\V1\ACL\Salesforce\Marketingcampaign\Filter\MarketingcampaignFilterPostPut;

/**
 * Skeleton subclass for representing a row from the 'marketingcampaign' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package    propel.generator.api
 */
class Marketingcampaign extends BaseMarketingcampaign
{
    public function isIdValidResource($idResource,$idCompany){
        return MarketingcampaignQuery::create()
            ->filterByIdmarketingcampaign($idResource)
            ->useMarketingchannelQuery()
            ->filterByIdcompany($idCompany)
            ->endUse()
            ->exists();
    }

    /////////// Start create ///////////
    /**
     * @param $dataArray
     * @param $idCompany
     * @param $userLevel
     * @param null $data
     * @return array
     */
    public function saveResouce($dataArray,$idCompany,$userLevel, $data=null){

        // validamos que el idmarketingchannel que nos envian, exista y corresponda a la compañia
        $idmarketingchannel = MarketingchannelQuery::create()->filterByIdmarketingchannel($dataArray['idmarketingchannel'])->filterByIdcompany($idCompany)->exists();
        if($idmarketingchannel){
            if(!$this->marketingcampaignnameByidmarketingchannelExist($dataArray["marketingcampaign_name"], $dataArray["idmarketingchannel"], $idCompany)){
                foreach ($dataArray as $dataKey => $dataValue){
                    $this->setByName($dataKey,$dataValue,  BasePeer::TYPE_FIELDNAME);
                }
                $this->setMarketingcampaignCreatedAt(date("Y-m-d H:i:s"));
                $this->save();

                //Las columnas permitidas de nuestros foreign keys
                $allowedMarketingchannelColumns = array();
                $marketingchannel = null;

                //Validamos los foreign Keys a los que va tener acceso el usuario para instanciar nuestros formularios
                if(array_key_exists("idmarketingchannel", $dataArray)){

                    //Instanciamos nuestro objeto Marketingchannel
                    $marketingchannel = $this->getMarketingchannel();

                    //Instanciamos nuestro formulario marketingchannelET para obtener los datos que el usuario de acuerdo a su nivel va tener accesso
                    $marketingchannelForm   = MarketingchannelFormGET::init($userLevel);

                    foreach ($marketingchannelForm->getElements() as $element){
                        if($element->getOption('value_options')!=null){
                            $allowedMarketingchannelColumns[$element->getAttribute('name')] = array('label' => $element->getOption('label') ,'value_options' => $element->getOption('value_options'));
                        }else{
                            $allowedMarketingchannelColumns[$element->getAttribute('name')] = $element->getOption('label');
                        }
                    }
                }
                //Mandamos a llamar a nuestra funcion create para darle el formato a nuestra respuesta pasandole los siguientes parametros
                //1. El objeto marketingcampaign "this"
                //2. Los elementos que van a ir como _embebed para removerlos(en este caso idmarketingchannel),
                //3. Las columnas permitidas e los foreignKeys
                //4. el objeto company que va ir como __embebed = "marketingchannel"
                $bodyResponse = $this->createBodyResponse($this,array('idmarketingchannel'),array('marketingchannel' => $allowedMarketingchannelColumns),array($marketingchannel));
                $this->save();
                return array('status_code' => 201, 'details' => $bodyResponse);

            }else{
                $bodyResponse = "marketingcampaign_name ". "'".$dataArray["marketingcampaign_name"]."'". " already exists in the idmarketingchannel ". "'".$dataArray["idmarketingchannel"]."'";
                return array('status_code' => 409, 'details' => $bodyResponse);
            }
        }else{
            $bodyResponse = 'Invalid idmarketingchannel';
            return array('status_code' => 409, 'details' => $bodyResponse);
        }
    }

    /**
     * @param $marketingcampaignname
     * @param $idmarketingchannel
     * @param $idCompany
     * @return bool
     */
    public function marketingcampaignnameByidmarketingchannelExist($marketingcampaignname, $idmarketingchannel, $idCompany){
        return MarketingcampaignQuery::create()->filterByMarketingcampaignName($marketingcampaignname)->filterByIdmarketingchannel($idmarketingchannel)->useMarketingchannelQuery()->filterByIdcompany($idCompany)->endUse()->exists();
    }

    /**
     * @param $marketingcampaign
     * @param array $voidElements
     * @param array $allowedColumns
     * @param array $halResources
     * @return array
     */
    public function createBodyResponse($marketingcampaign, array $voidElements = null, array $allowedColumns,array $halResources=null){

        //Guardamos en un arrglo los datos de nuestro recurso
        $marketingcampaignArray = $marketingcampaign->toArray(\BasePeer::TYPE_FIELDNAME);

        //Verificamos si hay elementos que hay que remover
        if($voidElements!=null){
            foreach ($voidElements as $element){
                unset($marketingcampaignArray[$element]);
            }
        }

        //Comnezamos a darle formato a nuestra respuesta.

        //Los links
        $body = array(
            "_links" => array(
                "self" => array(
                    "href" =>URL_API.'/v'.API_VERSION.'/'.MODULE.'/marketingcampaign/'.$marketingcampaign->getPrimaryKey()
                ),
            ),
        );

        //Los datos del recurso
        foreach ($marketingcampaignArray as $marketingcampaignKey => $marketingcampaignValue){
            $body[$marketingcampaignKey] = $marketingcampaignValue; // Los datos del recurso
        }

        //Verificamos si hay elementos recursos _embebed
        if($halResources!=null){
            foreach ($halResources as $halResource){
                if($halResource!=null){
                    if(!isset($body[strtolower(get_class($halResource))])){
                        $body[strtolower(get_class($halResource))] = array(
                            "_links" => array(
                                "self" => array(
                                    "href" =>URL_API.'/v'.API_VERSION.'/'.MODULE.'/'.strtolower(get_class($halResource)).'/'.$halResource->getPrimaryKey()
                                ),
                            ),
                        );
                        $halResourceArray = $halResource->toArray(\BasePeer::TYPE_FIELDNAME);
                        $halResourceName = strtolower(get_class($halResource));

                        //Los datos del recurso __embedded
                        if(isset($allowedColumns[$halResourceName])){
                            foreach($allowedColumns[$halResourceName] as $column => $value){
                                $body[$halResourceName][$column] = $halResourceArray[$column];
                            }
                        }
                    }else{
                        $body[strtolower(get_class($halResource))] = array(
                            "_links" => array(
                                "self" => array(
                                    "href" =>URL_API.'/v'.API_VERSION.'/'.MODULE.'/'.strtolower(get_class($halResource)).'/'.$halResource->getPrimaryKey()
                                ),
                            ),
                        );
                        if(isset($allowedColumns[$halResourceName])){
                            foreach($allowedColumns[$halResourceName] as $column){
                                $body[$halResourceName][$column] = $halResourceArray[$column];
                            }
                        }
                    }
                }
            }
        }

        $body[strtolower(get_class($halResource))] = array(
            'idmarketingchannel' => $body['marketingchannel']['idmarketingchannel'],
            'marketingchannel_name' => $body['marketingchannel']['marketingchannel_name'],
        );

        // Retornamos nuestra respuesta
        return $body;
    }
    /////////// End create ///////////

    /////////// Start get ///////////
    /**
     * @param $id
     * @return Marketingcampaign|Marketingcampaign[]|mixed
     */
    public function getEntity($id){
        $entity = MarketingcampaignQuery::create()->findPk($id);
        return $entity;
    }

    /**
     * @param $entity
     * @param $userLevel
     * @return array
     */
    public function getEntityResponse($entity,$userLevel){
        //Obtenemos nuestra entidad marketingcampaign en forma de arreglo
        $entityArray = $entity->toArray(BasePeer::TYPE_FIELDNAME);

        //Los Links
        $response = array(
            "_links" => array(
                "self" => array(
                    "href" =>  URL_API."/v".API_VERSION."/".MODULE."/marketingcampaign/".$entity->getIdmarketingcampaign(),
                ),
            ),
        );
        //El ACL

        //Instanciamos nuestros formularios para obtener las columnas que el usuario va poder tener acceso
        $marketingcampaignForm = MarketingcampaignFormGET::init($userLevel);
//        $marketingchannelForm = MarketingchannelFormGET::init($userLevel);

        foreach ($marketingcampaignForm->getElements() as $element){
            if($element->getOption('value_options')!=null){
                $response["ACL"][$element->getAttribute('name')] = array('label' => $element->getOption('label') ,'value_options' => $element->getOption('value_options'));
                $response[$element->getAttribute('name')] = $entityArray[$element->getAttribute('name')];
            }else{
                if($element->getAttribute('name')!="idmarketingchannel"){
                    $response["ACL"][$element->getAttribute('name')] = $element->getOption('label');
                    $response[$element->getAttribute('name')] = $entityArray[$element->getAttribute('name')];
                }
            }
        }
//        $response["ACL"]["marketingchannel"]=array(
//            "idmarketingchannel" =>  $marketingchannelForm->get("idmarketingchannel")->getOption('label'),
//            "marketingchannel_name" =>  $marketingchannelForm->get("marketingchannel_name")->getOption('label'),
//        );

        $marketingchannel = $entity->getMarketingchannel();
        $response["marketingchannel"] = array(
            "_links" => array(
                "self" => array(
                    "href" =>  URL_API."/v".API_VERSION."/".MODULE."/marketingchannel/".$marketingchannel->getIdmarketingchannel(),
                ),
            ),
            "idmarketingchannel" => $marketingchannel->getIdmarketingchannel(),
            "marketingchannel_name" => $marketingchannel->getMarketingchannelName()
        );
        return $response;
    }
    /////////// End get ///////////

    /////////// Start getList ///////////
    /**
     * @param $idcompany
     * @param $page
     * @param $limit
     * @param array $filters
     * @param $order
     * @param $dir
     * @return array
     */
    public function getCollection($idcompany, $page, $limit, array $filters=null, $order, $dir){
        $marketingcampaignQuery = new MarketingcampaignQuery();
        //Los Filtros
        if($filters!=null){
            foreach ($filters as $filter){
                $params = $marketingcampaignQuery->getParams();
                if(isset($filter['in'])){

                    if(!empty($params)){
                        foreach($params as $param){
                            if($filter['attribute'] == $param['column']){
                                $flag = true;
                            }else{
                                $flag=false;
                            }
                        }
                        if($flag){
                            $marketingcampaignQuery->addOr('marketingcampaign.'.$filter['attribute'], $filter['in'], \Criteria::IN);
                        }else{
                            $marketingcampaignQuery->addAnd('marketingcampaign.'.$filter['attribute'], $filter['in'], \Criteria::IN);
                        }
                    }else{
                        $marketingcampaignQuery->filterBy(BasePeer::translateFieldname('marketingcampaign', $filter['attribute'], BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), $filter['in'], \Criteria::IN);
                    }
                }

                if(isset($filter['neq'])){
                    if(!empty($params)){
                        foreach($params as $param){
                            if($filter['attribute'] = $param['column']){
                                $marketingcampaignQuery->addOr('marketingcampaign.'.$filter['attribute'], $filter['neq'], \Criteria::NOT_EQUAL);
                            }
                        }
                    }else{
                        $marketingcampaignQuery->filterBy(BasePeer::translateFieldname('marketingcampaign', $filter['attribute'], BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), $filter['neq'], \Criteria::NOT_EQUAL);
                    }
                }
                if(isset($filter['gt'])){
                    $marketingcampaignQuery->filterBy(BasePeer::translateFieldname('marketingcampaign', $filter['attribute'], BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), $filter['gt'], \Criteria::GREATER_THAN);
                }
                if(isset($filter['lt'])){
                    $marketingcampaignQuery ->filterBy(BasePeer::translateFieldname('marketingcampaign', $filter['attribute'], BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), $filter['lt'], \Criteria::LESS_THAN);
                }
                if(isset($filter['from']) && isset($filter['to'])){
                    $marketingcampaignQuery->filterBy(BasePeer::translateFieldname('marketingcampaign', $filter['attribute'], BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), $filter['from'], \Criteria::GREATER_EQUAL)
                        ->add(BasePeer::translateFieldname('marketingcampaign', $filter['attribute'], BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), $filter['to'], \Criteria::LESS_EQUAL);
                }
                if(isset($filter['like'])){
                    $marketingcampaignQuery->filterBy(BasePeer::translateFieldname('marketingcampaign', $filter['attribute'], BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), $filter['like'], \Criteria::LIKE);
                }
            }
        }

        //Order y Dir
        if($order !=null || $dir !=null){
            $marketingcampaignQuery->orderBy($order, $dir);
        }

        // Obtenemos el filtrado por medio del idcompany del recurso.
        $result = $marketingcampaignQuery->useMarketingchannelQuery()->filterByIdCompany($idcompany)->endUse()->paginate($page,$limit);

        $links = array(
            'self' => array('href' => URL_API.'/'.MODULE.'/marketingcampaign?page='.$result->getPage()),
            'prev' => array('href' => URL_API.'/'.MODULE.'/marketingcampaign?page='.$result->getPreviousPage()),
            'next' => array('href' => URL_API.'/'.MODULE.'/marketingcampaign?page='.$result->getNextPage()),
            'first' => array('href' => URL_API.'/'.MODULE.'/marketingcampaign'),
            'last' => array('href' => URL_API.'/'.MODULE.'/marketingcampaign?page='.$result->getLastPage()),
        );

        if($result->getPreviousPage() == 1){
            unset($links['prev']);
        }
        if($result->isLastPage()){
            unset($links['next']);
        }

        $resume = array(
            'currentPage' => $result->getPage(),
            'itemsPerPage' => $result->getMaxPerPage(),
            'totalItems' => $result->count(),
            'lastPage' => $result->getLastPage(),
        );

        $data = $result->getResults()->toArray(null,false,BasePeer::TYPE_FIELDNAME);

        $resultArray = array(
            'links' => $links,
            'resume' => $resume,
            'data' => $data
        );

        //Retornamos nuestro resultado
        return $resultArray;
    }

    /**
     * @param $getCollection
     * @param $userLevel
     * @return array
     */
    public function getCollectionResponse($getCollection, $userLevel){

        // Instanciamos el Formulario GET de nuestro recurso marketingcampaign
        $marketingcampaignFormGET = MarketingcampaignFormGET::init($userLevel);
        $marketingcampaignArray = array();
        foreach ($getCollection['data'] as $item){

            $marketingcampaignQuery = MarketingcampaignQuery::create()->filterByIdmarketingcampaign($item['idmarketingcampaign'])->findOne();

            $row = array(
                "_links" => array(
                    'self' => array('href' => URL_API.'/'.MODULE.'/marketingcampaign/'.$item['idmarketingcampaign']),
                ),
            );

            foreach ($marketingcampaignFormGET->getElements() as $key=>$value){
                $row[$key] = $item[$key];
            }

            $marketingchannelQuery = MarketingchannelQuery::create()->filterByIdmarketingchannel($item['idmarketingchannel'])->findOne();
            $marketingchannel = $marketingchannelQuery->toArray(BasePeer::TYPE_FIELDNAME);

            $row['marketingchannel'] = array(
                '_links' => array(
                    'self' => array('href' => URL_API.'/'.MODULE.'/marketingchannel/'.$marketingchannel['idmarketingchannel']),
                ),
                'idmarketingchannel' => $marketingchannel['idmarketingchannel'],
                'marketingchannel_name' => $marketingchannel['marketingchannel_name'],
            );
            //Eliminamos los campos que hacen referencia a otras tablas
            unset($row['idmarketingchannel']);

            array_push($marketingcampaignArray, $row);
        }

        // Start Marketingchannel //
        // Instanciamos el objeto de MarketingchannelQuery
        $marketingchannelQuery = $marketingcampaignQuery->getMarketingchannel()->toArray(BasePeer::TYPE_FIELDNAME);

        //Instanciamos nuestro formulario marketingchannelGET para obtener los datos que el usuario de acuerdo a su nivel va tener accesso
        $marketingchannelFormGET = MarketingchannelFormGET::init($userLevel);

        $marketingchannelArray = array();
        foreach ($marketingchannelFormGET->getElements() as $key=>$value){
            $marketingchannelArray[$key] = $marketingchannelQuery[$key];
        }

        //Agregamos los datos de user a nuestro arreglo $row['marketingchannel']
        foreach ($marketingchannelArray as $key=>$value){
            $row[$key] = $value;
        }
        // End Marketingchannel //

        // Start ACL //
        //Guardamos en un arreglo las columnas y los atributos a los que el usuario tiene permiso
        $acl = array();
        foreach ($marketingcampaignFormGET->getElements() as $element){
            if($element->getOption('value_options')!=null){
                $acl[$element->getAttribute('name')] = array('viewName' => $element->getOption('label') ,'value_options' => $element->getOption('value_options'));
            }else{
                $acl[$element->getAttribute('name')] = $element->getOption('label');
            }
        }

        //Eliminamos el id marketingchannel Si es visible y lo agregamos como embbeded toda la informacion de company a la que tiene visible el usuario
        if(key_exists('idmarketingchannel',$acl)){
            unset($acl['idmarketingchannel']);
            $marketingchannelColumns = array();
            foreach ($marketingchannelFormGET->getElements() as $element){
                $marketingchannelColumns[$element->getAttribute('name')] =  $element->getOption('label');
            }
            // Mostramos las columnas que son relevantes a la respuesta:
            $marketingchannelColumns = array(
                'idmarketingchannel' => $marketingchannelColumns['idmarketingchannel'],
                'marketingchannel_name' => $marketingchannelColumns['marketingchannel_name'],
            );
            $acl['marketingchannel'] = $marketingchannelColumns;
        }
        // End ACL //

        $response = array(
            '_links' => $getCollection['links'],
            'ACL' => $acl,
            'resume' => $getCollection['resume'],
            'marketingcampaigns' => $marketingcampaignArray,
        );
        switch(TYPE_RESPONSE){
            case "xml" :{
                $response['marketingcampaigns'] = array(
                    'marketingcampaign' => $marketingcampaignArray
                );
                break;
            }
        }

        return $response;
    }
    /////////// End getList ///////////

    /////////// Start update ///////////
    public function updateResource($id, $data, $idCompany, $userLevel, $request, $response){
        $idmarketingchannel = isset($data['idmarketingchannel'])?$data['idmarketingchannel']:null;
        //Instanciamos nuestra marketingcampaignQuery
        $marketingcampaignQuery = MarketingcampaignQuery::create();

        //Verificamos que el Id marketingcampaign que se quiere modificar exista y que pretenece a la compañia
        if($marketingcampaignQuery->create()->filterByIdmarketingcampaign($id)->useMarketingchannelQuery()->filterByIdCompany($idCompany)->endUse()->exists()){

            //Instanciamos nuestra marketingcampaignQuery
            $marketingcampaignPKQuery = $marketingcampaignQuery->findPk($id);
            $marketingcampaignFormToShowUpdate = MarketingcampaignFormToShowUpdate::init($userLevel);

            // Si idmarketingchannel tiene un valor, lo almacenamos, de lo contrario le asignamos el valor que tiene en la base de datos
            $data['idmarketingchannel'] = isset($data['idmarketingchannel'])?$data['idmarketingchannel']:$marketingcampaignPKQuery->getIdmarketingchannel();
            // Si marketingcampaign_name tiene un valor, lo almacenamos, de lo contrario le asignamos el valor que tiene en la base de datos
            $data['marketingcampaign_name'] = isset($data['marketingcampaign_name'])?$data['marketingcampaign_name']:$marketingcampaignPKQuery->getMarketingcampaignName();

            $marketingcampaignDataArray = $marketingcampaignPKQuery->toArray(BasePeer::TYPE_FIELDNAME);

            //Remplzamos los datos de la marketingcampaign por lo que se van a modificar
            foreach ($data as $key => $value){
                $marketingcampaignPKQuery->setByName($key, $value, BasePeer::TYPE_FIELDNAME);
            }

            $marketingcampaignArray = HttpRequest::resourceUpdateData($data, $request, $response, 'Marketingcampaign', $marketingcampaignDataArray);

            unset($marketingcampaignArray['idmarketingcampaign']);
            unset($marketingcampaignArray['idmarketingchannel']);

            // Si desean cambiar el $idmarketingchannel
            if(isset($idmarketingchannel)){
                // Instanciamos nuestro objeto MarketingchannelQuery y validamos si el idmarketingchannel del registro a actualizar sí pertenece a la misma compañia
                $marketingchannelQueryByIdmarketingchannel = MarketingchannelQuery::create()->filterByIdmarketingchannel($idmarketingchannel)->filterByIdcompany($idCompany)->findOne();
                // Si $marketingchannelQueryByIdmarketingchannel tiene un valor, significa que si es de la misma compañia el usuario al que se desea actualizar
                // Si $marketingchannelQueryByIdmarketingchannel es null, entonces no pertenece a la misma compañia
                if($marketingchannelQueryByIdmarketingchannel != null){
                    $marketingchannelByIdmarketingchannel = $marketingchannelQueryByIdmarketingchannel->toArray(BasePeer::TYPE_FIELDNAME);
                    // Asignamos a nuestro arreglo el valor del idmarketingchannel
                    $marketingcampaignArray['idmarketingchannel'] = $marketingchannelByIdmarketingchannel['idmarketingchannel'];
                    // Preparamos el valor del idmarketingchannel para actualizar el registro en la base de datos
                    $marketingcampaignPKQuery->setByName('idmarketingchannel', $marketingchannelByIdmarketingchannel['idmarketingchannel'], BasePeer::TYPE_FIELDNAME);

                }else{
                    $bodyResponse = 'Invalid idmarketingchannel';
                    return array('status_code' => 409, 'details' => $bodyResponse);
                }
            }

            // Instanciamos nuestro formulario resourceFormPostPut
            $marketingcampaignFormPostPut = MarketingcampaignFormPostPut::init($userLevel);

            //Le ponemos los datos a nuestro formulario
            $marketingcampaignFormPostPut->setData($marketingcampaignArray);

            // Instanciamos nuestro filtro resourceFilterPostPut
            $marketingcampaignFilterPostPut = new MarketingcampaignFilterPostPut();

            //Le ponemos el filtro a nuestro formulario
            $marketingcampaignFormPostPut->setInputFilter($marketingcampaignFilterPostPut->getInputFilter($userLevel));
            //Si los valores son validos
            if($marketingcampaignFormPostPut->isValid()){

                //Si hay valores por modificar
                if($marketingcampaignPKQuery->isModified()){
                    if($data['marketingcampaign_name'] == $marketingcampaignDataArray['marketingcampaign_name']){

                        $marketingcampaignPKQuery->save();

                        //Le damos formato a nuestra respuesta
                        $bodyResponse = array(
                            "_links" => array(
                                'self' => URL_API.'/'.MODULE.'/marketingcampaign/'.$marketingcampaignPKQuery->getIdmarketingcampaign(),
                            ),
                        );

                        foreach ($marketingcampaignPKQuery->toArray(BasePeer::TYPE_FIELDNAME) as $key => $value){
                            $bodyResponse[$key] = $value;
                        }

                        //Eliminamos los campos que hacen referencia a otras tablas
                        unset($bodyResponse['idmarketingchannel']);

                        //Agregamos el campo embedded a nuestro arreglo
                        $objectMarketingchannel = $marketingcampaignPKQuery->getMarketingchannel()->toArray(BasePeer::TYPE_FIELDNAME);

                        //Instanciamos nuestro formulario marketingchannelGET para obtener los datos que el usuario de acuerdo a su nivel va tener accesso
                        $marketingchannelForm = MarketingchannelFormGET::init($userLevel);

                        $marketingchannelArray = array();
                        foreach ($marketingchannelForm->getElements() as $key=>$value){
                            $marketingchannelArray[$key] = $objectMarketingchannel[$key];
                        }
                        $bodyResponse['marketingchannel'] = array(
                            '_links' => array(
                                'self' => array('href' => URL_API.'/'.MODULE.'/marketingchannel/'.$marketingcampaignPKQuery->getIdmarketingchannel()),
                            ),
                        );

                        //Agregamos los datos de marketingchannel a nuestro arreglo $row['_embedded']['marketingchannel']
                        foreach ($marketingchannelArray as $key=>$value){
                            $bodyResponse['marketingchannel'][$key] = $value;
                        }

                        $bodyResponse['marketingchannel'] = array(
                            'idmarketingchannel' => $bodyResponse['marketingchannel']['idmarketingchannel'],
                            'marketingchannel_name' => $bodyResponse['marketingchannel']['marketingchannel_name'],
                        );

                        return array('status_code' => 200, 'details' => $bodyResponse);

                    }else{

                        //Verificamos que marketingcampaign_name no exista ya en nuestra base de datos.
                        if($marketingcampaignQuery->filterByMarketingcampaignName($data['marketingcampaign_name'])->useMarketingchannelQuery()->filterByIdCompany($idCompany)->endUse()->find()->count()==0){

                            $marketingcampaignPKQuery->save();

                            //Le damos formato a nuestra respuesta
                            $bodyResponse = array(
                                "_links" => array(
                                    'self' => URL_API.'/'.MODULE.'/marketingcampaign/'.$marketingcampaignPKQuery->getIdmarketingcampaign(),
                                ),
                            );

                            foreach ($marketingcampaignPKQuery->toArray(BasePeer::TYPE_FIELDNAME) as $key => $value){
                                $bodyResponse[$key] = $value;
                            }

                            //Eliminamos los campos que hacen referencia a otras tablas
                            unset($bodyResponse['idmarketingchannel']);

                            //Agregamos el campo embedded a nuestro arreglo
                            $objectMarketingchannel = $marketingcampaignPKQuery->getMarketingchannel()->toArray(BasePeer::TYPE_FIELDNAME);

                            //Instanciamos nuestro formulario companyGET para obtener los datos que el usuario de acuerdo a su nivel va tener accesso
                            $marketingchannelForm = MarketingchannelFormGET::init($userLevel);

                            $marketingchannelArray = array();
                            foreach ($marketingchannelForm->getElements() as $key=>$value){
                                $marketingchannelArray[$key] = $objectMarketingchannel[$key];
                            }
                            $bodyResponse['marketingchannel'] = array(
                                '_links' => array(
                                    'self' => array('href' => URL_API.'/'.MODULE.'/marketingchannel/'.$marketingcampaignPKQuery->getIdMarketingchannel()),
                                ),
                            );

                            //Agregamos los datos de marketingchannel a nuestro arreglo $row['_embedded']['marketingchannel']
                            foreach ($marketingchannelArray as $key=>$value){
                                $bodyResponse['marketingchannel'][$key] = $value;
                            }

                            $bodyResponse['marketingchannel'] = array(
                                'idmarketingchannel' => $bodyResponse['marketingchannel']['idmarketingchannel'],
                                'marketingchannel_name' => $bodyResponse['marketingchannel']['marketingchannel_name'],
                            );

                            return array('status_code' => 200, 'details' => $bodyResponse);

                        }else{
                            $bodyResponse = "marketingcampaign_name ". "'".$marketingcampaignArray['marketingcampaign_name']."'". " already exists";
                            return array('status_code' => 409, 'details' => $bodyResponse);
                        }
                    }
                }else{
                    $messageArray = array();
                    foreach ($marketingcampaignFormToShowUpdate->getElements() as $key => $value){
                        //Obtenemos el nombre de la columna
                        $message = $key;
                        array_push($messageArray, $message);
                    }
                    $bodyResponse = "No changes were found";
                    return array('status_code' => 304, 'details' => $bodyResponse, 'columns_to_do_changes' => $messageArray);
                }
            }else{
                //Identificamos cual fue la columna que dio problemas y la enviamos como mensaje
                $messageArray = array();
                foreach ($marketingcampaignFormPostPut->getMessages() as $key => $value){
                    foreach($value as $val){
                        //Obtenemos el valor de la columna con error
                        $message = $key.' '.$val;
                        array_push($messageArray, $message);
                    }
                }
                return array('status_code' => 409, 'details' => $messageArray);
            }
        }else{

            $bodyResponse = 'Invalid idmarketingcampaign';
            return array('status_code' => 409, 'details' => $bodyResponse);
        }
    }
    /////////// End update ///////////

    /////////// Start delete ///////////
    /**
     * @param $id
     * @param $userLevel
     * @return bool
     */
    public function deleteEntity($id,$userLevel) {

        //Reglas de negocio
        if($userLevel>=4){
            MarketingcampaignQuery::create()->filterByIdmarketingcampaign($id)->delete();
            return true;
        }
        return false;

    }
    /////////// End delete ///////////
}


text:
ExplodingSprite::ExplodingSprite(Twowayms* s) :
  Twowayms(*s),
  chunks(),
  freeList(),
name(s->getName()){
  makeChunks(
    Gamedata::getInstance().getXmlInt(s->getName()+"/chunk/size")
  );
}
ExplodingSprite::~ExplodingSprite() {
  chunks.clear();     // clearing a vector is a waste of time, but ...
  freeList.clear();   // still ...
}

void ExplodingSprite::draw() const {
  // Override draw; use the draw in Chunk, which derives from Sprite.
  // So the draw we're using is actually in Sprite

  std::list<Chunk>::const_iterator ptr = chunks.begin();
  while (ptr != chunks.end()) {
    ptr->draw();
    ++ptr;
  }
}

void ExplodingSprite::update(Uint32 ticks) {
  std::list<Chunk>::iterator ptr = chunks.begin();
  while (ptr != chunks.end()) {
    ptr->update(ticks);
    if (ptr->goneTooFar()) {  // Check to see if we should free a chunk
      freeList.push_back(*ptr);
      ptr = chunks.erase(ptr);
    }
    else ++ptr;
  }
}

void ExplodingSprite::makeChunks(unsigned int n) {

  // Break the SDL_Surface into n*n squares; where each square
  // has width and height of frameWidth/n and frameHeight/n
  unsigned int chunk_width = std::max(1u, getFrame()->getWidth()/n);
  unsigned int chunk_height = std::max(1u, getFrame()->getHeight()/n);
  int speedx = static_cast<int>(velocityX()); // Wanna test for zero...
  int speedy = static_cast<int>(velocityY()); // Make sure it's an int.
  if (speedx == 0) speedx = 1; // Make sure it's not 0;
  if (speedy == 0) speedy = 1; // Make sure it's not 0;

  // Get the SDL_Surface so we can chunk it:
 // SDL_Surface* spriteSurface(getFrame()->getSurface());
  Sint16 source_y = getFrame()->getSourceY();
  while  (source_y < getFrame()->getHeight() ) {
    Sint16 source_x = getFrame()->getSourceX();
    while ( source_x < getFrame()->getWidth() ) {
      // Give each chunk it's own speed/direction:
      float sx = (rand() % speedx + 40) * (rand()%2?-1:1); // 'cause %0 is
      float sy = (rand() % speedy + 40) * (rand()%2?-1:1); // float except
      Frame* frame =
            FrameFactory::getInstance().getChunkFrame(getName(), chunk_width, chunk_height, source_x, source_y);
      Chunk chunk(
                Vector2f(X()+source_x,   // x coord of destination
                         Y()+source_y), // y coord of destination
                Vector2f(sx, sy),
                getName()+"/chunk",
                frame);
      // chunks uses value semantics, as does frames, but there's
      // a big difference:
      chunks.push_back(chunk);
      source_x += chunk_width;
    }
    source_y += chunk_height;
  }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * Open Source Software published under the Apache Licence, Version 2.0.
 */

package io.github.vocabhunter.gui.common;

import io.github.vocabhunter.test.utils.AbstractBeanTest;

public class PlacementTest extends AbstractBeanTest<Placement> {
    @Override
    protected Placement buildPrimary() {
        return new Placement(1, 2, 3,4);
    }

    @Override
    protected Placement buildSecondary() {
        return new Placement(1, 2);
    }
}


text:
% Copyright 2011 Zdenek Kalal
%
% This file is part of TLD.
%
% TLD is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% TLD is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with TLD.  If not, see <http://www.gnu.org/licenses/>.

function bbScale = bb_scale(bb)
% Returns bbox scale = sqrt(bbox area)

bbScale = sqrt((bb(4,:)-bb(2,:)+1).*(bb(3,:)-bb(1,:)+1));


text:
using UnityEngine;
using System.Collections;

public class BirdDeletor : MonoBehaviour {

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}

	void OnTriggerEnter2D(Collider2D collider){
		if(collider.tag == "Bird"){
			Destroy(collider.gameObject);
		}
	}
}


text:
<?php

namespace Sylius\Component\Promotion\Checker\Rule;

use Sylius\Bundle\PromotionBundle\Form\Type\Rule\ItemTotalConfigurationType;
use Sylius\Component\Promotion\Model\PromotionSubjectInterface;

/**
 * @author Saša Stamenković <umpirsky@gmail.com>
 */
final class ItemTotalRuleChecker implements RuleCheckerInterface
{
    const TYPE = 'item_total';

    /**
     * {@inheritdoc}
     */
    public function isEligible(PromotionSubjectInterface $subject, array $configuration)
    {
        return $subject->getPromotionSubjectTotal() >= $configuration['amount'];
    }

    /**
     * {@inheritdoc}
     */
    public function getConfigurationFormType()
    {
        return ItemTotalConfigurationType::class;
    }
}


text:
<?php

namespace Google\Service\Dialogflow;

class GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedReply extends \Google\Model
{
  /**
   * @var string
   */
  public $postbackData;
  /**
   * @var string
   */
  public $text;

  /**
   * @param string
   */
  public function setPostbackData($postbackData)
  {
    $this->postbackData = $postbackData;
  }
  /**
   * @return string
   */
  public function getPostbackData()
  {
    return $this->postbackData;
  }
  /**
   * @param string
   */
  public function setText($text)
  {
    $this->text = $text;
  }
  /**
   * @return string
   */
  public function getText()
  {
    return $this->text;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedReply::class, 'Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestedReply');


text:
<?php

abstract class PhabricatorMail {

  private $actor;

  public function setActor(PhabricatorUser $actor) {
    $this->actor = $actor;
    return $this;
  }

  public function getActor() {
    return $this->actor;
  }

}


text:
package mains;

import tasks.graph.GraphInitTask;
import tasks.graph.GraphIterationsTask;

public class DefaultGraph {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		/*Init*/
		GraphInitTask init = new GraphInitTask(true, true, true,1,1000, 0.9, 50, 3,25,3);

		init.run();

		/*Iteration Task*/
		GraphIterationsTask t = new GraphIterationsTask(6,25,3);
		t.run();

	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/negro" />
    <item android:drawable="@color/blanco" />
</selector>


text:
package reactivemongo.bson

import scala.collection.generic.CanBuildFrom
import scala.util.{ Failure, Success, Try }

sealed trait UnsafeBSONReader[T] {
  def readTry(value: BSONValue): Try[T]
}

/**
 * A reader that produces an instance of `T` from a subtype of [[BSONValue]].
 */
trait BSONReader[B <: BSONValue, T] { self =>

  /**
   * Reads a BSON value and produce an instance of `T`.
   *
   * This method may throw exceptions at runtime.
   * If used outside a reader, one should consider `readTry(bson: B): Try[T]` or `readOpt(bson: B): Option[T]`.
   */
  def read(bson: B): T

  /** Tries to produce an instance of `T` from the `bson` value, returns `None` if an error occurred. */
  def readOpt(bson: B): Option[T] = readTry(bson).toOption

  /** Tries to produce an instance of `T` from the `bson` value. */
  def readTry(bson: B): Try[T] = Try(read(bson))

  /**
   * Returns a BSON reader that returns the result of applying `f`
   * on the result of this reader.
   *
   * @param f the function to apply
   */
  final def afterRead[U](f: T => U): BSONReader[B, U] =
    BSONReader[B, U]((read _) andThen f)

  private[reactivemongo] def widenReader[U >: T]: UnsafeBSONReader[U] =
    new UnsafeBSONReader[U] {
      def readTry(value: BSONValue): Try[U] =
        Try(value.asInstanceOf[B]) match {
          case Failure(_) => Failure(exceptions.TypeDoesNotMatch(
            s"Cannot convert $value: ${value.getClass} with ${self.getClass}"
          ))

          case Success(bson) => self.readTry(bson)
        }
    }
}

object BSONReader {
  private class Default[B <: BSONValue, T](
      _read: B => T
  ) extends BSONReader[B, T] {
    def read(bson: B): T = _read(bson)
  }

  def apply[B <: BSONValue, T](read: B => T): BSONReader[B, T] =
    new Default[B, T](read)
}

/**
 * A writer that produces a subtype of [[BSONValue]] fron an instance of `T`.
 */
trait BSONWriter[T, B <: BSONValue] {
  /**
   * Writes an instance of `T` as a BSON value.
   *
   * This method may throw exceptions at runtime.
   * If used outside a reader, one should consider `writeTry(bson: B): Try[T]` or `writeOpt(bson: B): Option[T]`.
   */
  def write(t: T): B

  /** Tries to produce a BSON value from an instance of `T`, returns `None` if an error occurred. */
  def writeOpt(t: T): Option[B] = writeTry(t).toOption

  /** Tries to produce a BSON value from an instance of `T`. */
  def writeTry(t: T): Try[B] = Try(write(t))

  /**
   * Returns a BSON writer that returns the result of applying `f`
   * on the BSON value from this writer.
   *
   * @param f the function to apply
   */
  final def afterWrite[U <: BSONValue](f: B => U): BSONWriter[T, U] =
    BSONWriter[T, U]((write _) andThen f)

  final def beforeWrite[U](f: U => T): BSONWriter[U, B] =
    BSONWriter[U, B](f andThen (write _))
}

object BSONWriter {
  private class Default[T, B <: BSONValue](
      _write: T => B
  ) extends BSONWriter[T, B] {
    def write(value: T): B = _write(value)
  }

  def apply[T, B <: BSONValue](write: T => B): BSONWriter[T, B] =
    new Default[T, B](write)
}

/**
 * A reader that produces an instance of `T` from a subtype of [[BSONValue]].
 */
trait VariantBSONReader[-B <: BSONValue, +T] {
  /**
   * Reads a BSON value and produce an instance of `T`.
   *
   * This method may throw exceptions at runtime.
   * If used outside a reader, one should consider `readTry(bson: B): Try[T]` or `readOpt(bson: B): Option[T]`.
   */
  def read(bson: B): T

  /** Tries to produce an instance of `T` from the `bson` value, returns `None` if an error occurred. */
  def readOpt(bson: B): Option[T] = readTry(bson).toOption

  /** Tries to produce an instance of `T` from the `bson` value. */
  def readTry(bson: B): Try[T] = Try(read(bson))
}

/**
 * A writer that produces a subtype of [[BSONValue]] fron an instance of `T`.
 */
trait VariantBSONWriter[-T, +B <: BSONValue] {
  /**
   * Writes an instance of `T` as a BSON value.
   *
   * This method may throw exceptions at runtime.
   * If used outside a reader, one should consider `writeTry(bson: B): Try[T]` or `writeOpt(bson: B): Option[T]`.
   */
  def write(t: T): B

  /** Tries to produce a BSON value from an instance of `T`, returns `None` if an error occurred. */
  def writeOpt(t: T): Option[B] = writeTry(t).toOption

  /** Tries to produce a BSON value from an instance of `T`. */
  def writeTry(t: T): Try[B] = Try(write(t))
}

trait BSONDocumentReader[T] extends BSONReader[BSONDocument, T]

object BSONDocumentReader {
  private class Default[T](
      _read: BSONDocument => T
  ) extends BSONDocumentReader[T] {

    def read(value: BSONDocument): T = _read(value)
  }

  def apply[T](read: BSONDocument => T): BSONDocumentReader[T] =
    new Default[T](read)
}

trait BSONDocumentWriter[T] extends BSONWriter[T, BSONDocument]

object BSONDocumentWriter {
  private class Default[T](
      _write: T => BSONDocument
  ) extends BSONDocumentWriter[T] {

    def write(value: T): BSONDocument = _write(value)
  }

  def apply[T](write: T => BSONDocument): BSONDocumentWriter[T] =
    new Default[T](write)
}

trait VariantBSONDocumentReader[+T] extends VariantBSONReader[BSONDocument, T]
trait VariantBSONDocumentWriter[-T] extends VariantBSONWriter[T, BSONDocument]

class VariantBSONWriterWrapper[T, B <: BSONValue](writer: VariantBSONWriter[T, B]) extends BSONWriter[T, B] {
  def write(t: T) = writer.write(t)
}

class VariantBSONReaderWrapper[B <: BSONValue, T](reader: VariantBSONReader[B, T]) extends BSONReader[B, T] {
  def read(b: B) = reader.read(b)
}

trait BSONHandler[B <: BSONValue, T] extends BSONReader[B, T] with BSONWriter[T, B] {
  def as[R](to: T => R, from: R => T): BSONHandler[B, R] =
    new BSONHandler.MappedHandler(this, to, from)
}

object BSONHandler {
  private[bson] class MappedHandler[B <: BSONValue, T, U](
      parent: BSONHandler[B, T],
      to: T => U,
      from: U => T
  ) extends BSONHandler[B, U] {
    def write(u: U) = parent.write(from(u))
    def read(b: B) = to(parent.read(b))
  }

  private[bson] class DefaultHandler[B <: BSONValue, T](r: B => T, w: T => B)
      extends BSONHandler[B, T] {
    def read(x: B): T = r(x)
    def write(x: T): B = w(x)
  }

  /**
   * Handler factory.
   *
   * {{{
   * import reactivemongo.bson.{ BSONHandler, BSONString }
   *
   * case class Foo(value: String)
   *
   * val foo: BSONHandler[BSONString, Foo] = BSONHandler(
   *   { read: BSONString => Foo(read.value) },
   *   { write: Foo => BSONString(write.value)
   * )
   * }}}
   */
  def apply[B <: BSONValue, T](read: B => T, write: T => B): BSONHandler[B, T] =
    new DefaultHandler(read, write)

  /**
   * Returns a BSON handler for a type `T`, provided there are
   * a writer and a reader for it, both using the same kind of `BSONValue`.
   */
  implicit def provided[B <: BSONValue, T](implicit writer: BSONWriter[T, B], reader: BSONReader[B, T]): BSONHandler[B, T] = BSONHandler(reader.read _, writer.write _)
}

trait DefaultBSONHandlers {
  import scala.language.higherKinds

  implicit object BSONIntegerHandler extends BSONHandler[BSONInteger, Int] {
    def read(int: BSONInteger) = int.value
    def write(int: Int) = BSONInteger(int)
  }
  implicit object BSONLongHandler extends BSONHandler[BSONLong, Long] {
    def read(long: BSONLong) = long.value
    def write(long: Long) = BSONLong(long)
  }

  implicit object BSONDoubleHandler extends BSONHandler[BSONDouble, Double] {
    def read(double: BSONDouble) = double.value
    def write(double: Double) = BSONDouble(double)
  }

  implicit object BSONStringHandler extends BSONHandler[BSONString, String] {
    def read(string: BSONString) = string.value
    def write(string: String) = BSONString(string)
  }
  implicit object BSONBooleanHandler extends BSONHandler[BSONBoolean, Boolean] {
    def read(boolean: BSONBoolean) = boolean.value
    def write(boolean: Boolean) = BSONBoolean(boolean)
  }

  implicit object BSONBinaryHandler extends BSONHandler[BSONBinary, Array[Byte]] {
    def read(bin: BSONBinary) = bin.value.duplicate().readArray(bin.value.size)
    def write(xs: Array[Byte]) = BSONBinary(xs, Subtype.GenericBinarySubtype)
  }

  import java.util.Date

  implicit object BSONDateTimeHandler extends BSONHandler[BSONDateTime, Date] {
    def read(bson: BSONDateTime) = new Date(bson.value)
    def write(date: Date) = BSONDateTime(date.getTime)
  }

  // Typeclasses Handlers
  import BSONNumberLike._
  import BSONBooleanLike._

  class BSONNumberLikeReader[B <: BSONValue] extends BSONReader[B, BSONNumberLike] {
    def read(bson: B) = bson match {
      case int: BSONInteger   => BSONIntegerNumberLike(int)
      case long: BSONLong     => BSONLongNumberLike(long)
      case double: BSONDouble => BSONDoubleNumberLike(double)
      case dt: BSONDateTime   => BSONDateTimeNumberLike(dt)
      case ts: BSONTimestamp  => BSONTimestampNumberLike(ts)
      case _                  => throw new UnsupportedOperationException()
    }
  }

  implicit object BSONNumberLikeWriter extends VariantBSONWriter[BSONNumberLike, BSONValue] {
    def write(number: BSONNumberLike) = number.underlying
  }

  implicit def bsonNumberLikeReader[B <: BSONValue] = new BSONNumberLikeReader[B]

  class BSONBooleanLikeReader[B <: BSONValue] extends BSONReader[B, BSONBooleanLike] {
    def read(bson: B) = bson match {
      case int: BSONInteger        => BSONIntegerBooleanLike(int)
      case double: BSONDouble      => BSONDoubleBooleanLike(double)
      case long: BSONLong          => BSONLongBooleanLike(long)
      case boolean: BSONBoolean    => BSONBooleanBooleanLike(boolean)
      case nll: BSONNull.type      => BSONNullBooleanLike(BSONNull)
      case udf: BSONUndefined.type => BSONUndefinedBooleanLike(BSONUndefined)
      case _                       => throw new UnsupportedOperationException()
    }
  }

  implicit object BSONBooleanLikeWriter extends VariantBSONWriter[BSONBooleanLike, BSONValue] {
    def write(number: BSONBooleanLike) = number.underlying
  }

  implicit def bsonBooleanLikeReader[B <: BSONValue] = new BSONBooleanLikeReader[B]

  // Collections Handlers
  class BSONArrayCollectionReader[M[_], T](implicit cbf: CanBuildFrom[M[_], T, M[T]], reader: BSONReader[_ <: BSONValue, T]) extends BSONReader[BSONArray, M[T]] {
    def read(array: BSONArray) =
      array.stream.filter(_.isSuccess).map { v =>
        reader.asInstanceOf[BSONReader[BSONValue, T]].read(v.get)
      }.to[M]
  }

  class BSONArrayCollectionWriter[T, Repr <% Traversable[T]](implicit writer: BSONWriter[T, _ <: BSONValue]) extends VariantBSONWriter[Repr, BSONArray] {
    def write(repr: Repr) = {
      new BSONArray(repr.map(s => Try(writer.write(s))).to[Stream])
    }
  }

  implicit def collectionToBSONArrayCollectionWriter[T, Repr <% Traversable[T]](implicit writer: BSONWriter[T, _ <: BSONValue]): VariantBSONWriter[Repr, BSONArray] = new BSONArrayCollectionWriter[T, Repr]

  implicit def bsonArrayToCollectionReader[M[_], T](implicit cbf: CanBuildFrom[M[_], T, M[T]], reader: BSONReader[_ <: BSONValue, T]): BSONReader[BSONArray, M[T]] = new BSONArrayCollectionReader

  abstract class IdentityBSONConverter[T <: BSONValue](implicit m: Manifest[T]) extends BSONReader[T, T] with BSONWriter[T, T] {
    override def write(t: T): T = m.runtimeClass.cast(t).asInstanceOf[T]
    override def writeOpt(t: T): Option[T] = if (m.runtimeClass.isInstance(t)) Some(t.asInstanceOf[T]) else None
    override def read(bson: T): T = m.runtimeClass.cast(bson).asInstanceOf[T]
    override def readOpt(bson: T): Option[T] = if (m.runtimeClass.isInstance(bson)) Some(bson.asInstanceOf[T]) else None
  }

  implicit object BSONStringIdentity extends IdentityBSONConverter[BSONString]

  implicit object BSONIntegerIdentity extends IdentityBSONConverter[BSONInteger]

  implicit object BSONArrayIdentity extends IdentityBSONConverter[BSONArray]

  implicit object BSONDocumentIdentity extends IdentityBSONConverter[BSONDocument] with BSONDocumentReader[BSONDocument] with BSONDocumentWriter[BSONDocument]

  implicit object BSONBooleanIdentity extends IdentityBSONConverter[BSONBoolean]

  implicit object BSONLongIdentity extends IdentityBSONConverter[BSONLong]

  implicit object BSONDoubleIdentity extends IdentityBSONConverter[BSONDouble]

  implicit object BSONValueIdentity extends IdentityBSONConverter[BSONValue]

  implicit object BSONObjectIDIdentity extends IdentityBSONConverter[BSONObjectID]

  implicit object BSONBinaryIdentity extends IdentityBSONConverter[BSONBinary]

  implicit object BSONDateTimeIdentity extends IdentityBSONConverter[BSONDateTime]

  implicit object BSONNullIdentity extends IdentityBSONConverter[BSONNull.type]

  implicit object BSONUndefinedIdentity extends IdentityBSONConverter[BSONUndefined.type]

  implicit object BSONRegexIdentity extends IdentityBSONConverter[BSONRegex]

  implicit object BSONJavaScriptIdentity extends BSONReader[BSONJavaScript, BSONJavaScript] with BSONWriter[BSONJavaScript, BSONJavaScript] {
    def read(b: BSONJavaScript) = b
    def write(b: BSONJavaScript) = b
  }

  implicit def findWriter[T](implicit writer: VariantBSONWriter[T, _ <: BSONValue]): BSONWriter[T, _ <: BSONValue] =
    new VariantBSONWriterWrapper(writer)

  implicit def findReader[T](implicit reader: VariantBSONReader[_ <: BSONValue, T]): BSONReader[_ <: BSONValue, T] =
    new VariantBSONReaderWrapper(reader)

  implicit def MapReader[K, V](implicit keyReader: BSONReader[BSONString, K], valueReader: BSONReader[_ <: BSONValue, V]): BSONDocumentReader[Map[K, V]] =
    new BSONDocumentReader[Map[K, V]] {
      def read(bson: BSONDocument): Map[K, V] = {
        val elements = bson.elements.map { element =>
          keyReader.read(BSONString(element.name)) -> element.value.seeAsTry[V].get
        }
        elements.toMap
      }
    }

  implicit def MapWriter[K, V](implicit keyWriter: BSONWriter[K, BSONString], valueWriter: BSONWriter[V, _ <: BSONValue]): BSONDocumentWriter[Map[K, V]] =
    new BSONDocumentWriter[Map[K, V]] {
      def write(inputMap: Map[K, V]): BSONDocument = {
        val elements = inputMap.map { tuple =>
          BSONElement(keyWriter.write(tuple._1).value, valueWriter.write(tuple._2))
        }
        BSONDocument(elements)
      }
    }
}

object DefaultBSONHandlers extends DefaultBSONHandlers


text:
https://doc.rust-lang.org/1.1.0/arena/

##Aligned Allocations


text:
import { Component, Injector, Input, OnDestroy } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { TranslateService } from '@ngx-translate/core';
import { Observable } from 'rxjs/Observable';
import { InfoBoxType } from './../../../controls/info-box/info-box.component';
import { ArmSiteDescriptor } from './../../../shared/resourceDescriptors';
import { FeatureComponent } from './../../../shared/components/feature-component';
import { FunctionAppContext } from './../../../shared/function-app-context';
import { HttpResult } from './../../../shared/models/http-result';
import {
  Constants,
  FunctionAppVersion,
  LogCategories,
  ScenarioIds,
  SiteTabIds,
  SlotOperationState,
} from './../../../shared/models/constants';
import { DropDownElement } from './../../../shared/models/drop-down-element';
import { errorIds } from './../../../shared/models/error-ids';
import { BroadcastMessageId } from './../../../shared/models/portal';
import { PortalResources } from './../../../shared/models/portal-resources';
import { SlotNewInfo } from './../../../shared/models/slot-events';
import { ArmObj, ResourceId } from './../../../shared/models/arm/arm-obj';
import { Site } from './../../../shared/models/arm/site';
import { ApplicationSettings } from './../../../shared/models/arm/application-settings';
import { AiService } from '../../../shared/services/ai.service';
import { AuthzService } from './../../../shared/services/authz.service';
import { LogService } from './../../../shared/services/log.service';
import { PortalService } from '../../../shared/services/portal.service';
import { SiteService } from './../../../shared/services/site.service';
import { FunctionAppService } from './../../../shared/services/function-app.service';
import { ScenarioService } from './../../../shared/services/scenario/scenario.service';
import { RequiredValidator } from './../../../shared/validators/requiredValidator';
import { SlotNameValidator } from './../../../shared/validators/slotNameValidator';
import { ArmUtil } from './../../../shared/Utilities/arm-utils';
import { CloneSrcValidator } from './cloneSrcValidator';

@Component({
  selector: 'add-slot',
  templateUrl: './add-slot.component.html',
  styleUrls: ['./../common.scss', './add-slot.component.scss'],
})
export class AddSlotComponent extends FeatureComponent<ResourceId> implements OnDestroy {
  @Input()
  set resourceIdInput(resourceId: ResourceId) {
    this.setInput(resourceId);
  }
  @Input()
  showHeader = false;

  public unsavedChangesWarning: string;
  public operationInProgressWarning: string;

  public addForm: FormGroup;
  public hasCreateAccess = false;
  public slotsQuotaMessage: string;
  public isLoading = true;
  public loadingFailed = false;
  public loadingSiteFailureMessage = '';
  public loadingSlotsFailureMessage = '';
  public loadingAppSettingsFailureMessage = '';
  public slotPrefix = '';
  public slotSuffix = '';
  public cloneSrcIdDropDownOptions: DropDownElement<string>[];
  public isCreating = false;
  public executeButtonDisabled = false;
  public slotOptInNeeded = false;
  public slotOptInEnabled = false;
  public isFunctionApp = false;

  public progressMessage: string;
  public progressMessageClass: InfoBoxType = 'info';

  private _siteId: string;
  private _slotsArm: ArmObj<Site>[];
  private _functionAppContext: FunctionAppContext;

  constructor(
    private _fb: FormBuilder,
    private _siteService: SiteService,
    private _translateService: TranslateService,
    private _aiService: AiService,
    private _logService: LogService,
    private _portalService: PortalService,
    private _authZService: AuthzService,
    private _scenarioService: ScenarioService,
    private _functionAppService: FunctionAppService,
    private _injector: Injector
  ) {
    super('AddSlotComponent', _injector, SiteTabIds.deploymentSlotsCreate);

    this.featureName = 'addslot';
    this.isParentComponent = true;

    this.unsavedChangesWarning = this._translateService.instant(PortalResources.unsavedChangesWarning);
    this.operationInProgressWarning = this._translateService.instant(PortalResources.slotCreateOperationInProgressWarning);

    const nameCtrl = this._fb.control({ value: null, disabled: true });
    const cloneSrcIdCtrl = this._fb.control({ value: null, disabled: true });
    const cloneSrcConfigCtrl = this._fb.control({ value: null, disabled: true });

    this.addForm = this._fb.group({
      name: nameCtrl,
      cloneSrcId: cloneSrcIdCtrl,
      cloneSrcConfig: cloneSrcConfigCtrl,
    });
  }

  protected setup(inputEvents: Observable<ResourceId>) {
    return inputEvents
      .distinctUntilChanged()
      .switchMap(resourceId => {
        this.hasCreateAccess = false;
        this.slotsQuotaMessage = null;
        this.isLoading = true;
        this.loadingFailed = false;
        this.loadingSiteFailureMessage = '';
        this.loadingSlotsFailureMessage = '';
        this.loadingAppSettingsFailureMessage = '';

        this.cloneSrcIdDropDownOptions = null;

        this.isCreating = false;
        this.executeButtonDisabled = false;

        this.slotOptInNeeded = false;
        this.slotOptInEnabled = false;
        this.isFunctionApp = false;

        this.progressMessage = null;
        this.progressMessageClass = 'info';

        this._slotsArm = null;

        const siteDescriptor = new ArmSiteDescriptor(resourceId);
        this._siteId = siteDescriptor.getSiteOnlyResourceId();
        this._functionAppContext = null;

        return Observable.zip(
          this._siteService.getSite(this._siteId),
          this._siteService.getSlots(this._siteId),
          this._siteService.getAppSettings(this._siteId),
          this._authZService.hasPermission(this._siteId, [AuthzService.writeScope]),
          this._authZService.hasReadOnlyLock(this._siteId)
        );
      })
      .mergeMap(r => {
        const [siteResult, slotsResult, appSettingsResult, hasWritePermission, hasReadOnlyLock] = r;

        this.hasCreateAccess = hasWritePermission && !hasReadOnlyLock;

        if (!siteResult.isSuccessful) {
          this._logService.error(LogCategories.addSlot, '/add-slot', siteResult.error.result);
          this.loadingFailed = true;
          this.loadingSiteFailureMessage = this._translateService.instant(PortalResources.error_unableToLoadSite, {
            errorMessage: (siteResult.error && siteResult.error.message) || '',
          });
        } else {
          this.isFunctionApp = ArmUtil.isFunctionApp(siteResult.result);
        }

        if (!slotsResult.isSuccessful) {
          this._logService.error(LogCategories.addSlot, '/add-slot', slotsResult.error.result);
          this.loadingFailed = true;
          this.loadingSlotsFailureMessage = this._translateService.instant(PortalResources.error_unableToLoadSlotsList, {
            errorMessage: (slotsResult.error && slotsResult.error.message) || '',
          });
        }

        if (!this.loadingFailed) {
          this._slotsArm = slotsResult.result.value;
          this._slotsArm.unshift(siteResult.result);

          if (this.isFunctionApp) {
            this._setFunctionAppContext(siteResult, appSettingsResult);

            // This is a function app, so we need to check if it needs to be opted in to using slots.
            if (this._slotsArm.length > 1) {
              // The app already has slots, so it must have already been opted in.
              this.slotOptInNeeded = false;
            } else if (appSettingsResult.isSuccessful) {
              // The app doesn't have slots, so we check the app settings to see if it already opted in.
              this.slotOptInNeeded = !this._functionAppService.isSlotsSupported(appSettingsResult.result);
            } else {
              // The app doesn't have slots, and the app settings failed to load so we can't check.
              this.slotOptInNeeded = false;
              this.loadingFailed = true;
              this.loadingAppSettingsFailureMessage = this._translateService.instant(PortalResources.error_unableToLoadConfig, {
                errorMessage: (appSettingsResult.error && appSettingsResult.error.message) || '',
              });
            }
            this.executeButtonDisabled = this.slotOptInNeeded && !this.slotOptInEnabled;
          }
        }

        if (!this.loadingFailed) {
          return this._scenarioService.checkScenarioAsync(ScenarioIds.getSiteSlotLimits, { site: siteResult.result });
        } else {
          return Observable.of(null);
        }
      })
      .do(r => {
        if (r && r.status === 'enabled') {
          const slotsQuota = r.data;

          if (this._slotsArm && this._slotsArm.length >= slotsQuota) {
            this.slotsQuotaMessage = this._translateService.instant(PortalResources.slotNew_quotaReached, { quota: slotsQuota });
          }
        }

        this._setupForm();
        this.isLoading = false;
      });
  }

  private _setFunctionAppContext(siteResult: HttpResult<ArmObj<Site>>, appSettingsResult: HttpResult<ArmObj<ApplicationSettings>>) {
    this._functionAppContext = ArmUtil.mapArmSiteToContext(siteResult.result, this._injector);
    if (appSettingsResult.isSuccessful) {
      this._functionAppContext.urlTemplates.runtimeVersion =
        appSettingsResult.result.properties[Constants.runtimeVersionAppSettingName] || FunctionAppVersion.v3;
    }
  }

  private _setupForm() {
    const nameCtrl = this.addForm.get('name');
    const cloneSrcIdCtrl = this.addForm.get('cloneSrcId');
    const cloneSrcConfigCtrl = this.addForm.get('cloneSrcConfig');

    if (!this.hasCreateAccess || !!this.slotsQuotaMessage || this.loadingFailed || (this.slotOptInNeeded && !this.slotOptInEnabled)) {
      nameCtrl.clearValidators();
      nameCtrl.clearAsyncValidators();
      nameCtrl.setValue(null);
      nameCtrl.disable();

      cloneSrcIdCtrl.clearValidators();
      cloneSrcIdCtrl.clearAsyncValidators();
      cloneSrcIdCtrl.setValue(null);
      cloneSrcIdCtrl.disable();

      cloneSrcConfigCtrl.clearValidators();
      cloneSrcConfigCtrl.clearAsyncValidators();
      cloneSrcConfigCtrl.setValue(null);
      cloneSrcConfigCtrl.disable();
    } else {
      const requiredValidator = new RequiredValidator(this._translateService);
      const slotNameValidator = new SlotNameValidator(this._injector, this._siteId);
      nameCtrl.enable();
      nameCtrl.setValue(null);
      nameCtrl.setValidators(requiredValidator.validate.bind(requiredValidator));
      nameCtrl.setAsyncValidators(slotNameValidator.validate.bind(slotNameValidator));

      const splitHostname = this._slotsArm[0].properties.defaultHostName.split(/\.(.+)/);
      this.slotPrefix = splitHostname[0];
      this.slotSuffix = splitHostname[1];

      const options: DropDownElement<string>[] = [
        {
          displayLabel: this._translateService.instant(PortalResources.slotNew_dontCloneConfig),
          value: '-',
        },
      ];
      this._slotsArm.forEach(s => {
        options.push({
          displayLabel: s.name ? s.name.replace('/', '-') : '-',
          value: s.id,
        });
      });
      this.cloneSrcIdDropDownOptions = options;

      const cloneSrcValidator = new CloneSrcValidator(this._siteService, this._translateService, this.addForm);
      cloneSrcIdCtrl.enable();
      cloneSrcIdCtrl.setValue('-');
      cloneSrcIdCtrl.setAsyncValidators(cloneSrcValidator.validate.bind(cloneSrcValidator));

      cloneSrcConfigCtrl.enable();
      cloneSrcConfigCtrl.setValue(null);
    }
  }

  createSlot() {
    this.addForm.markAsPristine();

    const newSlotName = this.addForm.controls['name'].value;
    const newSlotConfig = this.addForm.controls['cloneSrcConfig'].value;
    const siteId = this._slotsArm[0].id;
    const location = this._slotsArm[0].location;
    const serverFarmId = this._slotsArm[0].properties.serverFarmId;
    const cloneConfig = !this.isFunctionApp ? newSlotConfig || {} : undefined;

    const slotNewInfo: SlotNewInfo = {
      resourceId: `${siteId}/slots/${newSlotName}`,
      state: SlotOperationState.started,
    };

    this.addForm.controls['name'].disable();
    this.addForm.controls['cloneSrcId'].disable();
    this.addForm.controls['cloneSrcConfig'].disable();

    this._portalService.broadcastMessage(BroadcastMessageId.slotNew, siteId, slotNewInfo);

    this.setBusy();
    this.progressMessage = this._translateService.instant(PortalResources.slotNew_startCreateNotifyTitle).format(newSlotName);
    this.progressMessageClass = 'spinner';
    this.isCreating = true;
    this.executeButtonDisabled = true;

    this._enableSlotOptIn(siteId)
      .switchMap(s => {
        if (!s || s.isSuccessful) {
          // _enableSlotOptIn() was a no-op or completed successfully
          return this._siteService.createSlot(siteId, newSlotName, location, serverFarmId, cloneConfig);
        } else {
          // _enableSlotOptIn() failed so we pass on the failure
          return Observable.of(s);
        }
      })
      .subscribe(r => {
        if (r.isSuccessful) {
          this.progressMessage = this._translateService.instant(PortalResources.slotNew_startCreateSuccessNotifyTitle).format(newSlotName);
          this.progressMessageClass = 'success';
        } else {
          const errorMessage = r.error && r.error.message;
          this.progressMessage = errorMessage
            ? this._translateService.instant(PortalResources.slotNew_startCreateFailureNotifyTitleExt).format(newSlotName, errorMessage)
            : this._translateService.instant(PortalResources.slotNew_startCreateFailureNotifyTitle).format(newSlotName);
          this.progressMessageClass = 'error';
          this._aiService.trackEvent(errorIds.failedToCreateSlot, { error: r.error.errorId, id: siteId });
          this._logService.error(LogCategories.addSlot, '/add-slot', r.error);
        }

        slotNewInfo.success = r.isSuccessful;
        slotNewInfo.state = SlotOperationState.completed;
        this._portalService.broadcastMessage(BroadcastMessageId.slotNew, siteId, slotNewInfo);

        this.isCreating = false;
        this.clearBusy();
      });
  }

  private _enableSlotOptIn(siteId: string) {
    if (!this.isFunctionApp || !this.slotOptInNeeded) {
      return Observable.of(null);
    } else {
      const newOrUpdatedSettings = {};
      newOrUpdatedSettings[Constants.secretStorageSettingsName] = Constants.secretStorageSettingsValueBlob;
      return this._siteService.addOrUpdateAppSettings(siteId, newOrUpdatedSettings).do(r => {
        if (r.isSuccessful && this._functionAppContext) {
          this._functionAppService.fireSyncTrigger(this._functionAppContext);
        }
      });
    }
  }

  closePanel() {
    this._portalService.closeSelf();
  }

  toggleOptInState() {
    this.slotOptInEnabled = !this.slotOptInEnabled;
    this.executeButtonDisabled = this.slotOptInNeeded && !this.slotOptInEnabled;
    this._setupForm();
  }
}


text:
import click
import os
import yaml
try:
    from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
    from yaml import Loader, Dumper
from .logging import logger

def read(file_path, key=None, safe=False):
    if(not os.path.exists(file_path)):
        return None

    data_file = click.open_file(file_path)
    value = None
    try:
        data = yaml.load(data_file, Loader=Loader)
        data_file.close()
        logger.debug("read data from file %s" % file_path)
        logger.debug(data)
        logger.debug(key)
        if key is None:
            value = data
        else:
            value = data[key]
    except yaml.YAMLError as e:
        logger.error("yaml error" + str(e))
    except KeyError as e:
        logger.debug("KeyError key %s does not exist" % key)
    except TypeError as e:
        logger.debug("Type Error" + str(e))
    return value

def write(file_path, key, value):
    existing_data = read(file_path, None)
    if existing_data is None:
        existing_data = {}

    if key is not None:
        existing_data[key] = value
    else:
        existing_data = value
    data_file = click.open_file(file_path, 'w')
    try:
        logger.debug("writing data to file %s" % file_path)
        logger.debug(existing_data)
        yaml.dump(data=existing_data, stream=data_file, Dumper=Dumper)
    except yaml.YAMLError:
        raise


text:
package dcultrera.registerMachine;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class ProgramLoader {
    public static List<Instruction> loadProgram(String filename) throws IOException, InstructionFormatException {
        List<Instruction> program = new ArrayList<>();

        for (String line : Files.readAllLines(Paths.get(filename))) {
            Instruction i = new Instruction(line);
            program.add(i);
        }

        return program;
    }

    public static int[][] loadRegisters(String filename) throws IOException {
        ArrayList<int[]> allRegisters = new ArrayList<>();

        for (String line : Files.readAllLines(Paths.get(filename))) {
            String[] regsAsString = line.split("\\s+");

            int[] regsAsInt = new int[regsAsString.length];
            for (int i=0; i<regsAsInt.length; i++) {
                regsAsInt[i] = Integer.parseInt(regsAsString[i]);
            }

            allRegisters.add(regsAsInt);
        }
        return allRegisters.toArray(new int[allRegisters.size()][]);
    }
}


text:
<?php

	require_once 'src/data/DAOFactory.php';
	require_once 'src/data/MySqlDataBaseDAO.php';

	class MySqlDAOFactory extends DAOFactory {
		public function getDataBaseOperations() {
			return new MySqlDataBaseDAO();
		}
	}

?>


text:
ACCEPTED

#### According to
Interim Register of Marine and Nonmarine Genera

#### Published in
Mededelingen Rijks Geol. Dienst 40 (2): 22.

#### Original name
null

### Remarks
null


text:
Java Commandline Interface in three lines of code... **or your money back**.

(Free)

# Example

Get this:

![console output](https://github.com/rundeck/cli-toolbelt/raw/master/examples/demo/img/screenshot-console1.png)

From this:

~~~ {.java}
package example;

import org.rundeck.toolbelt.*;

import java.io.IOException;

@SubCommand
public class App {

    public static void main(String[] args) throws IOException, CommandRunFailure {
        ToolBelt.with("example", new App()).runMain(args, true);
    }

    @Command(description = "Simple example")
    public void simple() {
        System.out.println("Easily create commandlines with simple annotation");
    }

    @Command(description = "Fancy example")
    public boolean fancy(@Arg("string") String val) {
        System.out.println("Basic commandline parsing " + val);
        return true;
    }
}
~~~

# Purpose

Simply use annotations on instance method to indicate commands to expose via the CLI.

You can group related sets of commands into different classes, and tie them together
with a top-level "Toolbelt" class.

Builtin features:

* ANSI colorized output
* Simple argument parsing
* Or plugin in a more advanced parser like [JewelCLI][] (see [below](#using-jewelcli))
* Support for printing basic Java container objects in a nice way
* Support for YAML and JSON formatted output for scripting

[JewelCLI]: https://github.com/lexicalscope/jewelcli/

# Using

Find the latest version from the [Releases][] section.

[Releases]: https://github.com/rundeck/cli-toolbelt/releases

Gradle build:

~~~ {.groovy}
repositories {
    jcenter()
}
dependencies{
    compile 'org.rundeck.cli-toolbelt:toolbelt:VERSION'
}
~~~

# Javadoc

* [toolbelt ![javadoc](https://javadoc.io/badge2/org.rundeck.cli-toolbelt/toolbelt/javadoc.svg)](https://javadoc.io/doc/org.rundeck.cli-toolbelt/toolbelt)
* [toolbelt-jewelcli ![javadoc](https://javadoc.io/badge2/org.rundeck.cli-toolbelt/toolbelt-jewelcli/javadoc.svg)](https://javadoc.io/doc/org.rundeck.cli-toolbelt/toolbelt-jewelcli)
* [toolbelt-json-jackson ![javadoc](https://javadoc.io/badge2/org.rundeck.cli-toolbelt/toolbelt-json-jackson/javadoc.svg)](https://javadoc.io/doc/org.rundeck.cli-toolbelt/toolbelt-json-jackson)
* [toolbelt-snakeyaml ![javadoc](https://javadoc.io/badge2/org.rundeck.cli-toolbelt/toolbelt-snakeyaml/javadoc.svg)](https://javadoc.io/doc/org.rundeck.cli-toolbelt/toolbelt-snakeyaml)

# In Progress

* Groovy builder support, see the toolbelt-groovy submodule

# Design

* "Command" : an invocable named action, with optional arguments.
* "Command container": A "Command" may also be a container for other "Commands" (i.e. "Subcommands").
    In that case, the parent "command" is called a "command container".

The simplest structure is a Class with Methods, where the Class is the command container, and the methods are the
sub commands.

# Examples

* Full featured example: [rundeck-cli commandline tool](https://github.com/rundeck/rundeck-cli)
* See the [examples](https://github.com/rundeck/cli-toolbelt/tree/master/examples) directory.

# More Info

Simplest usage:

~~~ {.java}
class Greet{
   @Command void hi(@Arg("name") String name){
       System.out.println("Hello, "+name+".");
   }

   @Command void remark(@Arg("age") int age){
       System.out.println("I see you are "+age+" years old.");
   }
}

class Main{
   public static void main(String[] args){
       ToolBelt.with(new Greet()).runMain(args);
   }
}
~~~

Commandline:

    $ java ... Main greet hi --name bob

    Hello, bob.

    $ java ... Main greet remark --age 33

    I see you are 33 years old.

This constructs a `Tool` object, with a command "greet" (based on the class name
Greet).  "greet" has a "hi" and a "remark" subcommand. The class must have at least
one method annotated with `@Command`.  The parameters of that
method (if any) should be annotated with `@Arg` to define their names.
(Alternately, if you compile your java class with `-parameters` flag to javac, the parameter names will be
introspected.)

This will use the `SimpleCommandInput` to parse "--somearg value" for a
method parameter with arg name "somearg".

You can define multiple commands (with their subcommands) in one step:

~~~{.java}
ToolBelt.with(new Command1(), new Command2(),...).runMain(args);
~~~

For more advanced usage, see below:

Use `org.rundeck.toolbelt.ToolBelt#belt()` to create a builder.

~~~~ {.java}
ToolBelt.belt()
 .defaultHelp()
 .systemOutput()
 .addCommands(
   new MyCommand(),
   new MyCommand2()
 )
 .setParser(new JewelInput())
 .buckle();
~~~~

Within your MyCommand classes, use the {@link org.rundeck.toolbelt.Command @Command} annotation to indicate the
class is a top-level command (optional).  Add the same annotation on any methods within the class to expose them
as subcommands. At least one method should be annotated this way.

~~~ {.java}
@Command(description = "Does something", name="doit")
public class MyCommand{
   @Command(name="sub1") public void sub1(InputArgs args){
       System.out.println("Input args: "+args);
   }
}
~~~

The annotation can exclude the "name" attribute, and the lowercase name of the class or method is used as the
command/subcommand.  The method parameters will be parsed using the input parser (e.g. JewelCLI), so
`InputArgs` must be defined with appropriate annotations.

## Using HasSubCommand interface:

For further nesting, the class can implement `HasSubCommands` and return
other command container objects.

If a `@Command` annotated class wants to define a subcommand which is also a container (has subcommands of
its own), It should implement {@link org.rundeck.toolbelt.HasSubCommands}, and return a list of command
container objects.

~~~{.java}
@Command class First implements HasSubCommands{

   @Command void something(){

       System.out.println("This method prints something")

   }

   List<Object> getCommands(){

       return Arrays.asList(new Second());

   }
}
@Command class Second{

   @Command void third(){

       System.out.println("Third level nested command");

   }
}
~~~

This will define an interface like:

    $ java ... First

    Available commands: [something, second]

    $ java ... First something

    This method prints something

    $ java ... First second

    Availabe commands: [third]

    $ java ... First second third

    Third level nested command

# Using JewelCLI

[JewelCLI][] is a useful interface-based commandline argument parser.  You
can use it with cli-toolbelt:

Add `toolbelt-jewelcli` dependency to your Gradle build:

~~~ {.groovy}
repositories {
    maven { url "https://jitpack.io" }
}
dependencies{
    compile 'com.github.rundeck.cli-toolbelt:toolbelt:VERSION'
    compile 'com.github.rundeck.cli-toolbelt:toolbelt-jewelcli:VERSION'
}
~~~

Add `JewelInput` as a InputParser to your ToolBelt:

~~~{.java}
import org.rundeck.toolbelt.input.jewelcli.JewelInput;
...
Tool cli = ToolBelt.belt(name)
    .add(new MyCommand())
    .commandInput(new JewelInput())
    .build();
~~~

In the `@Command` methods of `MyCommand`, use a parameter annotated with the
JewelCLI commandline argument annotations:

 ~~~{.java}
import com.lexicalscope.jewel.cli.Option;

     interface Widget{
        @Option(shortName="n",description="Widget name")
        String getName();
     }
     @Command(description = "Requeques widgets")
     public boolean requeue(Widget options, CommandOutput out) {
        out.output("Requeueing widget "+options.getName()+"...");
        //...
     }
 ~~~

See the other annotations available from [JewelCLI][]

[JewelCLI]: http://jewelcli.lexicalscope.com/


text:
package br.com.caelum.livraria.login;

import javax.el.ELContext;
import javax.el.ELResolver;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

public class Autorizador implements PhaseListener {

	private static final long serialVersionUID = 1L;

	public void afterPhase(PhaseEvent event) {

		FacesContext context = event.getFacesContext();

		if ("/login.xhtml".equals(context.getViewRoot().getViewId())) {
			return;
		}

		ELContext elContext = context.getELContext();
		ELResolver elResolver = context.getApplication().getELResolver();
		UsuarioLogadoBean usuarioLogado = (UsuarioLogadoBean) elResolver.getValue(elContext, null, "usuarioLogadoBean");

		// Usando o usuarioLogado que foi injetado
		if (!usuarioLogado.isLogado()) {

			NavigationHandler handler = context.getApplication().getNavigationHandler();
			handler.handleNavigation(context, null, "login?faces-redirect=true");

			// efetua renderizacao da tela
			context.renderResponse();
		}
	}

	@Override
	public void beforePhase(PhaseEvent event) {
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

}


text:
"""This implementation of UniqueRandomizer is simple for educational purposes.

This implementation is designed to match the pseudocode in the UniqueRandomizer
paper. Compared to the better implementation in unique_randomizer.py, the
bare-bones implementation in this file lacks:

  * Efficiency tricks, such as storing unsampled probability masses as a single
    numpy array
  * Some useful functions, such as computing the fraction of the space sampled
  * The Randomizer -> UniqueRandomizer/NormalRandomizer object hierarchy
  * UniqueRandomizer with SBS for batching
"""

from typing import List, Optional

import numpy as np

def _log_subtract(x: float, y: float) -> float:
  """Returns log(exp(x) - exp(y)), or negative infinity if x <= y."""
  # Inspired by https://stackoverflow.com/questions/778047.
  return x + np.log1p(-np.exp(np.minimum(y - x, 0)))

def _sample_log_distribution(log_distribution: List[float]) -> int:
  """Samples from an unnormalized probability distribution in log space."""
  # A slower but more numerically stable solution is discussed at
  # https://stats.stackexchange.com/questions/64081. However, we expect that
  # as the randomizer runs, the probability distribution at each node should
  # not be skewed significantly more than the initial provided distribution,
  # since we will sample more frequently from high-probability choices until
  # the probabilities "even out".
  unnormalized = np.exp(log_distribution - np.max(log_distribution))
  distribution = unnormalized / np.sum(unnormalized)
  return int(np.random.choice(np.arange(len(distribution)), p=distribution))

class _TrieNode(object):
  """A trie node for UniqueRandomizer.

  Attributes:
    parent: The _TrieNode parent of this node, or None if this node is the root.
    children: A list of _TrieNode children. The list will be None if this node
      has never sampled a child yet. The list will be empty if this node is a
      leaf.
    unsampled_log_mass: The current unsampled log probability mass at this node.
  """

  def __init__(self,
               parent: Optional['_TrieNode'],
               unsampled_log_mass: float) -> None:
    """Initializes a _TrieNode."""
    self.parent = parent
    self.children = None
    self.unsampled_log_mass = unsampled_log_mass

def _node_exhausted(node: _TrieNode) -> bool:
  """Returns whether all of the mass at this node has been sampled."""
  if node.children == []:  # Distinguish [] and None. pylint: disable=g-explicit-bool-comparison
    return True  # This node is a leaf.
  if node.children is None:
    return False  # This node is not a leaf but has never been sampled from.
  return all(child.unsampled_log_mass == np.NINF for child in node.children)

class UniqueRandomizer(object):
  """Samples unique sequences of discrete random choices.

  When using a UniqueRandomizer object to provide randomness, the client
  algorithm must be deterministic and behave identically when given a constant
  sequence of choices.

  When a sequence of choices is complete, the client algorithm must call
  `mark_sequence_complete()`. This will update the internal data so that the
  next sampled choices form a new sequence, which is guaranteed to be different
  from previous complete sequences.

  Choices returned by a UniqueRandomizer object respect the initial probability
  distributions provided by the client algorithm, conditioned on the constraint
  that a complete sequence of choices cannot be sampled more than once.

  `sample_distribution()` returns an int in the range [0, num_choices), raising
  a ValueError if all possible sequences of choices have already been sampled.
  """

  def __init__(self) -> None:
    """Initializes a UniqueRandomizer object."""
    self.root_node = _TrieNode(None, 0.0)
    self.current_node = self.root_node

  def sample_distribution(self, distribution: List[float]) -> int:
    """Samples from a given probability distribution."""
    if _node_exhausted(self.current_node):
      raise ValueError('This node has been completely sampled already.')

    current = self.current_node
    if not current.children:
      # This is the first sample from the current node. Set up its children.
      # Note that the current node's unsampled_log_mass is still the initial
      # log probability mass, since the node has never been sampled from before.
      current.children = [
          _TrieNode(parent=current, unsampled_log_mass=float(log_mass))
          for log_mass in np.log(distribution) + current.unsampled_log_mass]

    child_index = _sample_log_distribution([child.unsampled_log_mass
                                            for child in current.children])

    self.current_node = current.children[child_index]
    return child_index

  def mark_sequence_complete(self) -> float:
    """Ends a sequence of choices and returns its log probability."""
    self.current_node.children = []  # This marks the current node as a leaf.

    # Update unsampled log masses for all ancestors.
    sampled_log_mass = self.current_node.unsampled_log_mass
    node = self.current_node
    while node:
      if _node_exhausted(node):
        node.unsampled_log_mass = np.NINF
      else:
        node.unsampled_log_mass = _log_subtract(node.unsampled_log_mass,
                                                sampled_log_mass)
      node = node.parent

    self.current_node = self.root_node
    return sampled_log_mass

  def exhausted(self) -> bool:
    """Returns whether all possible sequences of choices have been sampled."""
    return _node_exhausted(self.root_node)


text:
package com.mredrock.cyxbs.presenter.activity;

import android.content.res.Configuration;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.MenuItem;

import com.mredrock.cyxbs.event.NavEvent;
import com.mredrock.cyxbs.presenter.fragment.CalendarContainerFragment;
import com.mredrock.cyxbs.presenter.fragment.DiscoveryContainerFragment;
import com.mredrock.cyxbs.presenter.fragment.InquiryContainerFragment;
import com.mredrock.cyxbs.presenter.fragment.NewsContainerFragment;
import com.mredrock.cyxbs.presenter.fragment.CourseContainerFragment;
import com.mredrock.cyxbs.view.impl.HomeVu;

public class HomeActivity extends BasePresenterActivity<HomeVu> {

    @Override
    protected boolean shouldSwipeBack() {
        return false;
    }

    @Override
    public Class<HomeVu> getVuClass() {
        return HomeVu.class;
    }

    @Override
    public void onBindVu() {
        navigate(0);
        vu.configureDrawer(this);
    }

    @Override
    protected void afterResume() {
        bus.registerSticky(this);
    }

    @Override
    protected void beforePause() {
        bus.unregister(this);
    }

    @Override
    public boolean handleBackPressed() {
        bus.removeAllStickyEvents();
        if(vu.isDrawerOpen()){
            vu.closeDrawer();
            return true;
        }
        return false;
    }

    public void onEvent(NavEvent event) {
        navigate(event.position);
    }

    private void navigate(int position) {
        FragmentTransaction transaction = fm.beginTransaction();
        Fragment fragment;
        switch (position) {
            case 0:
                fragment = CourseContainerFragment.newInstance();
                break;
            case 1:
                fragment = CalendarContainerFragment.newInstance();
                break;
            case 2:
                fragment = NewsContainerFragment.newInstance();
                break;
            case 3:
                fragment = InquiryContainerFragment.newInstance();
                break;
            case 4:
                fragment = DiscoveryContainerFragment.newInstance();
                break;
            default:
                fragment = CourseContainerFragment.newInstance();
                break;
        }
        transaction.replace(vu.getContainerId(),fragment ).commit();
        vu.closeDrawer();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        vu.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return vu.onDrawerToggleSelected(item) || super.onOptionsItemSelected(item);
    }
}


text:
#include <pcl/point_types.h>
#include <pcl/impl/instantiate.hpp>
#include <pcl/features/shot_omp.h>
#include <pcl/features/impl/shot_omp.hpp>

// Instantiations of specific point types
#ifdef PCL_ONLY_CORE_POINT_TYPES
  PCL_INSTANTIATE_PRODUCT(SHOTEstimationOMP, ((pcl::PointXYZ)(pcl::PointXYZI)(pcl::PointXYZRGB)(pcl::PointXYZRGBA))((pcl::Normal))((pcl::SHOT))((pcl::ReferenceFrame)))
#else
  PCL_INSTANTIATE_PRODUCT(SHOTEstimationOMP, (PCL_XYZ_POINT_TYPES)(PCL_NORMAL_POINT_TYPES)((pcl::SHOT))((pcl::ReferenceFrame)))
#endif


text:
import itertools
import functools

import numpy as np
import networkx as nx
from scipy.spatial.distance import squareform, pdist

from .snf import low, smith_normal_form

__all__ = ['PersistentHomology']

def buildGraph(data, epsilon=1., metric='euclidean', p=2):
    D = squareform(pdist(data, metric=metric, p=p))
    D[D >= epsilon] = 0.
    G = nx.Graph(D)
    edges = list(map(set, G.edges()))
    weights = [G.get_edge_data(u, v)['weight'] for u, v in G.edges()]
    return G.nodes(), edges, weights

def lower_nbrs(nodeSet, edgeSet, node):
    return {x for x in nodeSet if {x, node} in edgeSet and node > x}

def rips(nodes, edges, k):
    VRcomplex = [{n} for n in nodes]
    for e in edges:  # add 1-simplices (edges)
        VRcomplex.append(e)
    for i in range(k):
        # skip 0-simplices
        for simplex in [x for x in VRcomplex if len(x) == i + 2]:
            # for each u in simplex
            nbrs = set.intersection(
                *[lower_nbrs(nodes, edges, z) for z in simplex])
            for nbr in nbrs:
                VRcomplex.append(set.union(simplex, {nbr}))
    return VRcomplex

def ripsFiltration(graph, k):
    nodes, edges, weights = graph
    VRcomplex = [{n} for n in nodes]
    filter_values = [0 for j in VRcomplex]  # vertices have filter value of 0
    # add 1-simplices (edges) and associated filter values
    for i in range(len(edges)):
        VRcomplex.append(edges[i])
        filter_values.append(weights[i])
    if k > 1:
        for i in range(k):
            # skip 0-simplices and 1-simplices
            for simplex in [x for x in VRcomplex if len(x) == i + 2]:
                # for each u in simplex
                nbrs = set.intersection(
                    *[lower_nbrs(nodes, edges, z) for z in simplex])
                for nbr in nbrs:
                    newSimplex = set.union(simplex, {nbr})
                    VRcomplex.append(newSimplex)
                    filter_values.append(getFilterValue(
                        newSimplex, VRcomplex, filter_values))

    # sort simplices according to filter values
    return sortComplex(VRcomplex, filter_values)

def getFilterValue(simplex, edges, weights):
    oneSimplices = list(itertools.combinations(simplex, 2))
    max_weight = 0
    for oneSimplex in oneSimplices:
        filter_value = weights[edges.index(set(oneSimplex))]
        if filter_value > max_weight:
            max_weight = filter_value
    return max_weight

def compare(item1, item2):
    if len(item1[0]) == len(item2[0]):
        if item1[1] == item2[1]:
            if sum(item1[0]) > sum(item2[0]):
                return 1
            else:
                return -1
        else:
            if item1[1] > item2[1]:
                return 1
            else:
                return -1
    else:
        if len(item1[0]) > len(item2[0]):
            return 1
        else:
            return -1

def sortComplex(filterComplex, filterValues):
    pairedList = zip(filterComplex, filterValues)
    sortedComplex = sorted(pairedList, key=functools.cmp_to_key(compare))
    sortedComplex = [list(t) for t in zip(*sortedComplex)]

    return sortedComplex

def nSimplices(n, filterComplex):
    nchain = []
    nfilters = []
    for i in range(len(filterComplex[0])):
        simplex = filterComplex[0][i]
        if len(simplex) == (n + 1):
            nchain.append(simplex)
            nfilters.append(filterComplex[1][i])
    if (nchain == []):
        nchain = [0]
    return nchain, nfilters

def checkFace(face, simplex):
    if simplex == 0:
        return 1

    elif (set(face) < set(simplex) and (len(face) == (len(simplex) - 1))):
        return 1
    else:
        return 0

def filterBoundaryMatrix(filterComplex):
    bmatrix = np.zeros(
        (len(filterComplex[0]), len(filterComplex[0])), dtype=np.uint8)

    i = 0
    for colSimplex in filterComplex[0]:
        j = 0
        for rowSimplex in filterComplex[0]:
            bmatrix[j, i] = checkFace(rowSimplex, colSimplex)
            j += 1
        i += 1
    return bmatrix

def readIntervals(reduced_matrix, filterValues):
    intervals = []
    m = reduced_matrix.shape[1]
    for j in range(m):
        low_j = low(j, reduced_matrix)
        if low_j == (m - 1):
            interval_start = [j, -1]
            intervals.append(interval_start)

        else:
            feature = intervals.index([low_j, -1])
            intervals[feature][1] = j
            epsilon_start = filterValues[intervals[feature][0]]
            epsilon_end = filterValues[j]
            if epsilon_start == epsilon_end:
                intervals.remove(intervals[feature])

    return intervals

def readPersistence(intervals, filterComplex):
    persistence = []
    for interval in intervals:
        start = interval[0]
        end = interval[1]

        homology_group = (len(filterComplex[0][start]) - 1)
        epsilon_start = filterComplex[1][start]
        epsilon_end = filterComplex[1][end]
        persistence.append([homology_group, [epsilon_start, epsilon_end]])

    return persistence

class PersistentHomology(object):

    def __init__(self, epsilon=1., k=3):
        self.epsilon = epsilon
        self.k = k

    def fit(self, X):
        self.graph = buildGraph(X, epsilon=self.epsilon)
        self.ripsComplex = ripsFiltration(self.graph, k=self.k)
        self.boundary_matrix = filterBoundaryMatrix(self.ripsComplex)
        self.reduced_boundary_matrix = smith_normal_form(self.boundary_matrix)
        return self

    def transform(self, X):
        intervals = readIntervals(self.reduced_boundary_matrix,
                                  self.ripsComplex[1])
        persistence = readPersistence(intervals, self.ripsComplex)
        return persistence

    def fit_transform(self, X):
        self.fit(X)
        return self.transform(X)


text:
<?php

namespace Lollipop\HTTP;

/**
 * Middleware Interface
 *
 * @author  John Aldrich Bernardo <4ldrich@protonmail.com>
 *
 */
interface Middleware {

    /**
     * All middleware will be required to be a callable
     * so __invoke function is a must so parameters to be instance of Lollipop Router
     * classes
     *
     * @access  public
     * @param   \Lollipop\HTTP\Request    $request    HTTP Request Object
     * @param   \Lollipop\HTTP\Response   $response   HTTP Response Object
     * @return  \Lollipop\HTTP\Response   Response Object
     *
     */
    public function __invoke(\Lollipop\HTTP\Request $request, \Lollipop\HTTP\Response $response, callable $next);

}