text:
var req;

// FUNÇÃO PARA BUSCA NOTICIA
function buscarCrimes() {

// Verificando Browser
if(window.XMLHttpRequest) {
   req = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
   req = new ActiveXObject("Microsoft.XMLHTTP");
}

// Arquivo PHP juntamente com o valor digitado no campo (método GET)

var concatenador;
var array=[];
var valorRecebido = document.getElementById("cidade").value;
if (valorRecebido!=null){
valorRecebido ="cidade LIKE "+ '"%"'+"'"+valorRecebido+"%'";
array.push(valorRecebido);
}

valorRecebido = document.getElementById("data_ocorrencia").value;
if (valorRecebido!=null){
valorRecebido ="data_ocorrencia LIKE '"+valorRecebido+"'";
array.push(valorRecebido);
}

valorRecebido = document.getElementById("idade").value;
if (valorRecebido!=null){
    valorRecebido=valorRecebido ="idade LIKE "+valorRecebido;
array.push(valorRecebido);
}

valorRecebido = document.getElementById("nome_vitima").value;
if (valorRecebido!=null){
    valorRecebido ="nome_vitima LIKE "+"'%"+valorRecebido+"%'"
array.push(valorRecebido);
}

valorRecebido = document.getElementById("objeto_utilizado").value;
if (valorRecebido!=null){
    valorRecebido ="objeto_utilizado LIKE "+"'%"+valorRecebido+"%'";
array.push(valorRecebido);
}

valorRecebido = document.getElementById("qtd_vitimas").value;
if (valorRecebido!=null){
    valorRecebido ="qtd_vitimas LIKE "+valorRecebido;
array.push(valorRecebido);
}

valorRecebido = document.getElementById("sexo").value;
if (valorRecebido!=null){
    valorRecebido ="sexo LIKE "+"'%"+valorRecebido+"%'";
array.push(valorRecebido);
}

valorRecebido = document.getElementById("tipo_crime").value;
if (valorRecebido!=null){
    valorRecebido ="tipo_crime LIKE "+"'%"+valorRecebido+"%'";
array.push(valorRecebido);
}
i=0;

while (i<array.length){
if (i==0){
    concatenador= array[i]
}
else{
    concatenador=concatenador+array[i];
}

if (i!=array.length-1){
        concatenador+=" and ";

    }
i+=1;
}

var url = "consultarCrime.php?valor="+concatenador;

// Chamada do método open para processar a requisição
req.open("Get", url, true);

// Quando o objeto recebe o retorno, chamamos a seguinte função;
req.onreadystatechange = function() {

    // Exibe a mensagem "Buscando crimes..." enquanto carrega
    if(req.readyState == 1) {
        document.getElementById('resultado').innerHTML = 'Buscando crimes...';
    }

    // Verifica se o Ajax realizou todas as operações corretamente
    if(req.readyState == 4 && req.status == 200) {

    // Resposta retornada pelo busca.php
    var resposta = req.responseText;

    // Abaixo colocamos a(s) resposta(s) na div resultado
    document.getElementById('resultado').innerHTML = resposta;
    }
}
req.send(null);
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Espírita</logradouro><bairro>Cambuci</bairro><cidade>São Paulo</cidade><uf>SP</uf><cep>01527040</cep></feed>

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 7: 114 (1953)

#### Original name
Aplosporella chamaecristae Petr.

### Remarks
null


text:
package com.paypal.selion.grid.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.openqa.grid.internal.Registry;
import org.openqa.grid.internal.utils.CapabilityMatcher;
import org.openqa.grid.web.servlet.RegistryBasedServlet;

import com.paypal.selion.grid.matchers.SeLionSauceCapabilityMatcher;
import com.paypal.selion.pojos.SeLionGridConstants;
import com.paypal.selion.utils.AuthenticationHelper;
import com.paypal.selion.utils.ServletHelper;

/**
 * This plain vanilla servlet is responsible for supporting login/logout and display of the main page.
 *
 */
public class LoginServlet extends RegistryBasedServlet {

    private static final long serialVersionUID = 1L;

    private static final String RESOURCE_PAGE_FILE = "/com/paypal/selion/html/loginServlet.html";

    /**
     * Request parameter to perform logout. Value must be 'true'.
     */
    public static final String LOGOUT = "logout";

    /**
     * Request parameter to perform login. Value must be 'login'.
     */
    public static final String FORM_ID = "form_id";

    /**
     * Request parameter that carries the userid
     */
    public static final String USER_ID = "userid";

    /**
     * Request parameter that carries the password
     */
    public static final String PASSWORD = "password";

    public LoginServlet(Registry registry) {
        super(registry);
    }

    public LoginServlet() {
        this(null);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.getParameter(LOGOUT) != null && req.getParameter(LOGOUT).equals("true")) {

            HttpSession session = req.getSession();
            if (session != null) {
                session.invalidate();
            }
            ServletHelper.respondAsHtmlUsingArgsAndTemplateWithHttpStatus(resp, RESOURCE_PAGE_FILE,
                    HttpServletResponse.SC_OK, "Enter username and password");
        } else {
            process(req, resp);
        }
    }

    private void process(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        if (req.getParameter(FORM_ID) != null && req.getParameter(FORM_ID).equals("login")) {
            String userId = req.getParameter(USER_ID);
            String password = req.getParameter(PASSWORD);
            // For already created session , if the session has username and the password then use the same to
            // authenticate user else get back to the parameters from the request
            HttpSession currentSession = req.getSession(false);
            if (currentSession != null) {
                userId = (String) currentSession.getAttribute(USER_ID);
                password = (String) currentSession.getAttribute(PASSWORD);
            }

            if (!AuthenticationHelper.authenticate(userId, password)) {
                /*
                 * To display error message if invalid username or password is entered
                 */
                ServletHelper.respondAsHtmlUsingArgsAndTemplateWithHttpStatus(resp, RESOURCE_PAGE_FILE,
                        HttpServletResponse.SC_OK, "<b>Invalid Credentials. Enter valid Username and Password</b>");
            } else {

                /*
                 * After successful login main page will be displayed with links to force restart and autoupgrade. Note:
                 * For every re-direction, a new session is created and the userId and password are forwarded with the
                 * session
                 */
                req.getSession(true);
                req.getSession().setAttribute(USER_ID, userId);
                req.getSession().setAttribute(PASSWORD, password);

                String page = SeLionGridConstants.GRID_HOME_PAGE_URL;
                CapabilityMatcher matcher = getRegistry().getConfiguration().capabilityMatcher;
                if (matcher instanceof SeLionSauceCapabilityMatcher) {
                    page = SeLionGridConstants.SAUCE_GRID_HOMEPAGE_URL;
                }

                resp.sendRedirect(page);
            }

        } else {

            /*
             * Login form will be displayed to get user name and password. If already created sessions are available,
             * those sessions will be invalidated
             */
            HttpSession session = req.getSession(false);
            if (session != null) {
                session.invalidate();
            }
            ServletHelper.respondAsHtmlUsingArgsAndTemplateWithHttpStatus(resp, RESOURCE_PAGE_FILE,
                    HttpServletResponse.SC_OK, "Enter username and password");
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        process(request, response);
    }
}


text:
<?php

namespace Troopers\AsseticInjectorBundle\AssetsCollector;

use Symfony\Component\Finder\Finder;

/**
 * Assets collector.
 *
 * @author Paul Andrieux <paul@troopers.email>
 */
class Collector
{
    /**
     * Constructor.
     *
     * @param Container $container The container
     */
    public function __construct($container)
    {
        $this->container = $container;
    }

    /**
     * Inject the assets.
     *
     * @param \Twig_TokenParser $parser
     */
    public function injectAssets(\Twig_TokenParser $parser)
    {
        $parser->addAssets($this->getAssets());
    }

    /**
     * Get the assets for each bundle.
     *
     * @return multitype:
     */
    public function getAssets()
    {
        //this is the app directory.
        //the console is in this directory
        $rootDir = $this->container->get('kernel')->getRootDir();
        $appOverrideDir = '/Resources';

        $resources = [];
        $finder = new Finder();
        $finder->files()->name('assetic_injector.json');
        foreach ($this->container->get('kernel')->getBundles() as $bundle) {
            //the number of files found in the override path
            $finderCount = 0;
            //the bundle name
            $bundleName = $bundle->getName();

            //the override path
            $overridePath = $rootDir.$appOverrideDir.'/'.$bundleName.'/config/';

            //does the file exists in the app/Resources
            if (file_exists($overridePath)) {
                $finder->in($overridePath);
                $finderCount = $finder->count();
            }

            //if no files were found
            if ($finderCount === 0) {
                if (file_exists($bundle->getPath().'/Resources/config/')) {
                    $finder->in($bundle->getPath().'/Resources/config/');
                }
            }
        }
        $injectArray = [];
        foreach ($finder as $file) {
            $json = file_get_contents($file);
            if (is_array(json_decode($json, true))) {
                $injectArray = array_merge_recursive($injectArray, json_decode($json, true));
            }
        }

        foreach ($injectArray as $engine => $assets) {
            $engine = $this->container->get('assetic_injector.'.$engine);
            $engine->compute($assets);
            $resources = array_merge_recursive($resources, $engine->getResources());
        }

        return $resources;
    }
}


text:
<!doctype HTML>
<title>Exam</title>

CLASS NAME, EXAM 1

Name:   _________________________________

Question #1
Fill In The Blank
____ / 1

What is the
capital of Texas?

Question #2
Multiple Choice, One Answer
____ / 2

What is the
capital of Washington?

<input type='radio' class='answer-mc'>Seattle

<input type='radio' class='answer-mc'>Boise

<input type='radio' class='answer-mc'>Salem

<input type='radio' class='answer-mc'>Olympia

0b1b


text:
echo "Installing MariaDB"
yum install -y mariadb-server

echo "Adding MariaDB service to autostart"
systemctl enable mariadb.service

echo "Starting MariaDB service"
systemctl start mariadb.service

# find the DB folder
if [ -d /vagrant/database ]
then
	echo "Found folder 'database', using as db folder"
	DATABASE_FOLDER="database"
elif [ -d /vagrant/db ]
then
	echo "Found folder db, using as db folder"
	DATABASE_FOLDER="db"
else
	echo "Can't find db folder. Quitting..."
	exit 1
fi

DEL_FILES=()
#extract .sql.gz files - these need to be cleaned up afterwards!
GZ_FILES=/vagrant/$DATABASE_FOLDER/*.sql.gz
shopt -s nullglob
for file in $GZ_FILES
do
	FILENAME=`basename $file .gz`
	gunzip -c -v $file > /vagrant/$DATABASE_FOLDER/$FILENAME
	DEL_FILES+=("/vagrant/$DATABASE_FOLDER/$FILENAME")
done;

BZ2_FILES=/vagrant/$DATABASE_FOLDER/*.sql.bz2
shopt -s nullglob
for file in $BZ2_FILES
do
	FILENAME=`basename $file .bz2`
	bzip2 -dkc $file > /vagrant/$DATABASE_FOLDER/$FILENAME
	DEL_FILES+=("/vagrant/$DATABASE_FOLDER/$FILENAME")
done;

DB_FILES=/vagrant/$DATABASE_FOLDER/*.sql
shopt -s nullglob
for file in $DB_FILES
do
	DB_NAME=`basename $file .sql`
	echo "Creating database '$DB_NAME'"
	# Drop the DB so that we can run the provisioner on a machine that already has had it run once
	mysql -u root <<< "DROP DATABASE IF EXISTS \`$DB_NAME\`; CREATE DATABASE IF NOT EXISTS \`$DB_NAME\`;"

	echo "Importing database dump"
	sed '/^CREATE DATABASE/d;/^USE/d' $file | mysql $DB_NAME -u root
done;

for file in $DEL_FILES
do
	rm -f $file
done;

echo "Databases imported"

#Reload the database
echo "Setting DB permissions for root"
mysql -u root <<< "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION; FLUSH PRIVILEGES;"

echo "MariaDB installed"


text:
import {Injector} from 'di';
import {Kitchen} from 'lib/kitchen-di/kitchen'
import {MockHeater} from 'lib/kitchen-di/mock_heater';
import {ConsoleReporter} from 'log/reporters/console';
import {Logger} from 'lib/log/reporters/console';
import {IOServer, RuntimeEnv} from 'src/io/server'

export function main(){

//    var injector = new Injector([]);
    var injector = new Injector([MockHeater]);

    var kitchen = injector.get(Kitchen);

    kitchen.makeBreakfast();

};


text:
angular.module("RadCalc").filter("twoDecimalsFilter", function () {

    return function (value) {
        return decimalFormatter.format(value, 2);
    };
});


text:
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Generate_Main(object):
    def setupUi(self, Generate_Main):
        Generate_Main.setObjectName("Generate_Main")
        Generate_Main.resize(419, 252)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(Generate_Main.sizePolicy().hasHeightForWidth())
        Generate_Main.setSizePolicy(sizePolicy)
        self.centralwidget = QtWidgets.QWidget(Generate_Main)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
        self.centralwidget.setSizePolicy(sizePolicy)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 10, 401, 232))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_3.setSpacing(0)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.gridLayout = QtWidgets.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.tr_label = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.tr_label.setObjectName("tr_label")
        self.gridLayout.addWidget(self.tr_label, 2, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
        spacerItem = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
        self.gridLayout.addItem(spacerItem, 5, 0, 1, 1)
        self.lineEdit = QtWidgets.QLineEdit(self.verticalLayoutWidget)
        self.lineEdit.setMaximumSize(QtCore.QSize(164, 16777215))
        self.lineEdit.setObjectName("lineEdit")
        self.gridLayout.addWidget(self.lineEdit, 0, 2, 1, 1, QtCore.Qt.AlignHCenter)
        self.tl_label = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.tl_label.setObjectName("tl_label")
        self.gridLayout.addWidget(self.tl_label, 0, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
        self.bl_label = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.bl_label.setObjectName("bl_label")
        self.gridLayout.addWidget(self.bl_label, 6, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
        self.comboBox_2 = QtWidgets.QComboBox(self.verticalLayoutWidget)
        self.comboBox_2.setMinimumSize(QtCore.QSize(164, 0))
        self.comboBox_2.setObjectName("comboBox_2")
        self.comboBox_2.addItem("")
        self.comboBox_2.addItem("")
        self.gridLayout.addWidget(self.comboBox_2, 6, 2, 1, 1, QtCore.Qt.AlignHCenter)
        self.comboBox = QtWidgets.QComboBox(self.verticalLayoutWidget)
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.gridLayout.addWidget(self.comboBox, 2, 2, 1, 1, QtCore.Qt.AlignHCenter)
        self.energy = QtWidgets.QLineEdit(self.verticalLayoutWidget)
        self.energy.setMaximumSize(QtCore.QSize(164, 16777215))
        self.energy.setObjectName("energy")
        self.gridLayout.addWidget(self.energy, 4, 2, 1, 1, QtCore.Qt.AlignHCenter)
        self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 4, 0, 1, 1, QtCore.Qt.AlignHCenter)
        spacerItem1 = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
        self.gridLayout.addItem(spacerItem1, 3, 0, 1, 1)
        spacerItem2 = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
        self.gridLayout.addItem(spacerItem2, 1, 0, 1, 1)
        self.verticalLayout_3.addLayout(self.gridLayout)
        spacerItem3 = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
        self.verticalLayout_3.addItem(spacerItem3)
        self.buttonBox = QtWidgets.QDialogButtonBox(self.verticalLayoutWidget)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.verticalLayout_3.addWidget(self.buttonBox)
        Generate_Main.setCentralWidget(self.centralwidget)

        self.retranslateUi(Generate_Main)
        QtCore.QMetaObject.connectSlotsByName(Generate_Main)

    def retranslateUi(self, Generate_Main):
        _translate = QtCore.QCoreApplication.translate
        Generate_Main.setWindowTitle(_translate("Generate_Main", "Generate Distribution"))
        self.tr_label.setText(_translate("Generate_Main", "Species:"))
        self.tl_label.setText(_translate("Generate_Main", "Number of Particles:"))
        self.bl_label.setText(_translate("Generate_Main", "Input Parameter Type:"))
        self.comboBox_2.setItemText(0, _translate("Generate_Main", "Envelope"))
        self.comboBox_2.setItemText(1, _translate("Generate_Main", "Twiss"))
        self.comboBox.setItemText(0, _translate("Generate_Main", "Proton"))
        self.comboBox.setItemText(1, _translate("Generate_Main", "Electron"))
        self.comboBox.setItemText(2, _translate("Generate_Main", "Dihydrogen cation"))
        self.comboBox.setItemText(3, _translate("Generate_Main", "Alpha particle"))
        self.label.setText(_translate("Generate_Main", "Energy (MeV):"))


text:
#include "pyramidROIAlignPlugin.h"
#include "common/plugin.h"
#include <cuda_runtime_api.h>
#include <math.h>

using namespace nvinfer1;
using namespace plugin;
using nvinfer1::plugin::PyramidROIAlign;
using nvinfer1::plugin::PyramidROIAlignPluginCreator;

namespace
{
char const* PYRAMIDROIALGIN_PLUGIN_VERSION{"1"};
char const* PYRAMIDROIALGIN_PLUGIN_NAME{"PyramidROIAlign_TRT"};
} // namespace

PluginFieldCollection PyramidROIAlignPluginCreator::mFC{};
std::vector<PluginField> PyramidROIAlignPluginCreator::mPluginAttributes;

PyramidROIAlignPluginCreator::PyramidROIAlignPluginCreator()
{
    mPluginAttributes.clear();
    mPluginAttributes.emplace_back(PluginField("fpn_scale", nullptr, PluginFieldType::kINT32, 1));
    mPluginAttributes.emplace_back(PluginField("pooled_size", nullptr, PluginFieldType::kINT32, 1));
    mPluginAttributes.emplace_back(PluginField("image_size", nullptr, PluginFieldType::kINT32, 2));
    mPluginAttributes.emplace_back(PluginField("roi_coords_absolute", nullptr, PluginFieldType::kINT32, 1));
    mPluginAttributes.emplace_back(PluginField("roi_coords_swap", nullptr, PluginFieldType::kINT32, 1));
    mPluginAttributes.emplace_back(PluginField("roi_coords_plusone", nullptr, PluginFieldType::kINT32, 1));
    mPluginAttributes.emplace_back(PluginField("roi_coords_transform", nullptr, PluginFieldType::kINT32, 1));
    mPluginAttributes.emplace_back(PluginField("sampling_ratio", nullptr, PluginFieldType::kINT32, 1));
    mPluginAttributes.emplace_back(PluginField("legacy", nullptr, PluginFieldType::kINT32, 1));

    mFC.nbFields = mPluginAttributes.size();
    mFC.fields = mPluginAttributes.data();
}

char const* PyramidROIAlignPluginCreator::getPluginName() const noexcept
{
    return PYRAMIDROIALGIN_PLUGIN_NAME;
}

char const* PyramidROIAlignPluginCreator::getPluginVersion() const noexcept
{
    return PYRAMIDROIALGIN_PLUGIN_VERSION;
}

PluginFieldCollection const* PyramidROIAlignPluginCreator::getFieldNames() noexcept
{
    return &mFC;
}

IPluginV2Ext* PyramidROIAlignPluginCreator::createPlugin(char const* name, PluginFieldCollection const* fc) noexcept
{
    try
    {
        // Default values for the plugin creator, these will be used when the corresponding
        // plugin field is not passed, allowing to have defaults for "optional" ONNX attributes.
        int32_t pooledSize = 7;
        int32_t transformCoords = 2;
        bool absCoords = true;
        bool swapCoords = false;
        bool plusOneCoords = false;
        bool legacy = false;
        int32_t samplingRatio = 0;
        xy_t imageSize = {MaskRCNNConfig::IMAGE_SHAPE.d[1], MaskRCNNConfig::IMAGE_SHAPE.d[2]};
        int32_t fpnScale = 224;

        PluginField const* fields = fc->fields;
        for (int32_t i = 0; i < fc->nbFields; ++i)
        {
            char const* attrName = fields[i].name;
            if (!strcmp(attrName, "fpn_scale"))
            {
                PLUGIN_VALIDATE(fields[i].type == PluginFieldType::kINT32);
                fpnScale = *(static_cast<int32_t const*>(fields[i].data));
                PLUGIN_VALIDATE(fpnScale >= 1);
            }
            if (!strcmp(attrName, "pooled_size"))
            {
                PLUGIN_VALIDATE(fields[i].type == PluginFieldType::kINT32);
                pooledSize = *(static_cast<int32_t const*>(fields[i].data));
                PLUGIN_VALIDATE(pooledSize >= 1);
            }
            if (!strcmp(attrName, "image_size"))
            {
                PLUGIN_VALIDATE(fields[i].type == PluginFieldType::kINT32);
                PLUGIN_VALIDATE(fields[i].length == 2);
                auto const dims = static_cast<int32_t const*>(fields[i].data);
                imageSize.y = dims[0];
                imageSize.x = dims[1];
                PLUGIN_VALIDATE(imageSize.y >= 1);
                PLUGIN_VALIDATE(imageSize.x >= 1);
            }
            if (!strcmp(attrName, "roi_coords_absolute"))
            {
                PLUGIN_VALIDATE(fields[i].type == PluginFieldType::kINT32);
                absCoords = *(static_cast<int32_t const*>(fields[i].data));
            }
            if (!strcmp(attrName, "roi_coords_swap"))
            {
                PLUGIN_VALIDATE(fields[i].type == PluginFieldType::kINT32);
                swapCoords = *(static_cast<int32_t const*>(fields[i].data));
            }
            if (!strcmp(attrName, "roi_coords_plusone"))
            {
                PLUGIN_VALIDATE(fields[i].type == PluginFieldType::kINT32);
                plusOneCoords = *(static_cast<int32_t const*>(fields[i].data));
            }
            if (!strcmp(attrName, "roi_coords_transform"))
            {
                PLUGIN_VALIDATE(fields[i].type == PluginFieldType::kINT32);
                transformCoords = *(static_cast<int32_t const*>(fields[i].data));
            }
            if (!strcmp(attrName, "sampling_ratio"))
            {
                PLUGIN_VALIDATE(fields[i].type == PluginFieldType::kINT32);
                samplingRatio = *(static_cast<int32_t const*>(fields[i].data));
                PLUGIN_VALIDATE(samplingRatio >= 0);
            }
            if (!strcmp(attrName, "legacy"))
            {
                PLUGIN_ASSERT(fields[i].type == PluginFieldType::kINT32);
                legacy = *(static_cast<int32_t const*>(fields[i].data));
            }
            if (!strcmp(attrName, "legacy"))
            {
                PLUGIN_ASSERT(fields[i].type == PluginFieldType::kINT32);
                legacy = *(static_cast<int32_t const*>(fields[i].data));
            }
        }
        return new PyramidROIAlign(
            pooledSize, transformCoords, absCoords, swapCoords, plusOneCoords, samplingRatio, legacy, imageSize, fpnScale);
    }
    catch (std::exception const& e)
    {
        caughtError(e);
    }
    return nullptr;
}

IPluginV2Ext* PyramidROIAlignPluginCreator::deserializePlugin(
    char const* name, void const* data, size_t length) noexcept
{
    try
    {
        return new PyramidROIAlign(data, length);
    }
    catch (std::exception const& e)
    {
        caughtError(e);
    }
    return nullptr;
}

PyramidROIAlign::PyramidROIAlign(int32_t pooledSize, int32_t transformCoords, bool absCoords, bool swapCoords,
    bool plusOneCoords, int32_t samplingRatio, bool legacy, xy_t imageSize, int32_t fpnScale)
    : mPooledSize({pooledSize, pooledSize})
    , mImageSize(imageSize)
    , mFPNScale(fpnScale)
    , mTransformCoords(transformCoords)
    , mAbsCoords(absCoords)
    , mSwapCoords(swapCoords)
    , mPlusOneCoords(plusOneCoords)
    , mSamplingRatio(samplingRatio)
    , mIsLegacy(legacy)
{
    PLUGIN_VALIDATE(pooledSize >= 1);
    PLUGIN_VALIDATE(samplingRatio >= 0);
    PLUGIN_VALIDATE(fpnScale >= 1);
}

int32_t PyramidROIAlign::getNbOutputs() const noexcept
{
    return 1;
}

int32_t PyramidROIAlign::initialize() noexcept
{
    return 0;
}

void PyramidROIAlign::terminate() noexcept {}

void PyramidROIAlign::destroy() noexcept
{
    delete this;
}

size_t PyramidROIAlign::getWorkspaceSize(int) const noexcept
{
    return 0;
}

bool PyramidROIAlign::supportsFormat(DataType type, PluginFormat format) const noexcept
{
    return (type == DataType::kFLOAT && format == PluginFormat::kLINEAR);
}

char const* PyramidROIAlign::getPluginType() const noexcept
{
    return PYRAMIDROIALGIN_PLUGIN_NAME;
}

char const* PyramidROIAlign::getPluginVersion() const noexcept
{
    return PYRAMIDROIALGIN_PLUGIN_VERSION;
}

IPluginV2Ext* PyramidROIAlign::clone() const noexcept
{
    try
    {
        auto plugin = new PyramidROIAlign(*this);
        plugin->setPluginNamespace(mNameSpace.c_str());
        return plugin;
    }
    catch (std::exception const& e)
    {
        caughtError(e);
    }
    return nullptr;
}

void PyramidROIAlign::setPluginNamespace(char const* libNamespace) noexcept
{
    mNameSpace = libNamespace;
}

char const* PyramidROIAlign::getPluginNamespace() const noexcept
{
    return mNameSpace.c_str();
}

void PyramidROIAlign::check_valid_inputs(nvinfer1::Dims const* inputs, int32_t nbInputDims)
{
    // to be compatible with tensorflow node's input:
    // roi: [N, anchors, 4],
    // feature_map list(4 maps): p2, p3, p4, p5
    PLUGIN_ASSERT(nbInputDims == 1 + mFeatureMapCount);

    nvinfer1::Dims rois = inputs[0];
    PLUGIN_ASSERT(rois.nbDims == 2);
    PLUGIN_ASSERT(rois.d[1] == 4);

    for (int32_t i = 1; i < nbInputDims; ++i)
    {
        nvinfer1::Dims dims = inputs[i];

        // CHW with the same #C
        PLUGIN_ASSERT(dims.nbDims == 3 && dims.d[0] == inputs[i].d[0]);
    }
}

Dims PyramidROIAlign::getOutputDimensions(int32_t index, Dims const* inputs, int32_t nbInputDims) noexcept
{

    check_valid_inputs(inputs, nbInputDims);
    PLUGIN_ASSERT(index == 0);

    nvinfer1::Dims result;
    result.nbDims = 4;

    // mROICount
    result.d[0] = inputs[0].d[0];
    // mFeatureLength
    result.d[1] = inputs[1].d[0];
    // height
    result.d[2] = mPooledSize.y;
    // width
    result.d[3] = mPooledSize.x;

    return result;
}

int32_t PyramidROIAlign::enqueue(
    int32_t batch_size, void const* const* inputs, void* const* outputs, void* workspace, cudaStream_t stream) noexcept

{
    void* const pooled = outputs[0];
    cudaError_t status;

    // Support legacy UFF mode
    if (mIsLegacy)
    {
        // Legacy values
        mTransformCoords = -1;
        mPlusOneCoords = 0;
        mSwapCoords = true;
        mAbsCoords = false;
        mSamplingRatio = 1;
        float const firstThreshold = (224 * 224 * 2.0f / (MaskRCNNConfig::IMAGE_SHAPE.d[1] * MaskRCNNConfig::IMAGE_SHAPE.d[2])) / (4.0 * 4.0f);
        status = roiAlign(stream, batch_size, mImageSize, mFeatureLength, mROICount, firstThreshold,
            mTransformCoords, mAbsCoords, mSwapCoords, mPlusOneCoords, mSamplingRatio, inputs[0], &inputs[1],
            mFeatureSpatialSize, pooled, mPooledSize);
    }
    else
    {
        // As per FPN paper equation 1 (https://arxiv.org/pdf/1612.03144.pdf)
        // the default 224 FPN scale corresponds to the canonical ImageNet size
        // used to define the ROI scale threshold that samples from P4. Because the
        // plugin works with normalized ROI coordinates, the FPN scale must be normalized
        // by the input image size.
        float const scale = static_cast<float>(mFPNScale);
        float const normScale = sqrtf(scale * scale / (mImageSize.y * mImageSize.x));
        // Furthermore, the roiAlign kernel expects a first threshold instead. This is
        // the *area* of an ROI but for one level down, i.e. at the P2->P3 transition.
        float const firstThreshold = normScale * normScale / 4.F;
        status = roiAlign(stream, batch_size, mImageSize, mFeatureLength, mROICount, firstThreshold,
            mTransformCoords, mAbsCoords, mSwapCoords, mPlusOneCoords, mSamplingRatio, inputs[0], &inputs[1],
            mFeatureSpatialSize, pooled, mPooledSize);
    }
    return status;
}

size_t PyramidROIAlign::getSerializationSize() const noexcept
{
    return sizeof(int) * 2 // mPooledSize
        + sizeof(int) * 2  // mImageSize
        + sizeof(int)      // mFeatureLength
        + sizeof(int)      // mROICount
        + sizeof(int)      // mFPNScale
        + sizeof(int)      // mTransformCoords
        + sizeof(bool)     // mAbsCoords
        + sizeof(bool)     // mSwapCoords
        + sizeof(bool)     // mPlusOneCoords
        + sizeof(int)      // mSamplingRatio
        + sizeof(bool)     // mIsLegacy
        + sizeof(int) * 8; // mFeatureSpatialSize
}

void PyramidROIAlign::serialize(void* buffer) const noexcept
{
    char *d = reinterpret_cast<char*>(buffer), *a = d;
    write(d, mPooledSize.y);
    write(d, mPooledSize.x);
    write(d, mImageSize.y);
    write(d, mImageSize.x);
    write(d, mFeatureLength);
    write(d, mROICount);
    write(d, mFPNScale);
    write(d, mTransformCoords);
    write(d, mAbsCoords);
    write(d, mSwapCoords);
    write(d, mPlusOneCoords);
    write(d, mSamplingRatio);
    write(d, mIsLegacy);
    write(d, mFeatureSpatialSize[0].y);
    write(d, mFeatureSpatialSize[0].x);
    write(d, mFeatureSpatialSize[1].y);
    write(d, mFeatureSpatialSize[1].x);
    write(d, mFeatureSpatialSize[2].y);
    write(d, mFeatureSpatialSize[2].x);
    write(d, mFeatureSpatialSize[3].y);
    write(d, mFeatureSpatialSize[3].x);
    PLUGIN_ASSERT(d == a + getSerializationSize());
}

PyramidROIAlign::PyramidROIAlign(void const* data, size_t length)
{
    char const *d = reinterpret_cast<char const*>(data), *a = d;
    mPooledSize = {read<int>(d), read<int>(d)};
    mImageSize = {read<int>(d), read<int>(d)};
    mFeatureLength = read<int>(d);
    mROICount = read<int>(d);
    mFPNScale = read<int>(d);
    mTransformCoords = read<int>(d);
    mAbsCoords = read<bool>(d);
    mSwapCoords = read<bool>(d);
    mPlusOneCoords = read<bool>(d);
    mSamplingRatio = read<int>(d);
    mIsLegacy = read<bool>(d);
    mFeatureSpatialSize[0].y = read<int>(d);
    mFeatureSpatialSize[0].x = read<int>(d);
    mFeatureSpatialSize[1].y = read<int>(d);
    mFeatureSpatialSize[1].x = read<int>(d);
    mFeatureSpatialSize[2].y = read<int>(d);
    mFeatureSpatialSize[2].x = read<int>(d);
    mFeatureSpatialSize[3].y = read<int>(d);
    mFeatureSpatialSize[3].x = read<int>(d);

    PLUGIN_VALIDATE(d == a + length);
}

// Return the DataType of the plugin output at the requested index
DataType PyramidROIAlign::getOutputDataType(
    int32_t index, nvinfer1::DataType const* inputTypes, int32_t nbInputs) const noexcept
{
    // Only DataType::kFLOAT is acceptable by the plugin layer
    return DataType::kFLOAT;
}

// Return true if output tensor is broadcast across a batch.
bool PyramidROIAlign::isOutputBroadcastAcrossBatch(
    int32_t outputIndex, bool const* inputIsBroadcasted, int32_t nbInputs) const noexcept
{
    return false;
}

// Return true if plugin can use input that is broadcast across batch without replication.
bool PyramidROIAlign::canBroadcastInputAcrossBatch(int32_t inputIndex) const noexcept
{
    return false;
}

// Configure the layer with input and output data types.
void PyramidROIAlign::configurePlugin(Dims const* inputDims, int32_t nbInputs, Dims const* outputDims,
    int32_t nbOutputs, DataType const* inputTypes, DataType const* outputTypes, bool const* inputIsBroadcast,
    bool const* outputIsBroadcast, PluginFormat floatFormat, int32_t maxBatchSize) noexcept
{
    PLUGIN_ASSERT(supportsFormat(inputTypes[0], floatFormat));
    check_valid_inputs(inputDims, nbInputs);

    PLUGIN_ASSERT(nbOutputs == 1);
    PLUGIN_ASSERT(nbInputs == 1 + mFeatureMapCount);

    mROICount = inputDims[0].d[0];
    mFeatureLength = inputDims[1].d[0];

    for (size_t layer = 0; layer < mFeatureMapCount; ++layer)
    {
        mFeatureSpatialSize[layer] = {inputDims[layer + 1].d[1], inputDims[layer + 1].d[2]};
    }
}

// Attach the plugin object to an execution context and grant the plugin the access to some context resource.
void PyramidROIAlign::attachToContext(
    cudnnContext* cudnnContext, cublasContext* cublasContext, IGpuAllocator* gpuAllocator) noexcept
{
}

// Detach the plugin object from its execution context.
void PyramidROIAlign::detachFromContext() noexcept {}


text:
/*--------------------------------------------*/
/*	GRAMMAR RULES LIBRARY FOR BABEL MODULES   */
/*                                            */
/*	ECM, 2006                                 */
/*--------------------------------------------*/

/** \file GrammarRules.cpp
 *\brief Implementation of GrammarRules.hpp
 */

#include <cstdio>
#include "GrammarRules.hpp"

/*------------*
 * Rule class *
 *------------*/

Rule::Rule(bool newisOr)
{
	ruleAntecedent = NULL;
	isOr = newisOr;
}

Rule::Rule(const Rule & originRule)
{
	copyRule(originRule);
}

Rule::~Rule()
{
}

Rule & Rule::operator =(const Rule &originRule)
{
	copyRule(originRule);
	return(*this);
}

Rule * Rule::dynamicCopy()
{
	Rule * copiedRule = new Rule(*this); //Replica Object
	return(copiedRule);
}

void Rule::showState()
{
	printf("Rule state:\nAntecedent:\n");
	if(ruleAntecedent != NULL)
	{
		ruleAntecedent->showState();
	}
	else
	{
		printf("The Antecedent is empty.\n");
	}
	Consequents::iterator ConsequentsIter;
	ConsequentsIter = ruleConsequents.begin();
	printf("Consequents:\n");
	while(ConsequentsIter != ruleConsequents.end())
	{
		(*ConsequentsIter)->showState();
		ConsequentsIter++;
	}

	if(isOr)
	{
		printf("OR Rule\n");
	}
	else
	{
		printf("Sequence Rule\n");
	}
}

bool Rule::isOR()
{
	return(isOr);
}

void Rule::setAntecedent(const Antecedent & newAntecedent)
{
	ruleAntecedent = (NonTerminal *)newAntecedent->dynamicCopy();
}

Rule::Antecedent Rule::getAntecedent()
{
	return(ruleAntecedent);
}

bool Rule::addConsequent(Symbol *newConsequent)
{
	try
	{
		ruleConsequents.push_back(newConsequent->dynamicCopy());
		return(true);
	}
	catch(...)
	{
		return(false);
	}
}

unsigned Rule::getNumberOfConsequents()
{
	return((unsigned)ruleConsequents.size());
}

Symbol * Rule::ConsequentAt(unsigned n)
{
	Consequents::iterator ConsequentsIter;
	if((n < 0)||(n>= ruleConsequents.size()))
	{
		return(NULL);
	}
	else
	{
		try
		{
			ConsequentsIter = ruleConsequents.begin();
			for(unsigned i = 1;i <= n;i++)
			{
				ConsequentsIter++;
			}
			return(*ConsequentsIter);
		}
		catch(...)
		{
			return(NULL);
		}
	}

}

void Rule::copyRule(const Rule &originRule)
{
	//Replication of the antecedent
	ruleAntecedent = (NonTerminal*)originRule.ruleAntecedent->dynamicCopy();
	//Replication of the list of Consequent
	Consequents::const_iterator originConsequentsIter; //Iterator of the object being copied
	originConsequentsIter = originRule.ruleConsequents.begin();
	while(originConsequentsIter != originRule.ruleConsequents.end())
	{
		ruleConsequents.push_back((*originConsequentsIter)->dynamicCopy());
		originConsequentsIter++;
	}
	isOr = originRule.isOr;
}
/* end Rule class*/


text:
import { Typography } from '@mui/material';
import { ConditionallyRender } from 'component/common/ConditionallyRender/ConditionallyRender';
import classnames from 'classnames';
import CheckIcon from '@mui/icons-material/Check';

import { useStyles } from './PasswordMatcher.styles';

interface IPasswordMatcherProps {
    started: boolean;
    matchingPasswords: boolean;
}

const PasswordMatcher = ({
    started,
    matchingPasswords,
}: IPasswordMatcherProps) => {
    const { classes: styles } = useStyles();
    return (
        <div className={styles.matcherContainer}>
            <ConditionallyRender
                condition={started}
                show={
                    <ConditionallyRender
                        condition={matchingPasswords}
                        show={
                            <Typography
                                variant="body2"
                                data-loading
                                className={classnames(styles.matcher, {
                                    [styles.matcherSuccess]: matchingPasswords,
                                })}
                            >
                                <CheckIcon className={styles.matcherIcon} />{' '}
                                Passwords match
                            </Typography>
                        }
                        elseShow={
                            <Typography
                                variant="body2"
                                data-loading
                                className={classnames(styles.matcher, {
                                    [styles.matcherError]: !matchingPasswords,
                                })}
                            >
                                Passwords do not match
                            </Typography>
                        }
                    />
                }
            />
        </div>
    );
};

export default PasswordMatcher;


text:
<?php

namespace SerendipityHQ\Component\ValueObjects\Ip;

use Darsyn\IP\Exception\InvalidIpAddressException;
use Darsyn\IP\Exception\IpException;
use Darsyn\IP\Exception\WrongVersionException;
use Darsyn\IP\Version\IPv4;
use SerendipityHQ\Component\ValueObjects\Common\DisableWritingMethodsTrait;

/**
 * {@inheritdoc}
 */
final class Ip implements IpInterface
{
    use DisableWritingMethodsTrait;

    /** @var IPv4 $valueObject */
    private $valueObject;

    /**
     * {@inheritdoc}
     *
     * @throws InvalidIpAddressException
     * @throws WrongVersionException
     * @psalm-suppress MixedArgument
     */
    public function __construct($value)
    {
        $this->valueObject = IPv4::factory($value);
    }

    /**
     * {@inheritdoc}
     *
     * @throws IpException
     * @throws WrongVersionException
     */
    public function toString(array $options = []): string
    {
        return $this->__toString();
    }

    /**
     * @throws IpException
     * @throws WrongVersionException
     *
     * @return string
     */
    public function __toString()
    {
        return $this->valueObject->getDotAddress();
    }
}


text:
'use strict'

var errors = require('./errors')
  , fs = require('fs')
  , path = require('path')
  , FieldError = errors.FieldError
  , FieldTypeError = errors.FieldTypeError
  , slice = Array.prototype.slice
  , undefined

var FIELD_SETTERS = {
  boolean: function(value) {
    return !!((value||false).valueOf())
  },

  object: function(value) {
    if (typeof value !== 'object') {
      throw new FieldTypeError(this + '', 'object')
    }

    return value
  },

  number: function(value) {
    var num = value
    if (typeof num !== 'number') {
      num = parseFloat(num) || parseInt(num, 10)
    }

    if (isNaN(num)) {
      return FieldTypeError(this + '', 'number', value)
    }

    return num
  },

  string: function(value) {
    if (typeof value !== 'string') {
      value = value + ''
    }

    return value
  },

  array: function(value) {
    if (!Array.isArray(value)) {
      value = exports.args(arguments, 0)
    }

    return value
  }
}

/**
 * Arguments object to array
 *
 * @param {Arguments} args
 * @param {number} [num=0] Array#slice start index
 * @returns {Array}
 */
exports.args = function(args, num) {
  if (arguments.length === 1) {
    num = 0
  }

  return slice.call(args, num)
}

/**
 * Parse date
 *
 * @param {string|number|Date} value
 * @throws {FieldError} Throws error if bad value specified
 * @returns {Date}
 */
exports.date = function(value) {
  if (value == null) {
    return undefined
  }
  else if (value instanceof Date) {
    return value
  }

  if (~['number', 'string'].indexOf(typeof value)) {
    value = new Date(value)
  }

  if (!(value instanceof Date)) {
    throw new FieldError('Bad date value: ' + value)
  }

  return value
}

/**
 * Get needed setter
 *
 * @param {string} field Query field name
 * @param {string} setter Setter name
 */
exports.fieldSetter = function(field, setter) {
  var setterFn = FIELD_SETTERS[setter]
  return setterFn.bind(field)
}

/**
 * Check if value is object and not null
 *
 * @param {*} value Value to check
 * @returns {boolean}
 */
exports.isObject = function(value) {
  return value && typeof value === 'object'
}

/**
 * Load modules from folder and map them to object by filenames.
 *
 * @param {string} dir
 * @returns {Object}
 */
exports.moduleMap = function(dir) {
  var map = {}
  fs.readdirSync(dir).forEach(mapFn)
  function mapFn(filename) {
    if (filename === 'index.js') {
      return
    }

    var modulePath = path.basename(filename, '.js')
    map[modulePath] = require(path.join(dir, filename))
  }

  return map
}


text:
angular.module('adminHomeApp')
    .directive('adminInfoLogin', [function () {
        return {
            templateUrl: 'views/admin/login_partials/forms/admin_info_login.html',
            restrict: 'AEC',
            link: function ($scope, $element, $attrs) {
            }
        }
    }])
    .directive('adminHomeTopNav', [function () {
        return {
            templateUrl: 'views/admin/login_partials/navs/admin_home_top_nav.html',
            restrict: 'AEC',
            link: function ($scope, $element, $attrs) {
            }
        }
    }])
    .directive('grillsEdit', [function () {
        return {
            templateUrl: 'views/admin/login_partials/sections/grill_edit.html',
            restrict: 'AEC',
            link: function ($scope, $element, $attrs) {
            }
        }
    }])
    .directive('completeRegistration', [function () {
        return {
            templateUrl: 'views/admin/login_partials/forms/registration.html',
            restrict: 'AEC',
            link: function ($scope, $element, $attrs) {
            }
        }
    }]);


text:
NSString *const THThumbnailCreatedNotification = @"THThumbnailCreated";

@interface THCameraController () <AVCaptureFileOutputRecordingDelegate>

@property (strong, nonatomic) dispatch_queue_t videoQueue;
@property (strong, nonatomic) AVCaptureSession *captureSession;
@property (weak, nonatomic) AVCaptureDeviceInput *activeVideoInput;
@property (strong, nonatomic) AVCaptureStillImageOutput *imageOutput;
@property (strong, nonatomic) AVCaptureMovieFileOutput *movieOutput;
@property (strong, nonatomic) NSURL *outputURL;

@end

@implementation THCameraController

- (BOOL)setupSession:(NSError **)error {

    // Listing 6.4
    self.captureSession = [[AVCaptureSession alloc] init];
    self.captureSession.sessionPreset = AVCaptureSessionPresetHigh;

    // Set up the default video input
    AVCaptureDevice* videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput* cameraDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:error];
    if (cameraDeviceInput) {
        if ([self.captureSession canAddInput:cameraDeviceInput]) {
            [self.captureSession addInput:cameraDeviceInput];
            self.activeVideoInput = cameraDeviceInput;
        }
    }else {
        return NO;
    }

    // Set up the default audio
    AVCaptureDevice* audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
    AVCaptureDeviceInput* audioDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:error];
    if (audioDeviceInput) {
        if ([self.captureSession canAddInput:audioDeviceInput]) {
            [self.captureSession addInput:audioDeviceInput];
        }
    } else {
        return NO;
    }

    // Set up the still image output
    self.imageOutput = [[AVCaptureStillImageOutput alloc] init];
    self.imageOutput.outputSettings = @{AVVideoCodecKey:AVVideoCodecJPEG};
    if ([self.captureSession canAddOutput:self.imageOutput]) {
        [self.captureSession addOutput:self.imageOutput];
    }

    // Set up the movie output
    self.movieOutput = [[AVCaptureMovieFileOutput alloc] init];
    if ([self.captureSession canAddOutput:self.movieOutput]) {
        [self.captureSession addOutput:self.movieOutput];
    }

    self.videoQueue = dispatch_queue_create("vn.snapbuck.SnapbuckMobile", NULL);
    return YES;
}

