text:
#include "renderer/CCPrimitive.h"
#include "renderer/CCVertexIndexBuffer.h"

NS_CC_BEGIN

Primitive* Primitive::create(VertexData* verts, IndexBuffer* indices, int type)
{
    auto result = new (std::nothrow) Primitive();
    if( result && result->init(verts, indices, type))
    {
        result->autorelease();
        return result;
    }

    CC_SAFE_DELETE(result);
    return  nullptr;
}

const VertexData* Primitive::getVertexData() const
{
    return _verts;
}

const IndexBuffer* Primitive::getIndexData() const
{
    return _indices;
}

Primitive::Primitive()
: _verts(nullptr)
, _indices(nullptr)
, _type(GL_POINTS)
, _start(0)
, _count(0)
{
}

Primitive::~Primitive()
{
    CC_SAFE_RELEASE_NULL(_verts);
    CC_SAFE_RELEASE_NULL(_indices);
}

bool Primitive::init(VertexData* verts, IndexBuffer* indices, int type)
{
    if( nullptr == verts ) return false;
    if(verts != _verts)
    {
        CC_SAFE_RELEASE(_verts);
        CC_SAFE_RETAIN(verts);
        _verts = verts;
    }

    if(indices != _indices)
    {
        CC_SAFE_RETAIN(indices);
        CC_SAFE_RELEASE(_indices);
        _indices = indices;
    }

    _type = type;

    return true;
}

void Primitive::draw()
{
    if(_verts)
    {
        _verts->use();
        if(_indices!= nullptr)
        {
            GLenum type = (_indices->getType() == IndexBuffer::IndexType::INDEX_TYPE_SHORT_16) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indices->getVBO());
            size_t offset = _start * _indices->getSizePerIndex();
            glDrawElements((GLenum)_type, _count, type, (GLvoid*)offset);
        }
        else
        {
            glDrawArrays((GLenum)_type, _start, _count);
        }

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
    }
}

void Primitive::setStart(int start)
{
    _start = start;
}

void Primitive::setCount(int count)
{
    _count = count;
}

NS_CC_END


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Bull. Soc. Imp. Naturalistes Moscou 15:179. 1842

#### Original name
null

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<title>Attester</title>
	<link rel="stylesheet" type="text/css" href="./app.css">
	<meta name="viewport" content="width=device-width, initial-scale=1">

Attester results

		<button class="pull-right btn btn-default btn-xs"
			ng-class="{active: mainCtrl.configVisible}"
			ng-click="mainCtrl.configVisible = !mainCtrl.configVisible">

		</button>

