text:
/**
 * Acts as an EventEmitter, emits following events:
 *
 * accelerate: when acceleration is detected
 * rotate: when rotation is detected
 *
 */
function Tracker() {
  EventEmitter.call(this);
  this._speed = null;
  this._oldAccel = null;
  this._accel = null;
  this._orientation = null;
  this._boundOnMotion = this._onMotion.bind(this);
  this._boundOnOrientation = this._onOrientation.bind(this);
  this.reset();
  this._installEventListeners();
}

var _p = extend(Tracker, EventEmitter);

_p.reset = function() {
	this._speed = { x: 0, y: 0, z: 0 };
	this._accel = { x: 0, y: 0, z: 0 };
	this._oldAccel = { x: 0, y: 0, z: 0 };
	this._orientation = { alpha: 0, beta: 0, gamma: 0 };
};

_p.getAcceleration = function() {
	return this._accel;
};

_p.getSpeed = function() {
	return this._speed;
};

_p.getOrientation = function() {
	return this._orientation;
};

_p._installEventListeners = function() {
	window.addEventListener('deviceorientation', this._boundOnOrientation, false);
	window.addEventListener('devicemotion', this._boundOnMotion, false);
};

_p._uninstallEventListeners = function() {
	window.removeEventListener('deviceorientation', this._boundOnOrientation, false);
	window.removeEventListener('devicemotion', this._boundOnMotion, false);
};

_p._onMotion = function(event) {
	this._accel.x = this._oldAccel.x - event.acceleration.x;
	this._accel.y = this._oldAccel.y - event.acceleration.y;
	this._accel.z = this._oldAccel.z - event.acceleration.z;

	this._oldAccel.x = event.acceleration.x;
	this._oldAccel.y = event.acceleration.y;
	this._oldAccel.z = event.acceleration.z;

	this.emit("accelerate", this._accel);
};

_p._onOrientation = function(event) {
	this._orientation.alpha = event.alpha;
	this._orientation.beta = event.beta;
	this._orientation.gamma = event.gamma;
	this.emit("rotate", this._orientation);
};


text:
  The IBM Watson [Visual Recognition][service_url] service analyzes the visual content of images and videos to understand the scene without any input text describing

Give it a try! Click the button below to fork into IBM DevOps Services and deploy your own copy of this application on Bluemix.