- (void)startSession {

    // Listing 6.5
    if (![self.captureSession isRunning]) {
        dispatch_async(self.videoQueue, ^{
            [self.captureSession startRunning];
        });
    }
}

- (void)stopSession {

    // Listing 6.5
    if ([self.captureSession isRunning]) {
        dispatch_async(self.videoQueue, ^{
            [self.captureSession stopRunning];
        });
    }
}

#pragma mark - Device Configuration

- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position {

    // Listing 6.6
    NSArray* allDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice* device in allDevices) {
        if (device.position == position) {
            return device;
        }
    }
    return nil;
}

- (AVCaptureDevice *)activeCamera {

    // Listing 6.6

    return [self.activeVideoInput device];
}

- (AVCaptureDevice *)inactiveCamera {

    // Listing 6.6
    AVCaptureDevice* inactiveDevice = nil;
    if (self.cameraCount > 1) {
        AVCaptureDevicePosition activePostion = [self.activeVideoInput.device position];
        if (activePostion == AVCaptureDevicePositionBack) {
            inactiveDevice = [self cameraWithPosition:AVCaptureDevicePositionFront];
        } else if (activePostion == AVCaptureDevicePositionFront){
            inactiveDevice = [self cameraWithPosition:AVCaptureDevicePositionBack];
        }
    }
    return inactiveDevice;
}