Configuration

					<form class="form-horizontal" role="form" novalidate>

							Test URL

								<input type="url" class="form-control input-sm"
									ng-model="mainCtrl.config.testURL"
									title="String to prepend to the name of the test to build the test URLs.">

							Execution chooser

								<select class="form-control input-sm" ng-model="mainCtrl.executionChooser" ng-model-options="{ getterSetter: true }">
									<option value="lastNonWaiting">Last non-waiting</option>
									<option value="last">Last</option>
									<option value="first">First</option>
								</select>

					</form>

		<uib-tabset ng-if="mainCtrl.config"> <uib-tab
			ng-repeat="source in campaignsManager.sources" active="source.active">
		<uib-tab-heading> <item-box
				drag-source="campaignsManager.getDragSourceFromCampaignSource(source)"
				ng-style="{'background-color':campaignsManager.getCampaignColor(source.campaign)}"
				label="source.campaign.campaignId"></item-box>  {{ source.error ? 'Error
			!' : 'Loading...' }}
		<button type="button" class="close"
			ng-click="campaignsManager.removeSource($index); $event.preventDefault();">
			×
		</button>
		</uib-tab-heading>

		<button ng-if="source.campaign && source.campaign.campaignId"
			class="pull-right btn btn-default btn-xs"
			ng-click="mainCtrl.saveLogs(source.campaign)"
			title="Save this campaign's results">

		</button>

Attester server URL

					{{source.serverURL}},

					{{source.connected ? 'connected': 'not connected'}}

Attester report URL

{{source.reportURL}}

Attester report file

{{source.file}}

			 Loading...

		<uib-alert ng-if="source.error" type="danger">{{source.error}}</uib-alert>

Campaign id

{{source.campaign.campaignId}}

Last update

{{source.campaign.lastUpdate | date: "medium" }} ({{source.campaign.events.length}} events)

		<uib-alert ng-if="source.campaign.mergeInfo" type="info">  This file is the result
		of a merge operation.
		<button type="button" class="btn btn-link"
			ng-click="source.displayMergeInfo = !source.displayMergeInfo">{{
			source.displayMergeInfo ? "Hide" :"Show" }} details.</button>

			<merge-campaigns-config-display config="source.campaign.mergeInfo"></merge-campaigns-config-display>

		</uib-alert>

			Loading {{source.resultsReceived}} / {{source.resultsTotal}}

			<uib-progressbar
				value="(1000 * source.resultsReceived / source.resultsTotal)"
				max="1000" animate="false"></uib-progressbar>

			<tasks-table browsers-array="source.campaign.browsersArray"
				browsers-map="source.campaign.browsersMap"
				tasks-groups="source.campaign.tasksGroups"
				state="source.state"
				test-url="mainCtrl.config.testURL"></tasks-table>
			<running-slaves-info source="source"></running-slaves-info>

</uib-tab> <uib-tab ng-repeat="comparator in mainCtrl.comparators"
			active="comparator.active"> <uib-tab-heading>Comparison
		{{$index+1}}
		<button type="button" class="close"
			ng-click="mainCtrl.removeComparator($index); $event.preventDefault();">
			×
		</button>
		</uib-tab-heading>

		<tasks-table browsers-array="comparator.browsersArray"
			browsers-map="comparator.browsersMap"
			tasks-groups="comparator.tasksGroups"
			state="comparator.state"
			test-url="mainCtrl.config.testURL"></tasks-table>
</uib-tab> <uib-tab
			active="campaignsManager.addCampaignsTabActive"> <uib-tab-heading
			drag-target="campaignsManager.drop($event.dragSource)"
			drag-target-enter="campaignsManager.addCampaignsTabActive = true">
		</uib-tab-heading>

		<campaign-chooser server-url="mainCtrl.config.serverURL"
			server-urls="mainCtrl.config.serverURLs"
			report-url="mainCtrl.config.reportURL"
			report-urls="mainCtrl.config.reportURLs"></campaign-chooser> <merge-campaigns-config
			on-select="campaignsManager.addSource($source)"></merge-campaigns-config>
		<compare-campaigns-selector
			on-select="mainCtrl.addComparator($comparator)"
			campaigns="campaignsManager.getLoadedCampaigns()"></compare-campaigns-selector>

		</uib-tab> </uib-tabset>


text:
namespace YAF.Controls {

    public partial class DialogBox {

        /// <summary>
        /// YafForumPageErrorPopup control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel YafForumPageErrorPopup;

        /// <summary>
        /// Header control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Header;

        /// <summary>
        /// ImageIcon control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Image ImageIcon;

        /// <summary>
        /// MessageText control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Literal MessageText;

        /// <summary>
        /// OkButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button OkButton;

        /// <summary>
        /// CancelButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button CancelButton;
    }
}


text:
<?php
class AES256
{
	public static function encrypt($string, $key = null, $salt = null, $iv = null){
		$config = ConfigManager::getConfig('Crypto','AES256')->AuxConfig;
		if($key === null){
			$key = $config->key;
		}
		if($salt === null){
			$salt = $config->salt;
		}
		if($iv === null){
			$iv = $config->iv;
		}

		$td = mcrypt_module_open('rijndael-128', '', MCRYPT_MODE_CBC, '');

		$ks = mcrypt_enc_get_key_size($td);
		$bs = mcrypt_enc_get_block_size($td);

		$iv = substr(hash("sha256", $iv), 0, $bs);

		// Create key
		$key = Crypto::pbkdf2("sha512", $key, $salt, $config->pbkdfRounds, $ks);

		// Intialize encryption
		mcrypt_generic_init($td, $key, $iv);

		// Encrypt data
		$encryptedString = bin2hex(mcrypt_generic($td, $string));

		// Terminate encryption handler
		mcrypt_generic_deinit($td);
		mcrypt_module_close($td);

		return $encryptedString;
	}

	public static function decrypt($string, $key = null, $salt = null, $iv = null){
		$config = ConfigManager::getConfig('Crypto','AES256')->AuxConfig;
		if($key === null){
			$key = $config->key;
		}
		if($salt === null){
			$salt = $config->salt;
		}
		if($iv === null){
			$iv = $config->iv;
		}

		$td = mcrypt_module_open('rijndael-128', '', MCRYPT_MODE_CBC, '');

		$ks = mcrypt_enc_get_key_size($td);
		$bs = mcrypt_enc_get_block_size($td);

		$iv = substr(hash("sha256", $iv), 0, $bs);

		// Create key
		$key = Crypto::pbkdf2("sha512", $key, $salt, $config->pbkdfRounds, $ks);

		// Initialize encryption module for decryption
		mcrypt_generic_init($td, $key, $iv);

		$decryptedString = "";
		// Decrypt encrypted string
		try{
			if(ctype_xdigit($string)){
				$decryptedString = trim(mdecrypt_generic($td, pack("H*", $string)));
			}
		}
		catch(ErrorException $e){ }

		// Terminate decryption handle and close module
		mcrypt_generic_deinit($td);
		mcrypt_module_close($td);

		// Show string
		return $decryptedString;
	}
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.krminc.phr.api.service.clinical;

import com.krminc.phr.api.converter.clinical.CcrResultConverter;
import com.krminc.phr.api.service.Api;
import com.krminc.phr.dao.PersistenceService;
import com.krminc.phr.domain.clinical.CcrResult;
import com.krminc.phr.domain.clinical.CcrResultTest;
import java.util.Collection;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import com.sun.jersey.api.core.ResourceContext;
import javax.ws.rs.WebApplicationException;
import javax.persistence.NoResultException;
import javax.persistence.EntityManager;

/**
 *
 * @author cmccall
 */

public class CcrResultResource {
    @Context
    protected UriInfo uriInfo;
    @Context
    protected ResourceContext resourceContext;
    protected Long id;

    /** Creates a new instance of CcrResultResource */
    public CcrResultResource() {
    }

    public void setId(Long id) {
        this.id = id;
    }

    /**
     * Get method for retrieving an instance of CcrResult identified by id in XML format.
     *
     * @param id identifier for the entity
     * @return an instance of CcrResultConverter
     */
    @GET
    @Produces({"application/xml", "application/json"})
    public CcrResultConverter get() {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            return new CcrResultConverter(getEntity(), uriInfo.getAbsolutePath(), Api.DEFAULT_EXPAND_LEVEL);
        } finally {
            PersistenceService.getInstance().close();
        }
    }

    /**
     * Returns an instance of CcrResult identified by id.
     *
     * @param id identifier for the entity
     * @return an instance of CcrResult
     */
    protected CcrResult getEntity() {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        try {
            return (CcrResult) em.createQuery("SELECT e FROM CcrResult e where e.id = :id").setParameter("id", id).getSingleResult();
        } catch (NoResultException ex) {
            throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
        }
    }

    /**
     * Returns a dynamic instance of CcrResultTestsResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of CcrResultTestsResource
     */
    @Path("resultTests/")
    public CcrResultTestsResource getResultTestsResource() {
        ResultTestsResourceSub resource = resourceContext.getResource(ResultTestsResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    public static class ResultTestsResourceSub extends CcrResultTestsResource {

        private CcrResult parent;

        public void setParent(CcrResult parent) {
            this.parent = parent;
        }

        protected Collection<CcrResultTest> getEntities(int start, int max, String query) {
            Collection<CcrResultTest> result = new java.util.ArrayList<CcrResultTest>();
            int index = 0;
            for (CcrResultTest e : parent.getResultTests()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }
}


text:
#include <png.h>

#include <utility>

#include "GetUSBCamera.h"

namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace processors {

core::Property GetUSBCamera::FPS(  // NOLINT
    "FPS", "Frames per second to capture from USB camera", "1");
core::Property GetUSBCamera::Width(  // NOLINT
    "Width", "Target width of image to capture from USB camera", "");
core::Property GetUSBCamera::Height(  // NOLINT
    "Height", "Target height of image to capture from USB camera", "");
core::Property GetUSBCamera::Format(  // NOLINT
    "Format",
    "Frame format (currently only PNG and RAW are supported; RAW is a binary pixel buffer of RGB values)",
    "PNG");
core::Property GetUSBCamera::VendorID(  // NOLINT
    "USB Vendor ID", "USB Vendor ID of camera device, in hexadecimal format", "0x0");
core::Property GetUSBCamera::ProductID(  // NOLINT
    "USB Product ID", "USB Product ID of camera device, in hexadecimal format", "0x0");
core::Property GetUSBCamera::SerialNo(  // NOLINT
    "USB Serial No.", "USB Serial No. of camera device", "");
core::Relationship GetUSBCamera::Success(  // NOLINT
    "success", "Sucessfully captured images sent here");
core::Relationship GetUSBCamera::Failure(  // NOLINT
    "failure", "Failures sent here");

void GetUSBCamera::initialize() {
  std::set<core::Property> properties;
  properties.insert(FPS);
  properties.insert(Width);
  properties.insert(Height);
  properties.insert(Format);
  properties.insert(VendorID);
  properties.insert(ProductID);
  properties.insert(SerialNo);
  setSupportedProperties(properties);

  std::set<core::Relationship> relationships;
  relationships.insert(Success);
  relationships.insert(Failure);
  setSupportedRelationships(relationships);
}

void GetUSBCamera::onFrame(uvc_frame_t *frame, void *ptr) {
  auto cb_data = reinterpret_cast<GetUSBCamera::CallbackData *>(ptr);
  std::unique_lock<std::recursive_mutex> lock(*(cb_data->dev_access_mtx), std::try_to_lock);

  if (!lock.owns_lock()) {
    return;
  }

  auto now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch());

  if (now - cb_data->last_frame_time < std::chrono::milliseconds(static_cast<int>(1000.0 / cb_data->target_fps))) {
    return;
  }

  cb_data->last_frame_time = now;

  try {
    uvc_error_t ret;
    cb_data->logger->log_debug("Got frame");

    ret = uvc_any2rgb(frame, cb_data->frame_buffer);

    if (ret) {
      cb_data->logger->log_error("Failed to convert frame to RGB: %s", uvc_strerror(ret));
      return;
    }

    auto session = cb_data->session_factory->createSession();
    auto flow_file = session->create();

    std::string flow_file_name;
    flow_file->getAttribute("filename", flow_file_name);
    cb_data->logger->log_info("Created flow file: %s", flow_file_name);

    // Initialize callback according to output format
    std::shared_ptr<OutputStreamCallback> write_cb;

    if (cb_data->format == "PNG") {
      write_cb = std::make_shared<GetUSBCamera::PNGWriteCallback>(cb_data->png_write_mtx,
                                                                  cb_data->frame_buffer,
                                                                  cb_data->device_width,
                                                                  cb_data->device_height);
    } else if (cb_data->format == "RAW") {
      write_cb = std::make_shared<GetUSBCamera::RawWriteCallback>(cb_data->frame_buffer);
    } else {
      cb_data->logger->log_warn("Invalid format specified (%s); defaulting to PNG", cb_data->format);
      write_cb = std::make_shared<GetUSBCamera::PNGWriteCallback>(cb_data->png_write_mtx,
                                                                  cb_data->frame_buffer,
                                                                  cb_data->device_width,
                                                                  cb_data->device_height);
    }

    session->write(flow_file, write_cb.get());
    session->transfer(flow_file, GetUSBCamera::Success);
    session->commit();
  } catch (std::exception &exception) {
    cb_data->logger->log_debug("GetUSBCamera Caught Exception %s", exception.what());
  } catch (...) {
    cb_data->logger->log_debug("GetUSBCamera Caught Unknown Exception");
  }
}

void GetUSBCamera::onSchedule(core::ProcessContext *context, core::ProcessSessionFactory *session_factory) {
  std::lock_guard<std::recursive_mutex> lock(*dev_access_mtx_);

  double default_fps = 1;
  double target_fps = default_fps;
  std::string conf_fps_str;
  context->getProperty("FPS", conf_fps_str);

  if (conf_fps_str.empty()) {
    logger_->log_info("FPS property was not set; using default %f", default_fps);
  } else {
    try {
      target_fps = std::stod(conf_fps_str);
    } catch (std::invalid_argument &e) {
      logger_->log_error("Could not parse configured FPS value (will use default %f): %s", default_fps, conf_fps_str);
    }
  }

  uint16_t target_width = 0;
  uint16_t target_height = 0;
  std::string conf_width_str;
  context->getProperty("Width", conf_width_str);

  if (!conf_width_str.empty()) {
    auto target_width_ul = std::stoul(conf_width_str);
    if (target_width_ul > UINT16_MAX) {
      logger_->log_error("Configured target width %s is out of range", conf_width_str);
    } else {
      target_width = static_cast<uint16_t>(target_width_ul);
    }
    logger_->log_info("Using configured target width: %i", target_width);
  }

  std::string conf_height_str;
  context->getProperty("Height", conf_height_str);

  if (!conf_height_str.empty()) {
    auto target_height_ul = std::stoul(conf_height_str);
    if (target_height_ul > UINT16_MAX) {
      logger_->log_error("Configured target height %s is out of range", conf_height_str);
    } else {
      target_height = static_cast<uint16_t>(target_height_ul);
    }
    logger_->log_info("Using configured target height: %i", target_height);
  }

  std::string conf_format_str;
  context->getProperty("Format", conf_format_str);

  int usb_vendor_id;
  std::string conf_vendor_id;
  context->getProperty("USB Vendor ID", conf_vendor_id);
  std::stringstream(conf_vendor_id) >> std::hex >> usb_vendor_id;
  logger_->log_info("Using USB Vendor ID: %x", usb_vendor_id);

  int usb_product_id;
  std::string conf_product_id;
  context->getProperty("USB Product ID", conf_product_id);
  std::stringstream(conf_product_id) >> std::hex >> usb_product_id;
  logger_->log_info("Using USB Product ID: %x", usb_product_id);

  const char *usb_serial_no = nullptr;
  std::string conf_serial;
  context->getProperty("USB Serial No.", conf_serial);

  if (!conf_serial.empty()) {
    usb_serial_no = conf_serial.c_str();
    logger_->log_info("Using USB Serial No.: %s", conf_serial);
  }

  cleanupUvc();
  logger_->log_info("Beginning to capture frames from USB camera");

  uvc_stream_ctrl_t ctrl{};
  uvc_error_t res;
  res = uvc_init(&ctx_, nullptr);

  if (res < 0) {
    logger_->log_error("Failed to initialize UVC service context");
    ctx_ = nullptr;
    return;
  }

  logger_->log_debug("UVC initialized");

  // Locate device
  res = uvc_find_device(ctx_, &dev_, usb_vendor_id, usb_product_id, usb_serial_no);

  if (res < 0) {
    logger_->log_error("Unable to find device: %s", uvc_strerror(res));
    dev_ = nullptr;
  } else {
    logger_->log_info("Device found");

    // Open the device
    res = uvc_open(dev_, &devh_);

    if (res < 0) {
      logger_->log_error("Unable to open device: %s", uvc_strerror(res));
      devh_ = nullptr;
    } else {
      logger_->log_info("Device opened");

      // Iterate resolutions & framerates >= context fps, or nearest
      uint16_t width = 0;
      uint16_t height = 0;
      uint32_t max_size = 0;
      uint32_t fps = 0;

      double min_diff = -1;
      double current_diff = -1;
      double current_width_diff = -1;
      double current_height_diff = -1;

      for (auto fmt_desc = uvc_get_format_descs(devh_); fmt_desc; fmt_desc = fmt_desc->next) {
        uvc_frame_desc_t *frame_desc;
        switch (fmt_desc->bDescriptorSubtype) {
          case UVC_VS_FORMAT_UNCOMPRESSED:
          case UVC_VS_FORMAT_FRAME_BASED:
            for (frame_desc = fmt_desc->frame_descs; frame_desc; frame_desc = frame_desc->next) {
              uint32_t frame_fps = 10000000 / frame_desc->dwDefaultFrameInterval;
              logger_->log_info("Discovered supported format %ix%i @ %i",
                                frame_desc->wWidth,
                                frame_desc->wHeight,
                                frame_fps);
              if (target_height > 0 && target_width > 0) {
                if (frame_fps >= target_fps) {
                  current_width_diff = abs(frame_desc->wWidth - target_width) / static_cast<double>(target_width);
                  logger_->log_debug("Current frame format width difference is %f", current_width_diff);
                  current_height_diff = abs(frame_desc->wHeight - target_height) / static_cast<double>(target_height);
                  logger_->log_debug("Current frame format height difference is %f", current_height_diff);
                  current_diff = (current_width_diff + current_height_diff) / 2;
                  logger_->log_debug("Current frame format difference is %f", current_diff);

                  if (min_diff < 0 || current_diff < min_diff) {
                    logger_->log_info("Format %ix%i @ %i is now closest to target",
                                      frame_desc->wWidth,
                                      frame_desc->wHeight,
                                      frame_fps);
                    width = frame_desc->wWidth;
                    height = frame_desc->wHeight;
                    max_size = frame_desc->dwMaxVideoFrameBufferSize;
                    fps = frame_fps;
                    min_diff = current_diff;
                  }
                }

              } else {
                if (frame_desc->dwMaxVideoFrameBufferSize > max_size && frame_fps >= target_fps) {
                  width = frame_desc->wWidth;
                  height = frame_desc->wHeight;
                  max_size = frame_desc->dwMaxVideoFrameBufferSize;
                  fps = frame_fps;
                }
              }
            }

          case UVC_VS_FORMAT_MJPEG:logger_->log_info("Skipping MJPEG frame formats");

          default:logger_->log_warn("Found unknown format");
        }
      }

      if (fps == 0) {
        logger_->log_error("Could not find suitable frame format from device. "
                           "Try changing configuration (lower FPS) or device.");
        return;
      }

      logger_->log_info("Negotiating stream profile (looking for %dx%d @ %d)", width, height, fps);

      res = uvc_get_stream_ctrl_format_size(devh_, &ctrl, UVC_FRAME_FORMAT_UNCOMPRESSED, width, height, fps);

      if (res < 0) {
        logger_->log_error("Failed to find a matching stream profile: %s", uvc_strerror(res));
      } else {
        cb_data_.session_factory = session_factory;

        if (frame_buffer_ != nullptr) {
          uvc_free_frame(frame_buffer_);
        }

        frame_buffer_ = uvc_allocate_frame(width * height * 3);

        if (!frame_buffer_) {
          printf("unable to allocate bgr frame!");
          logger_->log_error("Unable to allocate RGB frame");
          return;
        }

        cb_data_.frame_buffer = frame_buffer_;
        cb_data_.context = context;
        cb_data_.png_write_mtx = png_write_mtx_;
        cb_data_.dev_access_mtx = dev_access_mtx_;
        cb_data_.logger = logger_;
        cb_data_.format = conf_format_str;
        cb_data_.device_width = width;
        cb_data_.device_height = height;
        cb_data_.device_fps = fps;
        cb_data_.target_fps = target_fps;
        cb_data_.last_frame_time = std::chrono::milliseconds(0);

        res = uvc_start_streaming(devh_, &ctrl, onFrame, &cb_data_, 0);

        if (res < 0) {
          logger_->log_error("Unable to start streaming: %s", uvc_strerror(res));
        } else {
          logger_->log_info("Streaming...");

          // Enable auto-exposure
          uvc_set_ae_mode(devh_, 1);
        }
      }
    }
  }
}

void GetUSBCamera::cleanupUvc() {
  std::lock_guard<std::recursive_mutex> lock(*dev_access_mtx_);

  if (frame_buffer_ != nullptr) {
    logger_->log_debug("Deallocating frame buffer");
    uvc_free_frame(frame_buffer_);
  }

  if (devh_ != nullptr) {
    logger_->log_debug("Stopping UVC streaming");
    uvc_stop_streaming(devh_);
    logger_->log_debug("Closing UVC device handle");
    uvc_close(devh_);
  }

  if (dev_ != nullptr) {
    logger_->log_debug("Closing UVC device descriptor");
    uvc_unref_device(dev_);
  }

  if (ctx_ != nullptr) {
    logger_->log_debug("Closing UVC context");
    uvc_exit(ctx_);
  }

  if (camera_thread_ != nullptr) {
    camera_thread_->join();
    logger_->log_debug("UVC thread ended");
  }
}

void GetUSBCamera::onTrigger(core::ProcessContext *context, core::ProcessSession *session) {
  auto flowFile = session->get();

  if (flowFile) {
    logger_->log_error("Received flowfile, but this processor does not support input flow files; routing to failure");
    session->transfer(flowFile, Failure);
  }
}

GetUSBCamera::PNGWriteCallback::PNGWriteCallback(std::shared_ptr<std::mutex> write_mtx,
                                                 uvc_frame_t *frame,
                                                 uint32_t width,
                                                 uint32_t height)
    : png_write_mtx_(std::move(write_mtx)),
      frame_(frame),
      width_(width),
      height_(height),
      logger_(logging::LoggerFactory<PNGWriteCallback>::getLogger()) {
}

int64_t GetUSBCamera::PNGWriteCallback::process(std::shared_ptr<io::BaseStream> stream) {
  std::lock_guard<std::mutex> lock(*png_write_mtx_);
  logger_->log_info("Writing %d bytes of raw capture data to PNG output", frame_->data_bytes);
  png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);

  if (!png) {
    logger_->log_error("Failed to create PNG write struct");
    return 0;
  }

  png_infop info = png_create_info_struct(png);

  if (!info) {
    logger_->log_error("Failed to create PNG info struct");
    return 0;
  }

  if (setjmp(png_jmpbuf(png))) {
    logger_->log_error("Failed to set PNG jmpbuf");
    return 0;
  }

  try {

    png_set_write_fn(png, this, [](png_structp out_png,
                                   png_bytep out_data,
                                   png_size_t num_bytes) {
                       auto this_callback = reinterpret_cast<PNGWriteCallback *>(png_get_io_ptr(out_png));
                       std::copy(out_data, out_data + num_bytes, std::back_inserter(this_callback->png_output_buf_));
                     },
                     [](png_structp flush_png) {});

    png_set_IHDR(png, info, width_, height_, 8,
                 PNG_COLOR_TYPE_RGB,
                 PNG_INTERLACE_NONE,
                 PNG_COMPRESSION_TYPE_DEFAULT,
                 PNG_FILTER_TYPE_DEFAULT);
    png_write_info(png, info);

    png_bytep row_pointers[height_];

    for (uint32_t y = 0; y < height_; y++) {
      row_pointers[y] = reinterpret_cast<png_byte *>(frame_->data) + width_ * y * 3;
    }

    png_write_image(png, &row_pointers[0]);
    png_write_end(png, nullptr);

    png_destroy_write_struct(&png, &info);
  } catch (...) {
    if (png && info) {
      png_destroy_write_struct(&png, &info);
    }
    throw;
  }

  return stream->writeData(png_output_buf_.data(), png_output_buf_.size());
}

GetUSBCamera::RawWriteCallback::RawWriteCallback(uvc_frame_t *frame)
    : frame_(frame),
      logger_(logging::LoggerFactory<RawWriteCallback>::getLogger()) {
}

int64_t GetUSBCamera::RawWriteCallback::process(std::shared_ptr<io::BaseStream> stream) {
  logger_->log_info("Writing %d bytes of raw capture data", frame_->data_bytes);
  return stream->writeData(reinterpret_cast<uint8_t *>(frame_->data), frame_->data_bytes);
}

} /* namespace processors */
} /* namespace minifi */
} /* namespace nifi */
} /* namespace apache */
} /* namespace org */