[![Deploy to Bluemix](https://bluemix.net/deploy/button.png)](https://bluemix.net/deploy?repository=https://github.com/watson-developer-cloud/visual-recognition-nodejs)

## Getting Started

1. Create a Bluemix Account

  [Sign up][sign_up] in Bluemix, or use an existing account. Watson Services in Beta are free to use.

2. Download and install the [Cloud-foundry CLI][cloud_foundry] tool

3. Edit the `manifest.yml` file and change the `<application-name>` to something unique.
  ```none
applications:
- services
  - visual-recognition-service
  - text-to-speech-service
  name: <application-name>
  command: node app.js
  path: .
  memory: 128M
  ```
  The name you use will determinate your application url initially, e.g. `<application-name>.mybluemix.net`.

4. Connect to Bluemix in the command line tool
  ```sh
  $ cf api https://api.ng.bluemix.net
  $ cf login -u <your user ID>
  ```

5. Create the Visual Recognition service in Bluemix
  ```sh
  $ cf create-service visual_recognition free visual-recognition-service
  ```
6. Create the Text To Speech service in Bluemix
  ```sh
  $ cf create-service text_to_speech standard text-to-speech-service
  ```

7. Push it live!
  ```sh
  $ cf push
  ```

See the full [Getting Started][getting_started] documentation for more details, including code snippets and references.

## Running locally
  The application uses [Node.js](http://nodejs.org) and [npm](https://www.npmjs.com) so you will have to download and install them as part of the steps below.

1. Copy the credentials from your `visual-recognition-service` and `text-to-speech-service` services in Bluemix to `app.js`, you can see the credentials using:

    ```sh
    $ cf env <application-name>
    ```
    Example output:
    ```sh
    System-Provided:
    {
    "VCAP_SERVICES": {
      "visual_recognition": [{
          "credentials": {
            "url": "<url>",
            "password": "<password>",
            "username": "<username>"
          },
        "label": "visual_recognition",
        "name": "visual-recognition-service",
        "plan": "free"
     }],
      "text_to_speech": [{
          "credentials": {
            "url": "<url>",
            "password": "<password>",
            "username": "<username>"
          },
        "label": "text_to_speech",
        "name": "text-to-speech-service",
        "plan": "standard"}]
      }
    }
    ```

    You need to copy `username`, `password` and `url`.

2. Install [Node.js](http://nodejs.org/)
3. Go to the project folder in a terminal and run:
    `npm install`
4. Start the application
5.  `node app.js`
6. Go to `http://localhost:3000`

## Troubleshooting

To troubleshoot your Bluemix app the main useful source of information are the logs, to see them, run:

  ```sh
  $ cf logs <application-name> --recent
  ```

## License

  This sample code is licensed under Apache 2.0. Full license text is available in [LICENSE](LICENSE).

## Contributing

  See [CONTRIBUTING](CONTRIBUTING.md).

## Open Source @ IBM
  Find more open source projects on the [IBM Github Page](http://ibm.github.io/)

[service_url]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/visual-recognition.html
[cloud_foundry]: https://github.com/cloudfoundry/cli
[getting_started]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/getting_started/
[sign_up]: https://apps.admin.ibmcloud.com/manage/trial/bluemix.html?cm_mmc=WatsonDeveloperCloud-_-LandingSiteGetStarted-_-x-_-CreateAnAccountOnBluemixCLI

redpajama_set_name: RedPajamaGithub


text:
package com.jediq.skinnyfe.config;

import com.jediq.skinnyfe.WrappedException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.map.ObjectMapper;

/**
 *
 */
public class Config {

    private int port;
    private int adminPort;
    private String defaultTemplates = ".";
    private String defaultFragments = ".";
    private List <Resource> resources = new ArrayList<>();
    private List <SkinnyTemplate> templates = new ArrayList<>();
    private long millisToCacheTemplates = 0;
    private String assetsPath;
    private String assetsFolder;
    private String baseLocation = "";
    private String virtualHost = null;
    private String name = "NO-NAME";
    private Map<Integer, String> errorPages = new HashMap<>();
    private String protectedHostsRegex;

    public static Config load(String configLocation) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Config config = objectMapper.readValue(new File(configLocation), Config.class);
            if (config.getPort() == 0) {
                throw new IllegalStateException("At the very least the port needs to be set, see the documentaiton.");
            }
            return config;
        } catch (IOException e) {
            throw new WrappedException(e);
        }
    }

    public List <Resource> getResources() {
        return resources;
    }

    public void setResources(List <Resource> resources) {
        this.resources = resources;
    }

    public String getDefaultTemplates() {
        return getBaseLocation() + defaultTemplates;
    }

    public void setDefaultTemplates(String defaultTemplates) {
        this.defaultTemplates = defaultTemplates;
    }

    public String getDefaultFragments() {
        return defaultFragments;
    }

    public void setDefaultFragments(String defaultFragments) {
        this.defaultFragments = defaultFragments;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public int getAdminPort() {
        return adminPort;
    }

    public void setAdminPort(int adminPort) {
        this.adminPort = adminPort;
    }

    public String getAssetsPath() {
        return assetsPath;
    }

    public void setAssetsPath(String assetsPath) {
        this.assetsPath = assetsPath;
    }

    public String getAssetsFolder() {
        if (assetsFolder != null) {
            return getBaseLocation() + assetsFolder;
        } else {
            return null;
        }
    }

    public void setAssetsFolder(String assetsFolder) {
        this.assetsFolder = assetsFolder;
    }

    public List<SkinnyTemplate> getTemplates() {
        return templates;
    }

    public void setTemplates(List<SkinnyTemplate> templates) {
        this.templates = templates;
    }

    public void setBaseLocation(String baseLocation) {
        this.baseLocation = baseLocation;
    }

    public String getBaseLocation() {
        return baseLocation;
    }

    public Map<Integer, String> getErrorPages() {
        return errorPages;
    }

    public void setErrorPages(Map<Integer, String> errorPages) {
        this.errorPages = errorPages;
    }

    public long getMillisToCacheTemplates() {
        return millisToCacheTemplates;
    }

    public void setMillisToCacheTemplates(long millisToCacheTemplates) {
        this.millisToCacheTemplates = millisToCacheTemplates;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getVirtualHost() {
        return virtualHost;
    }

    public void setVirtualHost(String virtualHost) {
        this.virtualHost = virtualHost;
    }

    public String getProtectedHostsRegex() {
        return protectedHostsRegex;
    }

    public void setProtectedHostsRegex(String protectedHostsRegex) {
        this.protectedHostsRegex = protectedHostsRegex;
    }
}


text:
require 'securerandom'
require 'active_model'
require 'active_support/core_ext/hash/indifferent_access'
require 'bunny'
require 'json'
require 'yell'

require 'samurai/version'
require 'samurai/listener'
require 'samurai/service'
require 'samurai/proxy'
require 'samurai/controller'

module Samurai

end


text:
<?php

namespace BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Category
 *
 * @ORM\Table()
 * @ORM\Entity
 */

class Category
{

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @ORM\OneToMany(targetEntity="Post", mappedBy="category")
     */
    protected $posts;
public function __construct(){
$this->posts=new ArrayCollection();
}

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Category
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Add post
     *
     * @param \BlogBundle\Entity\Post $post
     *
     * @return Category
     */
    public function addPost(\BlogBundle\Entity\Post $post)
    {
        $this->posts[] = $post;

        return $this;
    }

    /**
     * Remove post
     *
     * @param \BlogBundle\Entity\Post $post
     */
    public function removePost(\BlogBundle\Entity\Post $post)
    {
        $this->posts->removeElement($post);
    }

    /**
     * Get posts
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getPosts()
    {
        return $this->posts;
    }
}


text:
import React from 'react';
import { Button } from 'att-iot-ui/lib/button';
import { ListDivider } from 'att-iot-ui/lib/list';
import Icon from 'att-iot-ui/lib/icon';
import ProfileMenu from './profileMenu';

import classnames from 'classnames';

// style
import styles from './style.scss';
import index from '../../../index.scss';
import app from '../../../app.scss';

export default (props) => (

                    <Icon name='att-logo' att width={36} height={36} />    |  IoT Marketplace

                    <ProfileMenu />

);


text:
:root {
  --body-background-color: #eee;
  --card-background-color: #fff;
  --card-border-color: #fff;
  --card-shadow-color: rgba(200, 200, 200, 0.26);
  --text-color: #333;
  --text-color1: #666;
  --text-color2: #999;
  --link-color: #364cc9;
  --table-background-color1: #f5f5f5;
  --table-border-color: #f0f0f0;
  --input-border-color: #ddd;
  --button-background-color: #fff;
  --button-border-color: #eee;
  --button-text-color: #555;
  --button-hover-background-color: #f7f7f7;
  --button-hover-border-color: #eee;
  --button-danger-color: #f85149;
  --button-danger-hover-background-color: #f85149;
  --button-danger-hover-color: #fff;
  --pre-background-color: #f7f7f7;
  --notice-color: #fff;
  --notice-background-color: #3CBD46;
}

@media (prefers-color-scheme: dark) {
  :root {
    --body-background-color: #0d1117;
    --card-background-color: rgba(200, 200, 200, 0.02);
    --card-border-color: #30363d;
    --card-shadow-color: rgba(0, 0, 0, 0.16);
    --text-color: #c9d1d9;
    --text-color1: #999;
    --text-color2: #888;
    --link-color: #58a6ff;
    --table-background-color1: #161b22;
    --table-border-color: #30363d;
    --input-border-color: #333;
    --button-background-color: #21262d;
    --button-border-color: #30363d;
    --button-text-color: #c9d1d9;
    --button-hover-background-color: #30363d;
    --button-hover-border-color: #8b949e;
    --pre-background-color: #161b22;
    --notice-color: #3CBD46;
    --notice-background-color: #3cbd4621;
  }
}

body {
  margin: 0;
  padding: 20px 0;
  background-color: var(--body-background-color);
}

body, textarea {
  font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial, Helvetica, sans-serif;
  font-size: 14px;
  line-height: 1.4;
  color: var(--text-color);
}

.footer {
  padding: 15px;
  text-align: center;
  color: var(--text-color2);
}

.footer a:link, .footer a:visited {
  color: var(--text-color1);
  text-decoration: underline;
}

a, a:visited, a:active {
  color: var(--link-color);
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

table {
  width: 100%;
  border-collapse: collapse;
  border-spacing: 0;
  margin-bottom: 20px;
  border: 1px solid var(--table-border-color);
  border-radius: 3px;
}

td.date {
  width: 170px;
  font-size: 12px;
}

h1 {
  margin-top: 0;
  font-size: 20px;
  font-weight: bold;
}

h1, p {
  margin-bottom: 20px;
}

h3 {
  text-align: center;
}

ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

table td, table th {
  padding: 10px 15px;
}

th {
  text-align: left;
  background: var(--table-background-color1);
  border-bottom: 1px solid var(--table-border-color);
}

td {
  border-top: solid 1px var(--table-border-color);
}

textarea {
  width: 100%;
  height: 100px;
  border: solid 1px var(--input-border-color);
  padding: 10px;
}

hr {
  border: none;
  height: 0;
  border-top: solid 1px var(--input-border-color);
  margin-bottom: 15px;
}

.btn {
  display: inline-block;
  margin-bottom: 0;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  border-radius: 3px;
  transition: .2s cubic-bezier(.3, 0, .5, 1);
  transition-property: color, background-color, border-color;
  border: 1px solid var(--button-border-color);
  padding: 6px 16px;
  color: var(--button-text-color) !important;
  outline: 0 !important;
  background: var(--button-background-color);
}

.btn:hover {
  text-decoration: none !important;
  background: var(--button-hover-background-color);
}

.btn-danger {
  background: var(--button-background-color);
  color: var(--button-danger-color) !important;
  border-color: var(--button-border-color);
}

.btn-danger:hover {
  background: var(--button-danger-hover-background-color);
  color: var(--button-danger-hover-color) !important;
}

.container {
  max-width: 1000px;
  margin-left: auto;
  margin-right: auto;
  padding: 20px;
  background-color: var(--card-background-color);
  box-shadow: 0 1px 8px var(--card-shadow-color);
  border: 1px solid var(--card-border-color);
  border-radius: 3px;
}

.no-record {
  padding: 50px;
  text-align: center;
  font-size: 16px;
}

.toolbar {
  margin-bottom: 15px;
  height: 34px;
  line-height: 34px;
}

.toolbar form {
  display: inline;
}

.toolbar .pull-right {
  float: right;
}

#notice {
  padding: 8px 15px;
  background: var(--notice-background-color);
  color: var(--notice-color);
  margin-bottom: 15px;
  border-radius: 3px;
}

pre {
  white-space: pre-wrap;
  word-break: break-word;
  background: var(--pre-background-color);
  padding: 25px;
  border-radius: 3px;
  font-size: 12px;
  font-family: Menlo, Monaco, Consolas, monospace;
}

h1 {
  font-size: 16px;
}

.pagination {
  padding-bottom: 15px;
  font-size: 14px;
}

.pagination li {
  display: inline;
}

.pagination a {
  display: inline-block;
  padding: 5px 10px;
  border-radius: 3px;
  border: 1px solid var(--button-border-color);
  color: var(--button-text-color);
  background: var(--button-background-color);
  text-decoration: none;
}

.pagination a:hover {
  background: var(--button-hover-background-color);
  color: var(--button-hover-color);
  border-color: var(--button-hover-border-color);
}

.pagination em, .pagination .current {
  border-radius: 3px;
  display: inline-block;
  padding: 5px 10px;
  border: 1px solid var(--button-hover-border-color);
  background: var(--button-hover-background-color);
  font-style: normal;
}


text:
/**
 * NotInitialized Error module.
 * @author Aditya Subramanyam
 * @module
 */

import ExtendableError from './ExtendableError';
/**
 * NotInitialized Error
 */
class NotInitializedError extends ExtendableError {
    /**
     * Create a NotInitializedError.
     * @param {(string|string[])} message - The error message/messages.
     * @param {(string|string[])} fileName - The file/files in which the eror originated.
     * @param {(string|string[])} lineNumber - The line/lines at which error occurred.
     */
    constructor(message, fileName, lineNumber) {
        super(...arguments);
    }
}
/** Export NotInitializedError. */
export default NotInitializedError;


text:
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.slick.protocol.icq;

import junit.framework.*;
import net.java.sip.communicator.service.protocol.*;

/**
 * Phoney tests to signal specific problems with the
 * accounts.properties file
 * @author Brian Burch
 */
public class TestAccountInvalidNotification extends TestCase
{
    ProtocolProviderFactory icqProviderFactory  = null;

    public TestAccountInvalidNotification(String name)
    {
        super(name);
    }

    @Override
    protected void setUp() throws Exception
    {
        super.setUp();

    }

    @Override
    protected void tearDown() throws Exception
    {
        super.tearDown();
    }

    /**
     * It is not meaningful to define a test suite. Each of the
     * pseudo-tests reports a different setup failure, so the
     * appropriate test should be added individually.
     * <p>
     * As a safety measure, we add an empty test suite which
     * will generate a "no tests found" failure.
     *
     * @return an empty test suite.
     */
    public static Test suite()
    {
        TestSuite suite = new TestSuite();
        // will generate a jUnit "no tests found" error condition
        return suite;
    }

    /**
     * The icq test suites MUST have an accounts.properties file
     * that defines two icq test accounts. This test is ONLY
     * executed when icqProtocolProviderSlick.start() has failed
     * to load the Properties and it deliberately fails with a
     * meaningful message.
     */
    public void failIcqTesterAgentMissing()
    {
        fail("The IcqTesterAgent on icq was not defined. "
            +"Possible reasons: account.properties file not found "
            +"in lib directory. Please see wiki for advice on unit "
            +"test setup.");
    }

    /**
     * This test is ONLY executed when icqProtocolProviderSlick.start()
     * has failed to register with the icq service when providing
     * the username and password defined in the account.properties file.
     * It deliberately fails with a meaningful message.
     */
    public void failIcqTesterAgentRegisterRejected()
    {
        fail("Registering the IcqTesterAgent on icq has failed. "
            +"Possible reasons: authentification failure (wrong ICQ "
            +"account number, no password, wrong password), "
            +"or Connection rate limit exceeded.");
    }
}


text:
<?php

namespace Stfalcon\Bundle\PortfolioBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * StfalconPortfolioBundle
 *
 * @author Stepan Tanasiychuk <ceo@stfalcon.com>
 */
class StfalconPortfolioBundle extends Bundle
{
}


text:
\hypertarget{_u_i_picker_action_sheet_8h}{\section{/\-Users/\-Kalai/\-Desktop/classes/\-U\-I\-Picker\-Action\-Sheet.h File Reference}
\label{_u_i_picker_action_sheet_8h}\index{/\-Users/\-Kalai/\-Desktop/classes/\-U\-I\-Picker\-Action\-Sheet.\-h@{/\-Users/\-Kalai/\-Desktop/classes/\-U\-I\-Picker\-Action\-Sheet.\-h}}
}
{\ttfamily \#import $<$Foundation/\-Foundation.\-h$>$}\\*
\subsection*{Classes}
\begin{DoxyCompactItemize}
\item
class \hyperlink{interface_u_i_picker_action_sheet}{U\-I\-Picker\-Action\-Sheet}
\item
protocol \hyperlink{protocol_u_i_picker_action_sheet_delegate-p}{$<$\-U\-I\-Picker\-Action\-Sheet\-Delegate$>$}
\end{DoxyCompactItemize}


text:
namespace em = enterprise_management;

namespace policy {

namespace {

const char kMetricPolicyUserVerification[] =
    "Enterprise.PolicyUserVerification";

enum class MetricPolicyUserVerification {
  // Gaia id check used, but failed.
  kGaiaIdFailed = 0,
  // Gaia id check used and succeeded.
  kGaiaIdSucceeded = 1,
  // Gaia id is not present and username check failed.
  kUsernameFailed = 2,
  // Gaia id is not present for user and username check succeeded.
  kUsernameSucceeded = 3,
  // Gaia id is not present in policy and username check succeeded.
  kGaiaIdMissingUsernameSucceeded = 4,
  kMaxValue = kGaiaIdMissingUsernameSucceeded,
};

}  // namespace

// static
const char* CloudPolicyValidatorBase::StatusToString(Status status) {
  switch (status) {
    case VALIDATION_OK:
      return "OK";
    case VALIDATION_BAD_INITIAL_SIGNATURE:
      return "BAD_INITIAL_SIGNATURE";
    case VALIDATION_BAD_SIGNATURE:
      return "BAD_SIGNATURE";
    case VALIDATION_ERROR_CODE_PRESENT:
      return "ERROR_CODE_PRESENT";
    case VALIDATION_PAYLOAD_PARSE_ERROR:
      return "PAYLOAD_PARSE_ERROR";
    case VALIDATION_WRONG_POLICY_TYPE:
      return "WRONG_POLICY_TYPE";
    case VALIDATION_WRONG_SETTINGS_ENTITY_ID:
      return "WRONG_SETTINGS_ENTITY_ID";
    case VALIDATION_BAD_TIMESTAMP:
      return "BAD_TIMESTAMP";
    case VALIDATION_BAD_DM_TOKEN:
      return "BAD_DM_TOKEN";
    case VALIDATION_BAD_DEVICE_ID:
      return "BAD_DEVICE_ID";
    case VALIDATION_BAD_USER:
      return "BAD_USER";
    case VALIDATION_POLICY_PARSE_ERROR:
      return "POLICY_PARSE_ERROR";
    case VALIDATION_BAD_KEY_VERIFICATION_SIGNATURE:
      return "BAD_KEY_VERIFICATION_SIGNATURE";
    case VALIDATION_VALUE_WARNING:
      return "VALUE_WARNING";
    case VALIDATION_VALUE_ERROR:
      return "VALUE_ERROR";
    case VALIDATION_STATUS_SIZE:
      return "UNKNOWN";
  }
  return "UNKNOWN";
}

CloudPolicyValidatorBase::ValidationResult::ValidationResult() = default;
CloudPolicyValidatorBase::ValidationResult::~ValidationResult() = default;

CloudPolicyValidatorBase::~CloudPolicyValidatorBase() {}

std::unique_ptr<CloudPolicyValidatorBase::ValidationResult>
CloudPolicyValidatorBase::GetValidationResult() const {
  std::unique_ptr<ValidationResult> result =
      std::make_unique<ValidationResult>();
  result->status = status_;
  result->value_validation_issues = value_validation_issues_;
  result->policy_token = policy_data_->policy_token();
  result->policy_data_signature = policy_->policy_data_signature();
  return result;
}

void CloudPolicyValidatorBase::ValidateTimestamp(
    base::Time not_before,
    ValidateTimestampOption timestamp_option) {
  validation_flags_ |= VALIDATE_TIMESTAMP;
  timestamp_not_before_ = not_before.ToJavaTime();
  timestamp_option_ = timestamp_option;
}

void CloudPolicyValidatorBase::ValidateUser(const AccountId& account_id) {
  validation_flags_ |= VALIDATE_USER;
  username_ = account_id.GetUserEmail();
  gaia_id_ = account_id.GetGaiaId();
  // Always canonicalize when falls back to username check,
  // because it checks only for regular users.
  canonicalize_user_ = true;
}

void CloudPolicyValidatorBase::ValidateUsernameAndGaiaId(
    const std::string& expected_user,
    const std::string& gaia_id) {
  validation_flags_ |= VALIDATE_USER;
  username_ = expected_user;
  gaia_id_ = gaia_id;
  canonicalize_user_ = false;
}

void CloudPolicyValidatorBase::ValidateUsername(
    const std::string& expected_user) {
  validation_flags_ |= VALIDATE_USER;
  username_ = expected_user;
  gaia_id_.clear();
  canonicalize_user_ = false;
}

void CloudPolicyValidatorBase::ValidateDomain(
    const std::string& expected_domain) {
  validation_flags_ |= VALIDATE_DOMAIN;
  domain_ = gaia::CanonicalizeDomain(expected_domain);
}

void CloudPolicyValidatorBase::ValidateDMToken(
    const std::string& expected_dm_token,
    ValidateDMTokenOption dm_token_option) {
  validation_flags_ |= VALIDATE_DM_TOKEN;
  dm_token_ = expected_dm_token;
  dm_token_option_ = dm_token_option;
}

void CloudPolicyValidatorBase::ValidateDeviceId(
    const std::string& expected_device_id,
    ValidateDeviceIdOption device_id_option) {
  validation_flags_ |= VALIDATE_DEVICE_ID;
  device_id_ = expected_device_id;
  device_id_option_ = device_id_option;
}

void CloudPolicyValidatorBase::ValidatePolicyType(
    const std::string& policy_type) {
  validation_flags_ |= VALIDATE_POLICY_TYPE;
  policy_type_ = policy_type;
}

void CloudPolicyValidatorBase::ValidateSettingsEntityId(
    const std::string& settings_entity_id) {
  validation_flags_ |= VALIDATE_ENTITY_ID;
  settings_entity_id_ = settings_entity_id;
}

void CloudPolicyValidatorBase::ValidatePayload() {
  validation_flags_ |= VALIDATE_PAYLOAD;
}

void CloudPolicyValidatorBase::ValidateCachedKey(
    const std::string& cached_key,
    const std::string& cached_key_signature,
    const std::string& owning_domain) {
  validation_flags_ |= VALIDATE_CACHED_KEY;
  set_owning_domain(owning_domain);
  cached_key_ = cached_key;
  cached_key_signature_ = cached_key_signature;
}

void CloudPolicyValidatorBase::ValidateSignature(const std::string& key) {
  validation_flags_ |= VALIDATE_SIGNATURE;
  DCHECK(key_.empty() || key_ == key);
  key_ = key;
}

void CloudPolicyValidatorBase::ValidateSignatureAllowingRotation(
    const std::string& key,
    const std::string& owning_domain) {
  validation_flags_ |= VALIDATE_SIGNATURE;
  DCHECK(key_.empty() || key_ == key);
  key_ = key;
  set_owning_domain(owning_domain);
  allow_key_rotation_ = true;
}

void CloudPolicyValidatorBase::ValidateInitialKey(
    const std::string& owning_domain) {
  validation_flags_ |= VALIDATE_INITIAL_KEY;
  set_owning_domain(owning_domain);
}

void CloudPolicyValidatorBase::ValidateAgainstCurrentPolicy(
    const em::PolicyData* policy_data,
    ValidateTimestampOption timestamp_option,
    ValidateDMTokenOption dm_token_option,
    ValidateDeviceIdOption device_id_option) {
  base::Time last_policy_timestamp;
  std::string expected_dm_token;
  std::string expected_device_id;
  if (policy_data) {
    last_policy_timestamp = base::Time::FromJavaTime(policy_data->timestamp());
    expected_dm_token = policy_data->request_token();
    expected_device_id = policy_data->device_id();
  }
  ValidateTimestamp(last_policy_timestamp, timestamp_option);
  ValidateDMToken(expected_dm_token, dm_token_option);
  ValidateDeviceId(expected_device_id, device_id_option);
}

// static
bool CloudPolicyValidatorBase::VerifySignature(const std::string& data,
                                               const std::string& key,
                                               const std::string& signature,
                                               SignatureType signature_type) {
  crypto::SignatureVerifier verifier;
  crypto::SignatureVerifier::SignatureAlgorithm algorithm;
  switch (signature_type) {
    case em::PolicyFetchRequest::SHA1_RSA:
      algorithm = crypto::SignatureVerifier::RSA_PKCS1_SHA1;
      break;
    case em::PolicyFetchRequest::SHA256_RSA:
      algorithm = crypto::SignatureVerifier::RSA_PKCS1_SHA256;
      break;
    default:
      NOTREACHED() << "Invalid signature type: " << signature_type;
      return false;
  }

  if (!verifier.VerifyInit(algorithm,
                           base::as_bytes(base::make_span(signature)),
                           base::as_bytes(base::make_span(key)))) {
    DLOG(ERROR) << "Invalid verification signature/key format";
    return false;
  }
  verifier.VerifyUpdate(base::as_bytes(base::make_span(data)));
  return verifier.VerifyFinal();
}

CloudPolicyValidatorBase::CloudPolicyValidatorBase(
    std::unique_ptr<em::PolicyFetchResponse> policy_response,
    scoped_refptr<base::SequencedTaskRunner> background_task_runner)
    : validation_flags_(0),
      status_(VALIDATION_OK),
      policy_(std::move(policy_response)),
      timestamp_not_before_(0),
      timestamp_option_(TIMESTAMP_VALIDATED),
      dm_token_option_(DM_TOKEN_REQUIRED),
      device_id_option_(DEVICE_ID_REQUIRED),
      canonicalize_user_(false),
      verification_key_(GetPolicyVerificationKey()),
      allow_key_rotation_(false),
      background_task_runner_(background_task_runner) {
#if BUILDFLAG(IS_CHROMEOS_ASH)
  // Empty `verification_key_` is only allowed on Chrome OS test image when
  // policy key verification is disabled via command line flag.
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kDisablePolicyKeyVerification)) {
    base::SysInfo::CrashIfChromeOSNonTestImage();
    // GetPolicyVerificationKey() returns a non-empty string.
    verification_key_ = absl::nullopt;
  } else {
    DCHECK(verification_key_);
  }
#else
  DCHECK(verification_key_);
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)
}

// static
void CloudPolicyValidatorBase::PostValidationTask(
    std::unique_ptr<CloudPolicyValidatorBase> validator,
    base::OnceClosure completion_callback) {
  const auto task_runner = validator->background_task_runner_;
  task_runner->PostTask(
      FROM_HERE,
      base::BindOnce(&CloudPolicyValidatorBase::PerformValidation,
                     std::move(validator),
                     base::SingleThreadTaskRunner::GetCurrentDefault(),
                     std::move(completion_callback)));
}

// static
void CloudPolicyValidatorBase::PerformValidation(
    std::unique_ptr<CloudPolicyValidatorBase> self,
    scoped_refptr<base::SingleThreadTaskRunner> task_runner,
    base::OnceClosure completion_callback) {
  // Run the validation activities on this thread.
  self->RunValidation();

  // Report completion on |task_runner|.
  task_runner->PostTask(
      FROM_HERE,
      base::BindOnce(&CloudPolicyValidatorBase::ReportCompletion,
                     std::move(self), std::move(completion_callback)));
}

// static
void CloudPolicyValidatorBase::ReportCompletion(
    std::unique_ptr<CloudPolicyValidatorBase> self,
    base::OnceClosure completion_callback) {
  std::move(completion_callback).Run();
}

void CloudPolicyValidatorBase::RunValidation() {
  policy_data_ = std::make_unique<em::PolicyData>();
  RunChecks();
}

CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckProtoPayload(
    google::protobuf::MessageLite* payload) {
  DCHECK(payload);
  if (!policy_data_ || !policy_data_->has_policy_value() ||
      !payload->ParseFromString(policy_data_->policy_value()) ||
      !payload->IsInitialized()) {
    LOG(ERROR) << "Failed to decode policy payload protobuf";
    return VALIDATION_POLICY_PARSE_ERROR;
  }
  return VALIDATION_OK;
}

void CloudPolicyValidatorBase::RunChecks() {
  status_ = VALIDATION_OK;
  if ((policy_->has_error_code() && policy_->error_code() != 200) ||
      (policy_->has_error_message() && !policy_->error_message().empty())) {
    LOG(ERROR) << "Error in policy blob."
               << " code: " << policy_->error_code()
               << " message: " << policy_->error_message();
    status_ = VALIDATION_ERROR_CODE_PRESENT;
    return;
  }

  // Parse policy data.
  if (!policy_data_->ParseFromString(policy_->policy_data()) ||
      !policy_data_->IsInitialized()) {
    LOG(ERROR) << "Failed to parse policy response";
    status_ = VALIDATION_PAYLOAD_PARSE_ERROR;
    return;
  }

  // Table of checks we run. These are sorted by descending severity of the
  // error, s.t. the most severe check will determine the validation status.
  static const struct {
    int flag;
    Status (CloudPolicyValidatorBase::*checkFunction)();
  } kCheckFunctions[] = {
      {VALIDATE_SIGNATURE, &CloudPolicyValidatorBase::CheckSignature},
      {VALIDATE_INITIAL_KEY, &CloudPolicyValidatorBase::CheckInitialKey},
      {VALIDATE_CACHED_KEY, &CloudPolicyValidatorBase::CheckCachedKey},
      {VALIDATE_POLICY_TYPE, &CloudPolicyValidatorBase::CheckPolicyType},
      {VALIDATE_ENTITY_ID, &CloudPolicyValidatorBase::CheckEntityId},
      {VALIDATE_DM_TOKEN, &CloudPolicyValidatorBase::CheckDMToken},
      {VALIDATE_DEVICE_ID, &CloudPolicyValidatorBase::CheckDeviceId},
      {VALIDATE_USER, &CloudPolicyValidatorBase::CheckUser},
      {VALIDATE_DOMAIN, &CloudPolicyValidatorBase::CheckDomain},
      {VALIDATE_TIMESTAMP, &CloudPolicyValidatorBase::CheckTimestamp},
      {VALIDATE_PAYLOAD, &CloudPolicyValidatorBase::CheckPayload},
      {VALIDATE_VALUES, &CloudPolicyValidatorBase::CheckValues},
  };

  for (size_t i = 0; i < std::size(kCheckFunctions); ++i) {
    if (validation_flags_ & kCheckFunctions[i].flag) {
      status_ = (this->*(kCheckFunctions[i].checkFunction))();
      if (status_ != VALIDATION_OK)
        break;
    }
  }
}

// Verifies the |new_public_key_verification_signature_deprecated| for the
// |new_public_key| in the policy blob.
bool CloudPolicyValidatorBase::CheckNewPublicKeyVerificationSignature() {
#if BUILDFLAG(IS_CHROMEOS_ASH)
  // Skip verification if the key is empty (disabled via command line).
  if (!verification_key_) {
    return true;
  }
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)

  if (!policy_->has_new_public_key_verification_signature_deprecated()) {
    // Policy does not contain a verification signature, so log an error.
    LOG(ERROR) << "Policy is missing public_key_verification_signature";
    return false;
  }

  if (!CheckVerificationKeySignature(
          policy_->new_public_key(), verification_key_.value(),
          policy_->new_public_key_verification_signature_deprecated())) {
    LOG(ERROR) << "Signature verification failed";
    return false;
  }
  // Signature verification succeeded - return success to the caller.
  DVLOG(1) << "Signature verification succeeded";
  return true;
}

bool CloudPolicyValidatorBase::CheckVerificationKeySignature(
    const std::string& key,
    const std::string& verification_key,
    const std::string& signature) {
  DCHECK(!verification_key.empty());
  em::DEPRECATEDPolicyPublicKeyAndDomain signed_data;
  signed_data.set_new_public_key(key);

  // If no owning_domain_ supplied, try extracting the domain from the policy
  // itself (this happens on certain platforms during startup, when we validate
  // cached policy before prefs are loaded).
  std::string domain =
      owning_domain_.empty() ? ExtractDomainFromPolicy() : owning_domain_;
  if (domain.empty()) {
    LOG(ERROR) << "Policy does not contain a domain";
    return false;
  }
  signed_data.set_domain(domain);
  std::string signed_data_as_string;
  if (!signed_data.SerializeToString(&signed_data_as_string)) {
    DLOG(ERROR) << "Could not serialize verification key to string";
    return false;
  }
  return VerifySignature(signed_data_as_string, verification_key, signature,
                         em::PolicyFetchRequest::SHA256_RSA);
}

std::string CloudPolicyValidatorBase::ExtractDomainFromPolicy() {
  std::string domain;
  if (policy_data_->has_username()) {
    domain = gaia::ExtractDomainName(
        gaia::CanonicalizeEmail(gaia::SanitizeEmail(policy_data_->username())));
  }
  return domain;
}

void CloudPolicyValidatorBase::set_owning_domain(
    const std::string& owning_domain) {
  // Make sure we aren't overwriting the owning domain with a different one.
  DCHECK(owning_domain_.empty() || owning_domain_ == owning_domain);
  owning_domain_ = owning_domain;
}

CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckSignature() {
  const std::string* signature_key = &key_;
  if (policy_->has_new_public_key() && allow_key_rotation_) {
    signature_key = &policy_->new_public_key();
    if (!policy_->has_new_public_key_signature() ||
        !VerifySignature(policy_->new_public_key(), key_,
                         policy_->new_public_key_signature(),
                         em::PolicyFetchRequest::SHA1_RSA)) {
      LOG(ERROR) << "New public key rotation signature verification failed";
      return VALIDATION_BAD_SIGNATURE;
    }

    if (!CheckNewPublicKeyVerificationSignature()) {
      LOG(ERROR) << "New public key root verification failed";
      return VALIDATION_BAD_KEY_VERIFICATION_SIGNATURE;
    }
  }

  if (!policy_->has_policy_data_signature() ||
      !VerifySignature(policy_->policy_data(), *signature_key,
                       policy_->policy_data_signature(),
                       em::PolicyFetchRequest::SHA1_RSA)) {
    LOG(ERROR) << "Policy signature validation failed";
    return VALIDATION_BAD_SIGNATURE;
  }

  return VALIDATION_OK;
}

CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckInitialKey() {
  if (!policy_->has_new_public_key() || !policy_->has_policy_data_signature() ||
      !VerifySignature(policy_->policy_data(), policy_->new_public_key(),
                       policy_->policy_data_signature(),
                       em::PolicyFetchRequest::SHA1_RSA)) {
    LOG(ERROR) << "Initial policy signature validation failed";
    return VALIDATION_BAD_INITIAL_SIGNATURE;
  }

  if (!CheckNewPublicKeyVerificationSignature()) {
    LOG(ERROR) << "Initial policy root signature validation failed";
    return VALIDATION_BAD_KEY_VERIFICATION_SIGNATURE;
  }
  return VALIDATION_OK;
}

CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckCachedKey() {
#if BUILDFLAG(IS_CHROMEOS_ASH)
  // Skip verification if the key is empty (disabled via command line).
  if (!verification_key_) {
    return VALIDATION_OK;
  }
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)

  if (!CheckVerificationKeySignature(cached_key_, verification_key_.value(),
                                     cached_key_signature_)) {
    LOG(ERROR) << "Cached key signature verification failed";
    return VALIDATION_BAD_KEY_VERIFICATION_SIGNATURE;
  } else {
    DVLOG(1) << "Cached key signature verification succeeded";
  }
  return VALIDATION_OK;
}

CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckPolicyType() {
  if (!policy_data_->has_policy_type() ||
      policy_data_->policy_type() != policy_type_) {
    LOG(ERROR) << "Wrong policy type " << policy_data_->policy_type();
    return VALIDATION_WRONG_POLICY_TYPE;
  }

  return VALIDATION_OK;
}

CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckEntityId() {
  if (!policy_data_->has_settings_entity_id() ||
      policy_data_->settings_entity_id() != settings_entity_id_) {
    LOG(ERROR) << "Wrong settings_entity_id "
               << policy_data_->settings_entity_id() << ", expected "
               << settings_entity_id_;
    return VALIDATION_WRONG_SETTINGS_ENTITY_ID;
  }

  return VALIDATION_OK;
}

CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckTimestamp() {
  if (timestamp_option_ == TIMESTAMP_NOT_VALIDATED)
    return VALIDATION_OK;

  if (!policy_data_->has_timestamp()) {
    LOG(ERROR) << "Policy timestamp missing";
    return VALIDATION_BAD_TIMESTAMP;
  }

  if (policy_data_->timestamp() < timestamp_not_before_) {
    LOG(ERROR) << "Policy too old: " << policy_data_->timestamp();
    return VALIDATION_BAD_TIMESTAMP;
  }

  return VALIDATION_OK;
}

CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckDMToken() {
  if (dm_token_option_ == DM_TOKEN_REQUIRED &&
      (!policy_data_->has_request_token() ||
       policy_data_->request_token().empty())) {
    LOG(ERROR) << "Empty DM token encountered - expected: " << dm_token_;
    return VALIDATION_BAD_DM_TOKEN;
  }
  if (!dm_token_.empty() && policy_data_->request_token() != dm_token_) {
    LOG(ERROR) << "Invalid DM token: " << policy_data_->request_token()
               << " - expected: " << dm_token_;
    return VALIDATION_BAD_DM_TOKEN;
  }

  return VALIDATION_OK;
}

CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckDeviceId() {
  if (device_id_option_ == DEVICE_ID_REQUIRED &&
      (!policy_data_->has_device_id() || policy_data_->device_id().empty())) {
    LOG(ERROR) << "Empty device id encountered - expected: " << device_id_;
    return VALIDATION_BAD_DEVICE_ID;
  }
  if (!device_id_.empty() && policy_data_->device_id() != device_id_) {
    LOG(ERROR) << "Invalid device id: " << policy_data_->device_id()
               << " - expected: " << device_id_;
    return VALIDATION_BAD_DEVICE_ID;
  }
  return VALIDATION_OK;
}

CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckUser() {
  if (!policy_data_->has_username() && !policy_data_->has_gaia_id()) {
    LOG(ERROR) << "Policy is missing user name and gaia id";
    return VALIDATION_BAD_USER;
  }

  if (policy_data_->has_gaia_id() && !policy_data_->gaia_id().empty() &&
      !gaia_id_.empty()) {
    std::string expected = gaia_id_;
    std::string actual = policy_data_->gaia_id();

    if (expected != actual) {
      LOG(ERROR) << "Invalid gaia id: " << actual;
      UMA_HISTOGRAM_ENUMERATION(kMetricPolicyUserVerification,
                                MetricPolicyUserVerification::kGaiaIdFailed);
      return VALIDATION_BAD_USER;
    }
    UMA_HISTOGRAM_ENUMERATION(kMetricPolicyUserVerification,
                              MetricPolicyUserVerification::kGaiaIdSucceeded);
  } else {
    std::string expected = username_;
    std::string actual = policy_data_->username();
    if (canonicalize_user_) {
      expected = gaia::CanonicalizeEmail(gaia::SanitizeEmail(expected));
      actual = gaia::CanonicalizeEmail(gaia::SanitizeEmail(actual));
    }

    if (expected != actual) {
      LOG(ERROR) << "Invalid user name " << actual << ", expected " << expected;
      UMA_HISTOGRAM_ENUMERATION(kMetricPolicyUserVerification,
                                MetricPolicyUserVerification::kUsernameFailed);
      return VALIDATION_BAD_USER;
    }
    if (gaia_id_.empty()) {
      UMA_HISTOGRAM_ENUMERATION(
          kMetricPolicyUserVerification,
          MetricPolicyUserVerification::kUsernameSucceeded);
    } else {
      UMA_HISTOGRAM_ENUMERATION(
          kMetricPolicyUserVerification,
          MetricPolicyUserVerification::kGaiaIdMissingUsernameSucceeded);
    }
  }

  return VALIDATION_OK;
}

CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckDomain() {
  std::string policy_domain = ExtractDomainFromPolicy();
  if (policy_domain.empty()) {
    LOG(ERROR) << "Policy is missing user name";
    return VALIDATION_BAD_USER;
  }

  if (domain_ != policy_domain) {
    LOG(ERROR) << "Invalid domain name " << policy_domain << " - " << domain_;
    return VALIDATION_BAD_USER;
  }

  return VALIDATION_OK;
}

template class CloudPolicyValidator<em::CloudPolicySettings>;

#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
template class CloudPolicyValidator<em::ExternalPolicyData>;
#endif

}  // namespace policy


text:
package org.apache.camel.test.cdi;

import java.lang.annotation.Annotation;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.enterprise.inject.spi.Annotated;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InjectionPoint;

final class FrameworkMethodInjectionPoint implements InjectionPoint {

    private final Method method;

    private final FrameworkAnnotatedParameter annotated;

    private final Type type;

    private final Set<Annotation> qualifiers;

    FrameworkMethodInjectionPoint(Method method, int position, BeanManager manager) {
        this.method = method;
        this.annotated = new FrameworkAnnotatedParameter(method, position, manager);
        this.type = method.getGenericParameterTypes()[position];
        this.qualifiers = new HashSet<>();
        for (Annotation annotation : method.getParameterAnnotations()[position]) {
            if (manager.isQualifier(annotation.annotationType())) {
                qualifiers.add(annotation);
            }
        }
    }

    @Override
    public Bean<?> getBean() {
        return null;
    }

    @Override
    public Member getMember() {
        return method;
    }

    @Override
    public Set<Annotation> getQualifiers() {
        return Collections.unmodifiableSet(qualifiers);
    }

    @Override
    public Type getType() {
        return type;
    }

    @Override
    public boolean isDelegate() {
        return false;
    }

    @Override
    public boolean isTransient() {
        return false;
    }

    @Override
    public Annotated getAnnotated() {
        return annotated;
    }
}