- (BOOL)canSwitchCameras {

    // Listing 6.6

    return (self.cameraCount > 1);
}

- (NSUInteger)cameraCount {

    // Listing 6.6

    return [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
}

- (BOOL)switchCameras {

    // Listing 6.7
    if ([self canSwitchCameras] == NO) {
        return NO;
    }

    AVCaptureDevice* deviceToSwitchTo = [self inactiveCamera];
    NSError* error = nil;
    AVCaptureDeviceInput* inputToSwitchTo = [AVCaptureDeviceInput deviceInputWithDevice:deviceToSwitchTo error:&error];
    if (inputToSwitchTo != nil) {
        [self.captureSession beginConfiguration];
        [self.captureSession removeInput:self.activeVideoInput];

        if ([self.captureSession canAddInput:inputToSwitchTo]) {
            [self.captureSession addInput:inputToSwitchTo];
            self.activeVideoInput = inputToSwitchTo;
        }else {
            [self.captureSession addInput:self.activeVideoInput];
        }
        [self.captureSession commitConfiguration];
    } else {
        [self.delegate deviceConfigurationFailedWithError:error];
        return NO;
    }

    return YES;
}

#pragma mark - Focus Methods

- (BOOL)cameraSupportsTapToFocus {

    // Listing 6.8

    return [[self activeCamera] isFocusPointOfInterestSupported];
}

- (void)focusAtPoint:(CGPoint)point {

    // Listing 6.8
    AVCaptureDevice* activeDevice = [self activeCamera];
    if ([activeDevice isFocusPointOfInterestSupported] && [activeDevice isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
        NSError* error = nil;
        if ([activeDevice lockForConfiguration:&error]) {
            [activeDevice setFocusMode:AVCaptureFocusModeAutoFocus];
            [activeDevice setFocusPointOfInterest:point];
            [activeDevice unlockForConfiguration];
        } else {
            [self.delegate deviceConfigurationFailedWithError:error];
        }

    }

}

#pragma mark - Exposure Methods

- (BOOL)cameraSupportsTapToExpose {

    // Listing 6.9

    return [[self activeCamera] isExposurePointOfInterestSupported];
}

static const NSString* THCameraAdjustingExposureContext;
- (void)exposeAtPoint:(CGPoint)point {

    // Listing 6.9
    AVCaptureDevice* activeCameraDevice = [self activeCamera];
    AVCaptureExposureMode exposureMode = AVCaptureExposureModeAutoExpose;
    if ([activeCameraDevice isExposurePointOfInterestSupported] && [activeCameraDevice isExposureModeSupported:exposureMode]) {
        NSError* error = nil;
        if ([activeCameraDevice lockForConfiguration:&error]) {
            [activeCameraDevice setExposureMode:exposureMode];
            [activeCameraDevice setExposurePointOfInterest:point];

            if ([activeCameraDevice isExposureModeSupported:AVCaptureExposureModeLocked]) {
                [activeCameraDevice addObserver:self
                                     forKeyPath:@"adjustingExposure"
                                        options:NSKeyValueObservingOptionNew
                                        context:&THCameraAdjustingExposureContext];
            }
            [activeCameraDevice unlockForConfiguration];
        }else {
            [self.delegate deviceConfigurationFailedWithError:error];
        }
    }

}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {

    // Listing 6.9
    if (context == &THCameraAdjustingExposureContext) {
        AVCaptureDevice* cameraDevice = (AVCaptureDevice*)object;
        if ([cameraDevice isExposureModeSupported:AVCaptureExposureModeLocked]) {
            [object removeObserver:self
                        forKeyPath:@"adjustingExposure"
                           context:&THCameraAdjustingExposureContext];
            dispatch_async(dispatch_get_main_queue(), ^{
                NSError* error = nil;
                if ([cameraDevice lockForConfiguration:&error]) {
                    [cameraDevice setExposureMode:AVCaptureExposureModeLocked];
                    [cameraDevice unlockForConfiguration];
                } else{
                    [self.delegate deviceConfigurationFailedWithError:error];
                }
            });
        }
    }else {
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                               change:change
                              context:context];
    }

}

- (void)resetFocusAndExposureModes {

    // Listing 6.10
    AVCaptureDevice* cameraDevice = [self activeCamera];
    AVCaptureExposureMode exposureMode = AVCaptureExposureModeContinuousAutoExposure;
    AVCaptureFocusMode focusMode = AVCaptureFocusModeContinuousAutoFocus;
    BOOL canResetExposure = [cameraDevice isExposurePointOfInterestSupported] && [cameraDevice isExposureModeSupported:exposureMode];
    BOOL canResetFocus = [cameraDevice isFocusPointOfInterestSupported] && [cameraDevice isFocusModeSupported:focusMode];

    NSError* error = nil;
    if ([cameraDevice lockForConfiguration:&error]){
        CGPoint centerPoint = CGPointMake(.5, .5);

        if (canResetExposure) {
            [cameraDevice setExposureMode:exposureMode];
            [cameraDevice setExposurePointOfInterest:centerPoint];
        }

        if (canResetFocus) {
            [cameraDevice setFocusMode:focusMode];
            [cameraDevice setFocusPointOfInterest:centerPoint];
        }

        [cameraDevice unlockForConfiguration];
    }else{
        [self.delegate deviceConfigurationFailedWithError:error];
    }

}

#pragma mark - Flash and Torch Modes

- (BOOL)cameraHasFlash {

    // Listing 6.11

    return [[self activeCamera] hasFlash];
}

- (AVCaptureFlashMode)flashMode {

    // Listing 6.11

    return [[self activeCamera] flashMode];
}

- (void)setFlashMode:(AVCaptureFlashMode)flashMode {

    // Listing 6.11
    AVCaptureDevice* activeCameraDevice = [self activeCamera];
    NSError* error = nil;
    if ([activeCameraDevice lockForConfiguration:&error]) {
        if ([activeCameraDevice hasFlash] && [activeCameraDevice isFlashModeSupported:flashMode]) {
            [activeCameraDevice setFlashMode:flashMode];
        }
        [activeCameraDevice unlockForConfiguration];
    } else {
        [self.delegate deviceConfigurationFailedWithError:error];
    }

}

- (BOOL)cameraHasTorch {

    // Listing 6.11

    return [[self activeCamera] hasTorch];
}

- (AVCaptureTorchMode)torchMode {

    // Listing 6.11

    return [[self activeCamera] torchMode];
}

- (void)setTorchMode:(AVCaptureTorchMode)torchMode {

    // Listing 6.11
    AVCaptureDevice* activeCamera = [self activeCamera];
    if ([activeCamera hasTorch] && [activeCamera isTorchModeSupported:torchMode]) {
        NSError* error = nil;
        if ([activeCamera lockForConfiguration:&error]) {
            [activeCamera setTorchMode:torchMode];
            [activeCamera unlockForConfiguration];
        } else {
            [self.delegate deviceConfigurationFailedWithError:error];
        }
    }
}

#pragma mark - Image Capture Methods

- (void)captureStillImage {

    // Listing 6.12
    AVCaptureConnection* videoConnection = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];
    if ([videoConnection isVideoOrientationSupported]) {
        [videoConnection setVideoOrientation:[self currentVideoOrientation]];
    }
    [self.imageOutput captureStillImageAsynchronouslyFromConnection:videoConnection
                                                  completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
                                                      if (imageDataSampleBuffer != NULL) {
                                                          NSData* imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
                                                          UIImage* image = [UIImage imageWithData:imageData];
                                                          [self writeImageToAssetsLibrary:image];
                                                      } else {
                                                          NSLog(@"Error: %@", [error localizedDescription]);
                                                      }

                                                  }];

}