text:
namespace android_webview {

AwSafeBrowsingSubresourceHelper::~AwSafeBrowsingSubresourceHelper() {}

void AwSafeBrowsingSubresourceHelper::ReadyToCommitNavigation(
    content::NavigationHandle* navigation_handle) {
  if (navigation_handle->GetNetErrorCode() == net::ERR_BLOCKED_BY_CLIENT) {
    AwSafeBrowsingUIManager* manager =
        AwBrowserProcess::GetInstance()->GetSafeBrowsingUIManager();
    if (!manager)
      return;
    security_interstitials::UnsafeResource resource;
    if (manager->PopUnsafeResourceForURL(navigation_handle->GetURL(),
                                         &resource)) {
      std::unique_ptr<AwWebResourceRequest> request =
          std::make_unique<AwWebResourceRequest>(
              navigation_handle->GetURL().spec(),
              navigation_handle->IsPost() ? "POST" : "GET",
              navigation_handle->IsInMainFrame(),
              navigation_handle->HasUserGesture(),
              navigation_handle->GetRequestHeaders());
      request->is_renderer_initiated = navigation_handle->IsRendererInitiated();
      AwSafeBrowsingBlockingPage* blocking_page =
          AwSafeBrowsingBlockingPage::CreateBlockingPage(
              manager, navigation_handle->GetWebContents(),
              navigation_handle->GetURL(), resource, std::move(request));
      security_interstitials::SecurityInterstitialTabHelper::
          AssociateBlockingPage(navigation_handle->GetWebContents(),
                                navigation_handle->GetNavigationId(),
                                base::WrapUnique(blocking_page));
    }
  }
}

AwSafeBrowsingSubresourceHelper::AwSafeBrowsingSubresourceHelper(
    content::WebContents* web_contents)
    : WebContentsObserver(web_contents) {}

WEB_CONTENTS_USER_DATA_KEY_IMPL(AwSafeBrowsingSubresourceHelper)

}  // namespace android_webview