- (AVCaptureVideoOrientation)currentVideoOrientation {

    // Listing 6.12
    AVCaptureVideoOrientation videoOrientation;
    // Listing 6.13
    switch ([[UIDevice currentDevice] orientation]) {
        case UIDeviceOrientationPortrait:
            videoOrientation = AVCaptureVideoOrientationPortrait;
            break;
        case UIDeviceOrientationPortraitUpsideDown:
            videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
            break;
        case UIDeviceOrientationLandscapeLeft:
            videoOrientation = AVCaptureVideoOrientationLandscapeRight;
            break;
        default:
            videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
            break;
    }
    return videoOrientation;
}

- (void)writeImageToAssetsLibrary:(UIImage *)image {

    // Listing 6.13
    ALAssetsLibrary* al = [[ALAssetsLibrary alloc] init];
    [al writeImageToSavedPhotosAlbum:image.CGImage
                         orientation:(NSUInteger)image.imageOrientation
                     completionBlock:^(NSURL *assetURL, NSError *error) {
                         if (error != nil) {
                             [self postThumbnailNotifification:image];
                         } else {
                             NSString* errorDescription = [error localizedDescription];
                             NSLog(@"Error occured when saving the image: %@", errorDescription);
                         }
                     }];
}

- (void)postThumbnailNotifification:(UIImage *)image {

    // Listing 6.13
    NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
    [nc postNotificationName:THThumbnailCreatedNotification object:image];

}

#pragma mark - Video Capture Methods

- (BOOL)isRecording {

    // Listing 6.14

    return [self.movieOutput isRecording];
}

- (void)startRecording {

    // Listing 6.14
    if([self isRecording] == NO){
        AVCaptureConnection* captureConnection = [self.movieOutput connectionWithMediaType:AVMediaTypeVideo];
        if ([captureConnection isVideoOrientationSupported]) {
            [captureConnection setVideoOrientation:[self currentVideoOrientation]];
        }
        if ([captureConnection isVideoStabilizationSupported]) {
            [captureConnection setEnablesVideoStabilizationWhenAvailable:YES];
        }
        AVCaptureDevice* cameraDevice = [self activeCamera];
        if ([cameraDevice isSmoothAutoFocusSupported]) {
            NSError* error = nil;
            if ([cameraDevice lockForConfiguration:&error]) {
                [cameraDevice setSmoothAutoFocusEnabled:YES];
                [cameraDevice unlockForConfiguration];
            } else {
                [self.delegate deviceConfigurationFailedWithError:error];
            }
        }
        self.outputURL = [self uniqueURL];
        [self.movieOutput startRecordingToOutputFileURL:self.outputURL
                                      recordingDelegate:self];
    }

}

- (CMTime)recordedDuration {
    return self.movieOutput.recordedDuration;
}