text:
package com.bjzh.ws.book.service.impl;

import com.bjzh.ws.book.entity.Book;
import com.bjzh.ws.book.service.IBookService;

public class BookServiceImpl implements IBookService {

	public Book getBookById(int id) {
		Book book = new Book(id, "china");
		return book;
	}

}


text:
require "spec_helper"

require "hamster/set"

describe Hamster::Set do

  [:to_a, :entries].each do |method|

    describe "##{method}" do

      [
        [],
        ["A"],
        %w[A B C],
      ].each do |values|

        describe "on #{values.inspect}" do

          before do
            @set = Hamster.set(*values)
            @result = @set.send(method)
          end

          it "returns #{values.inspect}" do
            @result.sort.should == values.sort
          end

          it "returns a mutable array" do
            expect(@result.last).to_not eq("The End")
            @result << "The End"
            @result.last.should == "The End"
          end

        end

      end

    end

  end

end


text:
namespace gameplay
{

extern void luaGlobal_Register_Conversion_Function(const char* className, void*(*func)(void*, const char*));

static AudioListener* getInstance(lua_State* state)
{
    void* userdata = luaL_checkudata(state, 1, "AudioListener");
    luaL_argcheck(state, userdata != NULL, 1, "'AudioListener' expected.");
    return (AudioListener*)((gameplay::ScriptUtil::LuaObject*)userdata)->instance;
}

static int lua_AudioListener_getCamera(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                AudioListener* instance = getInstance(state);
                void* returnPtr = ((void*)instance->getCamera());
                if (returnPtr)
                {
                    gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                    object->instance = returnPtr;
                    object->owns = false;
                    luaL_getmetatable(state, "Camera");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_AudioListener_getCamera - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_AudioListener_getGain(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                AudioListener* instance = getInstance(state);
                float result = instance->getGain();

                // Push the return value onto the stack.
                lua_pushnumber(state, result);

                return 1;
            }

            lua_pushstring(state, "lua_AudioListener_getGain - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_AudioListener_getOrientationForward(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                AudioListener* instance = getInstance(state);
                void* returnPtr = (void*)&(instance->getOrientationForward());
                if (returnPtr)
                {
                    gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                    object->instance = returnPtr;
                    object->owns = false;
                    luaL_getmetatable(state, "Vector3");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_AudioListener_getOrientationForward - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_AudioListener_getOrientationUp(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                AudioListener* instance = getInstance(state);
                void* returnPtr = (void*)&(instance->getOrientationUp());
                if (returnPtr)
                {
                    gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                    object->instance = returnPtr;
                    object->owns = false;
                    luaL_getmetatable(state, "Vector3");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_AudioListener_getOrientationUp - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_AudioListener_getPosition(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                AudioListener* instance = getInstance(state);
                void* returnPtr = (void*)&(instance->getPosition());
                if (returnPtr)
                {
                    gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                    object->instance = returnPtr;
                    object->owns = false;
                    luaL_getmetatable(state, "Vector3");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_AudioListener_getPosition - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_AudioListener_getVelocity(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                AudioListener* instance = getInstance(state);
                void* returnPtr = (void*)&(instance->getVelocity());
                if (returnPtr)
                {
                    gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                    object->instance = returnPtr;
                    object->owns = false;
                    luaL_getmetatable(state, "Vector3");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_AudioListener_getVelocity - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_AudioListener_setCamera(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 2:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA) &&
                (lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TTABLE || lua_type(state, 2) == LUA_TNIL))
            {
                // Get parameter 1 off the stack.
                bool param1Valid;
                gameplay::ScriptUtil::LuaArray<Camera> param1 = gameplay::ScriptUtil::getObjectPointer<Camera>(2, "Camera", false, &param1Valid);
                if (!param1Valid)
                {
                    lua_pushstring(state, "Failed to convert parameter 1 to type 'Camera'.");
                    lua_error(state);
                }

                AudioListener* instance = getInstance(state);
                instance->setCamera(param1);

                return 0;
            }

            lua_pushstring(state, "lua_AudioListener_setCamera - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 2).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_AudioListener_setGain(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 2:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA) &&
                lua_type(state, 2) == LUA_TNUMBER)
            {
                // Get parameter 1 off the stack.
                float param1 = (float)luaL_checknumber(state, 2);

                AudioListener* instance = getInstance(state);
                instance->setGain(param1);

                return 0;
            }

            lua_pushstring(state, "lua_AudioListener_setGain - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 2).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_AudioListener_setOrientation(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 3:
        {
            do
            {
                if ((lua_type(state, 1) == LUA_TUSERDATA) &&
                    (lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL) &&
                    (lua_type(state, 3) == LUA_TUSERDATA || lua_type(state, 3) == LUA_TNIL))
                {
                    // Get parameter 1 off the stack.
                    bool param1Valid;
                    gameplay::ScriptUtil::LuaArray<Vector3> param1 = gameplay::ScriptUtil::getObjectPointer<Vector3>(2, "Vector3", true, &param1Valid);
                    if (!param1Valid)
                        break;

                    // Get parameter 2 off the stack.
                    bool param2Valid;
                    gameplay::ScriptUtil::LuaArray<Vector3> param2 = gameplay::ScriptUtil::getObjectPointer<Vector3>(3, "Vector3", true, &param2Valid);
                    if (!param2Valid)
                        break;

                    AudioListener* instance = getInstance(state);
                    instance->setOrientation(*param1, *param2);

                    return 0;
                }
            } while (0);

            lua_pushstring(state, "lua_AudioListener_setOrientation - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        case 7:
        {
            do
            {
                if ((lua_type(state, 1) == LUA_TUSERDATA) &&
                    lua_type(state, 2) == LUA_TNUMBER &&
                    lua_type(state, 3) == LUA_TNUMBER &&
                    lua_type(state, 4) == LUA_TNUMBER &&
                    lua_type(state, 5) == LUA_TNUMBER &&
                    lua_type(state, 6) == LUA_TNUMBER &&
                    lua_type(state, 7) == LUA_TNUMBER)
                {
                    // Get parameter 1 off the stack.
                    float param1 = (float)luaL_checknumber(state, 2);

                    // Get parameter 2 off the stack.
                    float param2 = (float)luaL_checknumber(state, 3);

                    // Get parameter 3 off the stack.
                    float param3 = (float)luaL_checknumber(state, 4);

                    // Get parameter 4 off the stack.
                    float param4 = (float)luaL_checknumber(state, 5);

                    // Get parameter 5 off the stack.
                    float param5 = (float)luaL_checknumber(state, 6);

                    // Get parameter 6 off the stack.
                    float param6 = (float)luaL_checknumber(state, 7);

                    AudioListener* instance = getInstance(state);
                    instance->setOrientation(param1, param2, param3, param4, param5, param6);

                    return 0;
                }
            } while (0);

            lua_pushstring(state, "lua_AudioListener_setOrientation - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 3 or 7).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_AudioListener_setPosition(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 2:
        {
            do
            {
                if ((lua_type(state, 1) == LUA_TUSERDATA) &&
                    (lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL))
                {
                    // Get parameter 1 off the stack.
                    bool param1Valid;
                    gameplay::ScriptUtil::LuaArray<Vector3> param1 = gameplay::ScriptUtil::getObjectPointer<Vector3>(2, "Vector3", true, &param1Valid);
                    if (!param1Valid)
                        break;

                    AudioListener* instance = getInstance(state);
                    instance->setPosition(*param1);

                    return 0;
                }
            } while (0);

            lua_pushstring(state, "lua_AudioListener_setPosition - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        case 4:
        {
            do
            {
                if ((lua_type(state, 1) == LUA_TUSERDATA) &&
                    lua_type(state, 2) == LUA_TNUMBER &&
                    lua_type(state, 3) == LUA_TNUMBER &&
                    lua_type(state, 4) == LUA_TNUMBER)
                {
                    // Get parameter 1 off the stack.
                    float param1 = (float)luaL_checknumber(state, 2);

                    // Get parameter 2 off the stack.
                    float param2 = (float)luaL_checknumber(state, 3);

                    // Get parameter 3 off the stack.
                    float param3 = (float)luaL_checknumber(state, 4);

                    AudioListener* instance = getInstance(state);
                    instance->setPosition(param1, param2, param3);

                    return 0;
                }
            } while (0);

            lua_pushstring(state, "lua_AudioListener_setPosition - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 2 or 4).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_AudioListener_setVelocity(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 2:
        {
            do
            {
                if ((lua_type(state, 1) == LUA_TUSERDATA) &&
                    (lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL))
                {
                    // Get parameter 1 off the stack.
                    bool param1Valid;
                    gameplay::ScriptUtil::LuaArray<Vector3> param1 = gameplay::ScriptUtil::getObjectPointer<Vector3>(2, "Vector3", true, &param1Valid);
                    if (!param1Valid)
                        break;

                    AudioListener* instance = getInstance(state);
                    instance->setVelocity(*param1);

                    return 0;
                }
            } while (0);

            lua_pushstring(state, "lua_AudioListener_setVelocity - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        case 4:
        {
            do
            {
                if ((lua_type(state, 1) == LUA_TUSERDATA) &&
                    lua_type(state, 2) == LUA_TNUMBER &&
                    lua_type(state, 3) == LUA_TNUMBER &&
                    lua_type(state, 4) == LUA_TNUMBER)
                {
                    // Get parameter 1 off the stack.
                    float param1 = (float)luaL_checknumber(state, 2);

                    // Get parameter 2 off the stack.
                    float param2 = (float)luaL_checknumber(state, 3);

                    // Get parameter 3 off the stack.
                    float param3 = (float)luaL_checknumber(state, 4);

                    AudioListener* instance = getInstance(state);
                    instance->setVelocity(param1, param2, param3);

                    return 0;
                }
            } while (0);

            lua_pushstring(state, "lua_AudioListener_setVelocity - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 2 or 4).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_AudioListener_static_getInstance(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 0:
        {
            void* returnPtr = ((void*)AudioListener::getInstance());
            if (returnPtr)
            {
                gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                object->instance = returnPtr;
                object->owns = false;
                luaL_getmetatable(state, "AudioListener");
                lua_setmetatable(state, -2);
            }
            else
            {
                lua_pushnil(state);
            }

            return 1;
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 0).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

// Provides support for conversion to all known relative types of AudioListener
static void* __convertTo(void* ptr, const char* typeName)
{
    AudioListener* ptrObject = reinterpret_cast<AudioListener*>(ptr);

    if (strcmp(typeName, "Camera::Listener") == 0)
    {
        return reinterpret_cast<void*>(static_cast<Camera::Listener*>(ptrObject));
    }

    // No conversion available for 'typeName'
    return NULL;
}

static int lua_AudioListener_to(lua_State* state)
{
    // There should be only a single parameter (this instance)
    if (lua_gettop(state) != 2 || lua_type(state, 1) != LUA_TUSERDATA || lua_type(state, 2) != LUA_TSTRING)
    {
        lua_pushstring(state, "lua_AudioListener_to - Invalid number of parameters (expected 2).");
        lua_error(state);
        return 0;
    }

    AudioListener* instance = getInstance(state);
    const char* typeName = gameplay::ScriptUtil::getString(2, false);
    void* result = __convertTo((void*)instance, typeName);

    if (result)
    {
        gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
        object->instance = (void*)result;
        object->owns = false;
        luaL_getmetatable(state, typeName);
        lua_setmetatable(state, -2);
    }
    else
    {
        lua_pushnil(state);
    }

    return 1;
}

void luaRegister_AudioListener()
{
    const luaL_Reg lua_members[] =
    {
        {"getCamera", lua_AudioListener_getCamera},
        {"getGain", lua_AudioListener_getGain},
        {"getOrientationForward", lua_AudioListener_getOrientationForward},
        {"getOrientationUp", lua_AudioListener_getOrientationUp},
        {"getPosition", lua_AudioListener_getPosition},
        {"getVelocity", lua_AudioListener_getVelocity},
        {"setCamera", lua_AudioListener_setCamera},
        {"setGain", lua_AudioListener_setGain},
        {"setOrientation", lua_AudioListener_setOrientation},
        {"setPosition", lua_AudioListener_setPosition},
        {"setVelocity", lua_AudioListener_setVelocity},
        {"to", lua_AudioListener_to},
        {NULL, NULL}
    };
    const luaL_Reg lua_statics[] =
    {
        {"getInstance", lua_AudioListener_static_getInstance},
        {NULL, NULL}
    };
    std::vector<std::string> scopePath;

    gameplay::ScriptUtil::registerClass("AudioListener", lua_members, NULL, NULL, lua_statics, scopePath);

    luaGlobal_Register_Conversion_Function("AudioListener", __convertTo);
}

}


text:
package codec

import (
	"time"

	"github.com/influxdata/telegraf/plugins/inputs/zipkin/trace"
	"github.com/openzipkin/zipkin-go-opentracing/_thrift/gen-go/zipkincore"
)

//now is a mockable time for now
var now = time.Now

// DefaultServiceName when the span does not have any serviceName
const DefaultServiceName = "unknown"

// Decoder decodes the bytes and returns a trace
type Decoder interface {
	Decode(octets []byte) ([]Span, error)
}

// Span are created by instrumentation in RPC clients or servers
type Span interface {
	Trace() (string, error)
	SpanID() (string, error)
	Parent() (string, error)
	Name() string
	Annotations() []Annotation
	BinaryAnnotations() ([]BinaryAnnotation, error)
	Timestamp() time.Time
	Duration() time.Duration
}

// Annotation represents an event that explains latency with a timestamp.
type Annotation interface {
	Timestamp() time.Time
	Value() string
	Host() Endpoint
}

// BinaryAnnotation represent tags applied to a Span to give it context
type BinaryAnnotation interface {
	Key() string
	Value() string
	Host() Endpoint
}

// Endpoint represents the network context of a service recording an annotation
type Endpoint interface {
	Host() string
	Name() string
}

// DefaultEndpoint is used if the annotations have no endpoints
type DefaultEndpoint struct{}

// Host returns 0.0.0.0; used when the host is unknown
func (d *DefaultEndpoint) Host() string { return "0.0.0.0" }

// Name returns "unknown" when an endpoint doesn't exist
func (d *DefaultEndpoint) Name() string { return DefaultServiceName }

// MicroToTime converts zipkin's native time of microseconds into time.Time
func MicroToTime(micro int64) time.Time {
	return time.Unix(0, micro*int64(time.Microsecond)).UTC()
}

// NewTrace converts a slice of []Span into a new Trace
func NewTrace(spans []Span) (trace.Trace, error) {
	tr := make(trace.Trace, len(spans))
	for i, span := range spans {
		bin, err := span.BinaryAnnotations()
		if err != nil {
			return nil, err
		}
		endpoint := serviceEndpoint(span.Annotations(), bin)
		id, err := span.SpanID()
		if err != nil {
			return nil, err
		}

		tid, err := span.Trace()
		if err != nil {
			return nil, err
		}

		pid, err := parentID(span)
		if err != nil {
			return nil, err
		}

		tr[i] = trace.Span{
			ID:                id,
			TraceID:           tid,
			Name:              span.Name(),
			Timestamp:         guessTimestamp(span),
			Duration:          convertDuration(span),
			ParentID:          pid,
			ServiceName:       endpoint.Name(),
			Annotations:       NewAnnotations(span.Annotations(), endpoint),
			BinaryAnnotations: NewBinaryAnnotations(bin, endpoint),
		}
	}
	return tr, nil
}

// NewAnnotations converts a slice of Annotation into a slice of new Annotations
func NewAnnotations(annotations []Annotation, endpoint Endpoint) []trace.Annotation {
	formatted := make([]trace.Annotation, len(annotations))
	for i, annotation := range annotations {
		formatted[i] = trace.Annotation{
			Host:        endpoint.Host(),
			ServiceName: endpoint.Name(),
			Timestamp:   annotation.Timestamp(),
			Value:       annotation.Value(),
		}
	}

	return formatted
}

// NewBinaryAnnotations is very similar to NewAnnotations, but it
// converts BinaryAnnotations instead of the normal Annotation
func NewBinaryAnnotations(annotations []BinaryAnnotation, endpoint Endpoint) []trace.BinaryAnnotation {
	formatted := make([]trace.BinaryAnnotation, len(annotations))
	for i, annotation := range annotations {
		formatted[i] = trace.BinaryAnnotation{
			Host:        endpoint.Host(),
			ServiceName: endpoint.Name(),
			Key:         annotation.Key(),
			Value:       annotation.Value(),
		}
	}
	return formatted
}

func minMax(span Span) (time.Time, time.Time) {
	min := now().UTC()
	max := time.Time{}.UTC()
	for _, annotation := range span.Annotations() {
		ts := annotation.Timestamp()
		if !ts.IsZero() && ts.Before(min) {
			min = ts
		}
		if !ts.IsZero() && ts.After(max) {
			max = ts
		}
	}
	if max.IsZero() {
		max = min
	}
	return min, max
}

func guessTimestamp(span Span) time.Time {
	ts := span.Timestamp()
	if !ts.IsZero() {
		return ts
	}

	min, _ := minMax(span)
	return min
}

func convertDuration(span Span) time.Duration {
	duration := span.Duration()
	if duration != 0 {
		return duration
	}
	min, max := minMax(span)
	return max.Sub(min)
}

func parentID(span Span) (string, error) {
	// A parent ID of "" means that this is a parent span. In this case,
	// we set the parent ID of the span to be its own id, so it points to
	// itself.
	id, err := span.Parent()
	if err != nil {
		return "", err
	}

	if id != "" {
		return id, nil
	}
	return span.SpanID()
}

func serviceEndpoint(ann []Annotation, bann []BinaryAnnotation) Endpoint {
	for _, a := range ann {
		switch a.Value() {
		case zipkincore.SERVER_RECV, zipkincore.SERVER_SEND, zipkincore.CLIENT_RECV, zipkincore.CLIENT_SEND:
			if a.Host() != nil && a.Host().Name() != "" {
				return a.Host()
			}
		}
	}

	for _, a := range bann {
		if a.Key() == zipkincore.LOCAL_COMPONENT && a.Host() != nil && a.Host().Name() != "" {
			return a.Host()
		}
	}
	// Unable to find any "standard" endpoint host, so, use any that exist in the regular annotations
	for _, a := range ann {
		if a.Host() != nil && a.Host().Name() != "" {
			return a.Host()
		}
	}
	return &DefaultEndpoint{}
}


text:
package com.feedsome.service.route;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.feedsome.model.FeedNotification;
import com.feedsome.service.route.configuration.EndpointProperties;
import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.spring.boot.CamelAutoConfiguration;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import redis.embedded.RedisServer;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {
        CamelAutoConfiguration.class,
        DataFeedSendRouteTester.TestConfiguration.class
})
public class DataFeedSendRouteTester {

    private static final String verifyFeedMockUri = "mock:feed:verify";

    @Configuration
    @Import(DataFeedSendRoute.class)
    static class TestConfiguration {

        @Bean
        public ObjectMapper mapper() {
            return new ObjectMapper();
        }

        @Bean
        public EndpointProperties endpointProperties() {
            final EndpointProperties props = new EndpointProperties();

            props.setDataFeedSenderUri("seda:feed:push");
            props.setDataFeedPublishUri("spring-redis://localhost:6379?command=PUBLISH");

            return props;
        }

        @Bean
        public RouteBuilder dataFeedConsumerRouteBuilder() {
            return new RouteBuilder() {
                @Override
                public void configure() throws Exception {
                    from("spring-redis://localhost:6379?command=SUBSCRIBE&channels=sports,fancy")
                            .log("Message received!!!")
                            .log("Message body is following...")
                            .log("${body}")
                            .to(verifyFeedMockUri);
                }
            };
        }

    }

    private static RedisServer redisServer;

    @BeforeClass
    public static void setupRedis() throws IOException {
        redisServer  = new RedisServer(6379);
        redisServer.start();
    }

    @AfterClass
    public static void stopRedis() {
        redisServer.stop();
    }

    @Autowired
    private ObjectMapper mapper;

    @EndpointInject(uri = "seda:feed:push")
    private ProducerTemplate pushDataFeedTemplate;

    @EndpointInject(uri = verifyFeedMockUri)
    private MockEndpoint verifyFeedMockEndpoint;

    @Test
    public void testSendDataFeedRoute_sendsFeed() throws Exception {
        final String pluginRef = "myFancyPlugin";

        final Map<String, String> body = new HashMap<String, String>() {{
            put("type", "super");
            put("text", "super is awesome");
        }};

        final String bodyString = mapper.writeValueAsString(body);

        final FeedNotification feedNotification = new FeedNotification();

        feedNotification.setBody(bodyString);
        feedNotification.setPluginRef(pluginRef);
        feedNotification.setTitle("fancy title goes here");

        feedNotification.getCategories().addAll(Arrays.asList("sports", "super", "fancy"));

        pushDataFeedTemplate.sendBody(feedNotification);

        verifyFeedMockEndpoint.expectedMessageCount(1);

        verifyFeedMockEndpoint.await(8, TimeUnit.SECONDS);

        verifyFeedMockEndpoint.assertIsSatisfied();
    }

}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18034
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace TfsWorkbench.StatisticsViewer.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TfsWorkbench.StatisticsViewer.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Workspace Overview.
        /// </summary>
        internal static string String001 {
            get {
                return ResourceManager.GetString("String001", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Instance Count.
        /// </summary>
        internal static string String002 {
            get {
                return ResourceManager.GetString("String002", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Sum Of Metric.
        /// </summary>
        internal static string String003 {
            get {
                return ResourceManager.GetString("String003", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to -.
        /// </summary>
        internal static string String004 {
            get {
                return ResourceManager.GetString("String004", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Displaying statistics for the current loaded workspace. Filtered / (All).
        /// </summary>
        internal static string String005 {
            get {
                return ResourceManager.GetString("String005", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Breakdown by item type:.
        /// </summary>
        internal static string String008 {
            get {
                return ResourceManager.GetString("String008", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Status Overview.
        /// </summary>
        internal static string String009 {
            get {
                return ResourceManager.GetString("String009", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Displaying the workspace data grouped by item state. Filtered / (All).
        /// </summary>
        internal static string String010 {
            get {
                return ResourceManager.GetString("String010", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to N/A.
        /// </summary>
        internal static string String011 {
            get {
                return ResourceManager.GetString("String011", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Views.
        /// </summary>
        internal static string String012 {
            get {
                return ResourceManager.GetString("String012", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Displaying workspace by item relationship view. Filtered / (All).
        /// </summary>
        internal static string String013 {
            get {
                return ResourceManager.GetString("String013", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to  (parent).
        /// </summary>
        internal static string String014 {
            get {
                return ResourceManager.GetString("String014", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to  (child).
        /// </summary>
        internal static string String016 {
            get {
                return ResourceManager.GetString("String016", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to  (orphans).
        /// </summary>
        internal static string String017 {
            get {
                return ResourceManager.GetString("String017", resourceCulture);
            }
        }
    }
}


text:
package com.yahoo.dtf.actions.conditionals;

import com.yahoo.dtf.exception.DTFException;

public interface Conditional {
    /**
     * Returns this conditionals logical value for the current state.
     *
     * @return
     * @throws DTFException
     */
    public boolean evaluate() throws DTFException;

    /**
     * Returns a string which represents in plain English what this condition
     * is attempting to validate.
     *
     * @return
     */
    public String explanation() throws DTFException;
}


text:
CSRFBanana
==========
[![Build Status](https://travis-ci.org/josephspurrier/csrfbanana.svg)](https://travis-ci.org/josephspurrier/csrfbanana) [![Coverage Status](https://coveralls.io/repos/josephspurrier/csrfbanana/badge.svg)](https://coveralls.io/r/josephspurrier/csrfbanana) [![GoDoc](https://godoc.org/github.com/josephspurrier/csrfbanana?status.svg)](https://godoc.org/github.com/josephspurrier/csrfbanana)

CSRF Protection for [gorilla/sessions](http://www.gorillatoolkit.org/pkg/sessions) in the Go Language

CSRFBanana is a middleware package that helps prevent cross-site request forgery attacks. The package can generate tokens per session or per page. Tokens can also be regenerated after a successful or failed attempt to validate.

In this package, the CSRF tokens are stored in the (same) session cookie that is handled by gorilla/sessions. You can read about the different CSRF approaches on StackOverflow: [Why is it common to put CSRF prevention tokens in cookies?](http://stackoverflow.com/a/20518324)

## Usage

Import the package:

~~~ go
import "github.com/josephspurrier/csrfbanana"
~~~

Configure the package as middleware:

~~~ go
// Default handler
h := http.HandlerFunc(YourOwnDefaultFunction)

// Insert the CSRFBanana here to prevent CSRF
cs := csrfbanana.New(h, Store, SessionName)

// Set error page for CSRF failures
cs.FailureHandler(http.HandlerFunc(routeInvalidToken))

// Generate a new token after each success/failure (also prevents double submits)
cs.ClearAfterUsage(true)

// Exclude routes like /static/ from token generation/checking
cs.ExcludeRegexPaths([]string{"/static(.*)"})

// Set the token length (default is 32)
csrfbanana.TokenLength = 32

// Set the token name used in the forms and session (default is token)
csrfbanana.TokenName = "token"

// Set the token to generate per page (false - the default) or per session (true)
csrfbanana.SingleToken = false

// Pass the handler to your HTTP server
http.ListenAndServe(":80", cs)
~~~

Generate the token before passing to your templates:

~~~ go
// Create a map for the template
vars := make(map[string]string)

// Store the CSRF token to the map
vars["token"] = csrfbanana.Token(w, r, sess)

// Show the template
templ.Execute(w, vars)
~~~

Add the token to every POST form that is not excluded by ExcludeRegexPaths():

~~~ html
<input type="hidden" name="token" value="{{.token}}">
~~~

Note: Any other POST operation needs to either include the token or be added to ExcludeRegexPaths().

## Working Example

To see the example in action, use the following commands:
~~~
go get github.com/josephspurrier/csrfbanana/example
go run src/github.com/josephspurrier/csrfbanana/example/example.go
~~~

## Major Contributions

Thanks to [Justinas Stankevičius](https://github.com/justinas/nosurf) for his CSRF package which I used as a solid example.


text:
.. include:: ../../Includes.txt

.. _overriding-fluid-templates:

==============================
Overriding the FLUID templates
==============================

At :ref:`typoscript` we have described the way content elements are rendered.

By default these settings are done in the file :file:`setup.txt` which can be found in the
folder :file:`EXT:fluid_styled_content/Configuration/TypoScript/Static/`.

.. _overriding-fluid-templates-using-lib-fluidcontent:

Using lib.fluidContent
======================

This option gives you the possibility to add another `templateRootPath` and can be defined
the same as `partialRootPaths` and `layoutRootPaths`:

.. code-block:: typoscript

   lib.fluidContent {
      templateRootPaths {
         200 = EXT:your_extension_key/Resources/Private/Templates/
      }
      partialRootPaths {
         200 = EXT:your_extension_key/Resources/Private/Partials/
      }
      layoutRootPaths {
         200 = EXT:your_extension_key/Resources/Private/Layouts/
      }
   }

A content element is using a `templateName`, which is defined in :file:`setup.txt`. You
can override this value, but the template from the extension "fluid_styled_content" will
not be loaded then, since its name is still the default value.

.. code-block:: typoscript

   tt_content {
      bullets {
         templateName = ChangedName.html
      }
   }