- (NSURL *)uniqueURL {

    // Listing 6.14
    NSFileManager* fileManager = [NSFileManager defaultManager];
    NSString* dirPath = [fileManager temporaryDirectoryWithTemplateString:@"kamera.XXXXXX"];
    if (dirPath) {
        NSString* filePath = [dirPath stringByAppendingPathComponent:@"kamera_movie.mov"];
        return [NSURL fileURLWithPath:filePath];
    }
    return nil;
}

- (void)stopRecording {

    // Listing 6.14
    if ([self.movieOutput isRecording]) {
        [self.movieOutput stopRecording];
    }
}

#pragma mark - AVCaptureFileOutputRecordingDelegate

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
      fromConnections:(NSArray *)connections
                error:(NSError *)error {

    // Listing 6.15
    if (error == nil) {
        [self writeVideoToAssetsLibrary:[self.outputURL copy]];
    } else {
        [self.delegate mediaCaptureFailedWithError:error];
    }
    self.outputURL = nil;
}

- (void)writeVideoToAssetsLibrary:(NSURL *)videoURL {

    // Listing 6.15
    ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];
    if ([assetsLibrary videoAtPathIsCompatibleWithSavedPhotosAlbum:videoURL]) {
        [assetsLibrary writeVideoAtPathToSavedPhotosAlbum:videoURL
                                          completionBlock:^(NSURL *assetURL, NSError *error) {
                                              if (error == nil) {
                                                  [self generateThumbnailForVideoAtURL:videoURL];
                                              }else{
                                                  [self.delegate assetLibraryWriteFailedWithError:error];
                                              }
                                          }];
    }
}

- (void)generateThumbnailForVideoAtURL:(NSURL *)videoURL {

    // Listing 6.15
    dispatch_async(self.videoQueue, ^{
        AVAsset* asset = [AVAsset assetWithURL:videoURL];
        AVAssetImageGenerator* imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
        imageGenerator.maximumSize = CGSizeMake(100.0f, 0);
        imageGenerator.appliesPreferredTrackTransform = YES;
        CGImageRef imageRef = [imageGenerator copyCGImageAtTime:kCMTimeZero actualTime:NULL error:nil];
        UIImage* image = [UIImage imageWithCGImage:imageRef];
        CFRelease(imageRef);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self postThumbnailNotifification:image];
        });
    });

}

@end


text:
#ifndef maciContainerServicesTestClassImpl_h
#define maciContainerServicesTestClassImpl_h

/*******************************************************************************
* E.S.O. - ACS project
*
* "@(#) $Id: maciContainerServicesTestClassImpl.h,v 1.16 2008/10/09 07:05:37 cparedes Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* acaproni   2005-02-28 created
*/

/************************************************************************
 *
 *----------------------------------------------------------------------
 */

#ifndef __cplusplus
#error This is a C++ include file and cannot be used from plain C
#endif

#include <acsutil.h>
#include <acscomponentImpl.h>
#include <acsContainerServices.h>
#include <maciTestS.h>
#include <string>

// The IDL of the dynamic components
#define IDLTYPE "IDL:alma/MACI_TEST/DynamicTestClass:1.0"
// The name of 2 remote components to get
# define COMPNAME "MACI_DYN_TEST1"
# define COMPNAME2 "MACI_DYN_TEST2"

class MaciContainerServicesTestClassImpl: public virtual acscomponent::ACSComponentImpl,
                     public virtual POA_MACI_TEST::ContainerServicesTestClass
{

public:

  /// Constructors
  MaciContainerServicesTestClassImpl(
    const ACE_CString& name,
    maci::ContainerServices* containerServices);

  /**
   * Destructor
   */
  virtual ~MaciContainerServicesTestClassImpl();

  /**
    * LifeCycle
    * @throw acsErrTypeLifeCycle::LifeCycleExImpl
    */
  virtual void initialize();

    /**
     * LifeCycle
     * @throw acsErrTypeLifeCycle::LifeCycleExImpl
     */
    virtual void execute();

    /**
     * LifeCycle
     */
    virtual void cleanUp();

    /**
     * LifeCycle
     */
    virtual void aboutToAbort();

  /* ----------------------------------------------------------------*/
  /* --------------------- [ CORBA interface ] ----------------------*/
  /* ----------------------------------------------------------------*/

  // Test the defaultComponent activation
  virtual void getComponentTest() ;

  // Test the getting a Component as Non Sticky
  virtual void getComponentNonStickyTest() ;

  // Test the dynamic component activation
  virtual void dynamicComponentTest();

  // Test the collocated component activation
  virtual void collocatedComponentTest();

  // Test the defaultComponent activation
  virtual void defaultComponentTest();

  // Test the defaultComponentSmartPtr activation
  virtual void getComponentSmartPtrTest();

  // Test the getting a Component smart pointer as Non Sticky
  virtual void getComponentNonStickySmartPtrTest();

  // Test the dynamic component smart pointer activation
  virtual void dynamicComponentSmartPtrTest();

  // Test the collocated component smart pointer activation
  virtual void collocatedComponentSmartPtrTest();

  // Test the defaultComponent smart pointer activation
  virtual void defaultComponentSmartPtrTest();

  // Test the request of a component descriptor
  virtual void componentDescriptorTest();

  // Test the relase of all components
  virtual void releaseResourcesTest();

  // Test the component listener
  virtual void componentListenerTest();

};

#endif   /* maciContainerServicesTestClassImpl_h */