text:
package org.apache.tomcat.websocket;

import java.net.URI;
import java.util.Queue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import javax.websocket.ClientEndpointConfig;
import javax.websocket.ContainerProvider;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

import org.junit.Assert;
import org.junit.Test;

import org.apache.catalina.Context;
import org.apache.catalina.servlets.DefaultServlet;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.websocket.TesterMessageCountClient.BasicText;
import org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint;

public class TestWebSocketFrameClient extends WebSocketBaseTest {

    @Test
    public void testConnectToServerEndpoint() throws Exception {
        Tomcat tomcat = getTomcatInstance();
        // No file system docBase required
        Context ctx = tomcat.addContext("", null);
        ctx.addApplicationListener(TesterFirehoseServer.Config.class.getName());
        Tomcat.addServlet(ctx, "default", new DefaultServlet());
        ctx.addServletMapping("/", "default");

        tomcat.start();

        WebSocketContainer wsContainer =
                ContainerProvider.getWebSocketContainer();
        ClientEndpointConfig clientEndpointConfig =
                ClientEndpointConfig.Builder.create().build();
        Session wsSession = wsContainer.connectToServer(
                TesterProgrammaticEndpoint.class,
                clientEndpointConfig,
                new URI("ws://localhost:" + getPort() +
                        TesterFirehoseServer.Config.PATH));
        CountDownLatch latch =
                new CountDownLatch(TesterFirehoseServer.MESSAGE_COUNT);
        BasicText handler = new BasicText(latch);
        wsSession.addMessageHandler(handler);
        wsSession.getBasicRemote().sendText("Hello");

        System.out.println("Sent Hello message, waiting for data");

        // Ignore the latch result as the message count test below will tell us
        // if the right number of messages arrived
        handler.getLatch().await(TesterFirehoseServer.WAIT_TIME_MILLIS,
                TimeUnit.MILLISECONDS);

        Queue<String> messages = handler.getMessages();
        Assert.assertEquals(
                TesterFirehoseServer.MESSAGE_COUNT, messages.size());
        for (String message : messages) {
            Assert.assertEquals(TesterFirehoseServer.MESSAGE, message);
        }
    }
    @Test
    public void testConnectToRootEndpoint() throws Exception {
        Tomcat tomcat = getTomcatInstance();
        // No file system docBase required
        Context ctx = tomcat.addContext("", null);
        ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
        Tomcat.addServlet(ctx, "default", new DefaultServlet());
        ctx.addServletMapping("/", "default");
        Context ctx2 = tomcat.addContext("/foo", null);
        ctx2.addApplicationListener(TesterEchoServer.Config.class.getName());
        Tomcat.addServlet(ctx2, "default", new DefaultServlet());
        ctx2.addServletMapping("/", "default");

        tomcat.start();

        echoTester("");
        echoTester("/");
        echoTester("/foo");
        echoTester("/foo/");
    }

    public void echoTester(String path) throws Exception {
        WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();
        ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
        Session wsSession = wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
                clientEndpointConfig, new URI("ws://localhost:" + getPort() + path));
        CountDownLatch latch = new CountDownLatch(1);
        BasicText handler = new BasicText(latch);
        wsSession.addMessageHandler(handler);
        wsSession.getBasicRemote().sendText("Hello");

        boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
        Assert.assertTrue(latchResult);

        Queue<String> messages = handler.getMessages();
        Assert.assertEquals(1, messages.size());
        for (String message : messages) {
            Assert.assertEquals("Hello", message);
        }
        wsSession.close();
    }

}


text:
require 'spec_helper'

RSpec.describe OneviewSDK::API1600::C7000::EthernetNetwork do
  include_context 'shared context'

  it 'inherits from OneviewSDK::API1200::C7000::EthernetNetwork' do
    expect(described_class).to be < OneviewSDK::API1200::C7000::EthernetNetwork
  end
end

redpajama_set_name: RedPajamaGithub


text:
id: 587d7b8f367417b2b2512b61
title: Usar o método map para extrair dados de um array
challengeType: 1
forumTopicId: 18214
dashedName: use-the-map-method-to-extract-data-from-an-array
---

# --description--

Até então nós aprendemos a usar funções puras para evitar efeitos colaterais em um programa. Vimos também que há valor em fazer funções dependerem apenas de suas entradas.

Este é apenas o começo. Como o nome sugere, programação funcional orbita uma teoria de funções.

Faz sentido conseguir passar funções como argumento a outras funções e retorná-las de outras funções. Funções são consideradas <dfn>objetos de primeira classe</dfn> em JavaScript e podem ser usadas como qualquer outro objeto. Elas podem ser salvas em variáveis, objetos ou passadas como argumento a funções.

Vamos começar com algumas funções simples de array. Alguns métodos no protótipo de objetos array. Neste exercício estamos de olho em `Array.prototype.map()`, ou simplesmente `map`.

O método `map` percorre cada item de um array e retorna um novo array cujos elementos são os resultados da chamada da função de callback para cada item. Isso tudo acontece sem modificar o array original.

A função de callback é chamada com três argumentos. O primeiro argumento é o elemento que está a ser processado. O segundo é o índice deste elemento e o terceiro é o array do qual `map` foi chamado.

Abaixo você vê um exemplo do `map` sendo usado do array `users` para retornar um novo array apenas com os nomes dos usuários. O exemplo usa apenas o primeiro argumento da função de callback por simplicidade.

```js
const users = [
  { name: 'John', age: 34 },
  { name: 'Amy', age: 20 },
  { name: 'camperCat', age: 10 }
];

const names = users.map(user => user.name);
console.log(names);
```

O console mostraria o valor `[ 'John', 'Amy', 'camperCat' ]`.

# --instructions--

A variável `watchList` armazena um array de objetos com informações de diversos filmes. Use o `map` na `watchList` para atribuir uma nova matriz de objetos à variável</code>ratins`. Cada filme no novo array deve ter apenas um <code>title` com o nome do filme, e uma chave `rating` com a classificação do IMDB. O código atual no editor usa um loop `for` para fazer isso, então você deve substituir o laço com sua expressão `map`.

# --hints--

A variável `watchList` não deve ser alterada.

```js
assert(
  watchList[0].Title === 'Inception' && watchList[4].Director == 'James Cameron'
);
```

Você não deve usar loops `for`.

```js
assert(!code.match(/for\s*?\([\s\S]*?\)/));
```

Você deve usar o método `map`.

```js
assert(code.match(/\.map/g));
```

`ratings` deve ser igual a `[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]`.

```js
assert.deepEqual(ratings, [
  { title: 'Inception', rating: '8.8' },
  { title: 'Interstellar', rating: '8.6' },
  { title: 'The Dark Knight', rating: '9.0' },
  { title: 'Batman Begins', rating: '8.3' },
  { title: 'Avatar', rating: '7.9' }
]);
```

# --seed--

## --seed-contents--

```js
// The global variable
var watchList = [
  {
    "Title": "Inception",
    "Year": "2010",
    "Rated": "PG-13",
    "Released": "16 Jul 2010",
    "Runtime": "148 min",
    "Genre": "Action, Adventure, Crime",
    "Director": "Christopher Nolan",
    "Writer": "Christopher Nolan",
    "Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Elliot Page, Tom Hardy",
    "Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
    "Language": "English, Japanese, French",
    "Country": "USA, UK",
    "Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
    "Metascore": "74",
    "imdbRating": "8.8",
    "imdbVotes": "1,446,708",
    "imdbID": "tt1375666",
    "Type": "movie",
    "Response": "True"
  },
  {
    "Title": "Interstellar",
    "Year": "2014",
    "Rated": "PG-13",
    "Released": "07 Nov 2014",
    "Runtime": "169 min",
    "Genre": "Adventure, Drama, Sci-Fi",
    "Director": "Christopher Nolan",
    "Writer": "Jonathan Nolan, Christopher Nolan",
    "Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
    "Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
    "Language": "English",
    "Country": "USA, UK",
    "Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
    "Metascore": "74",
    "imdbRating": "8.6",
    "imdbVotes": "910,366",
    "imdbID": "tt0816692",
    "Type": "movie",
    "Response": "True"
  },
  {
    "Title": "The Dark Knight",
    "Year": "2008",
    "Rated": "PG-13",
    "Released": "18 Jul 2008",
    "Runtime": "152 min",
    "Genre": "Action, Adventure, Crime",
    "Director": "Christopher Nolan",
    "Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
    "Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
    "Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
    "Language": "English, Mandarin",
    "Country": "USA, UK",
    "Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
    "Metascore": "82",
    "imdbRating": "9.0",
    "imdbVotes": "1,652,832",
    "imdbID": "tt0468569",
    "Type": "movie",
    "Response": "True"
  },
  {
    "Title": "Batman Begins",
    "Year": "2005",
    "Rated": "PG-13",
    "Released": "15 Jun 2005",
    "Runtime": "140 min",
    "Genre": "Action, Adventure",
    "Director": "Christopher Nolan",
    "Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
    "Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
    "Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
    "Language": "English, Urdu, Mandarin",
    "Country": "USA, UK",
    "Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
    "Metascore": "70",
    "imdbRating": "8.3",
    "imdbVotes": "972,584",
    "imdbID": "tt0372784",
    "Type": "movie",
    "Response": "True"
  },
  {
    "Title": "Avatar",
    "Year": "2009",
    "Rated": "PG-13",
    "Released": "18 Dec 2009",
    "Runtime": "162 min",
    "Genre": "Action, Adventure, Fantasy",
    "Director": "James Cameron",
    "Writer": "James Cameron",
    "Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
    "Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
    "Language": "English, Spanish",
    "Country": "USA, UK",
    "Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
    "Metascore": "83",
    "imdbRating": "7.9",
    "imdbVotes": "876,575",
    "imdbID": "tt0499549",
    "Type": "movie",
    "Response": "True"
  }
];

// Only change code below this line

var ratings = [];
for(var i=0; i < watchList.length; i++){
  ratings.push({title: watchList[i]["Title"],  rating: watchList[i]["imdbRating"]});
}

// Only change code above this line

console.log(JSON.stringify(ratings));
```

# --solutions--

```js
// The global variable
var watchList = [
  {
    "Title": "Inception",
    "Year": "2010",
    "Rated": "PG-13",
    "Released": "16 Jul 2010",
    "Runtime": "148 min",
    "Genre": "Action, Adventure, Crime",
    "Director": "Christopher Nolan",
    "Writer": "Christopher Nolan",
    "Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Elliot Page, Tom Hardy",
    "Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
    "Language": "English, Japanese, French",
    "Country": "USA, UK",
    "Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
    "Metascore": "74",
    "imdbRating": "8.8",
    "imdbVotes": "1,446,708",
    "imdbID": "tt1375666",
    "Type": "movie",
    "Response": "True"
  },
  {
    "Title": "Interstellar",
    "Year": "2014",
    "Rated": "PG-13",
    "Released": "07 Nov 2014",
    "Runtime": "169 min",
    "Genre": "Adventure, Drama, Sci-Fi",
    "Director": "Christopher Nolan",
    "Writer": "Jonathan Nolan, Christopher Nolan",
    "Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
    "Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
    "Language": "English",
    "Country": "USA, UK",
    "Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
    "Metascore": "74",
    "imdbRating": "8.6",
    "imdbVotes": "910,366",
    "imdbID": "tt0816692",
    "Type": "movie",
    "Response": "True"
  },
  {
    "Title": "The Dark Knight",
    "Year": "2008",
    "Rated": "PG-13",
    "Released": "18 Jul 2008",
    "Runtime": "152 min",
    "Genre": "Action, Adventure, Crime",
    "Director": "Christopher Nolan",
    "Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
    "Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
    "Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
    "Language": "English, Mandarin",
    "Country": "USA, UK",
    "Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
    "Metascore": "82",
    "imdbRating": "9.0",
    "imdbVotes": "1,652,832",
    "imdbID": "tt0468569",
    "Type": "movie",
    "Response": "True"
  },
  {
    "Title": "Batman Begins",
    "Year": "2005",
    "Rated": "PG-13",
    "Released": "15 Jun 2005",
    "Runtime": "140 min",
    "Genre": "Action, Adventure",
    "Director": "Christopher Nolan",
    "Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
    "Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
    "Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
    "Language": "English, Urdu, Mandarin",
    "Country": "USA, UK",
    "Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
    "Metascore": "70",
    "imdbRating": "8.3",
    "imdbVotes": "972,584",
    "imdbID": "tt0372784",
    "Type": "movie",
    "Response": "True"
  },
  {
    "Title": "Avatar",
    "Year": "2009",
    "Rated": "PG-13",
    "Released": "18 Dec 2009",
    "Runtime": "162 min",
    "Genre": "Action, Adventure, Fantasy",
    "Director": "James Cameron",
    "Writer": "James Cameron",
    "Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
    "Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
    "Language": "English, Spanish",
    "Country": "USA, UK",
    "Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
    "Metascore": "83",
    "imdbRating": "7.9",
    "imdbVotes": "876,575",
    "imdbID": "tt0499549",
    "Type": "movie",
    "Response": "True"
  }
];

var ratings = watchList.map(function(movie) {
  return {
    title: movie["Title"],
    rating: movie["imdbRating"]
  }
});
```


text:
package com.twu.biblioteca;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class UserTest {
    String libraryNumber = "000-0000";
    String password = "achal";
    String name = "Achal";
    String emailid = "achal@gmail.com";
    String phoneNumber = "1234567890";
    User user = new User(libraryNumber, password, name, emailid, phoneNumber);

    @Test
    public void testUserCreation(){
        assertEquals(libraryNumber, user.getLibraryNumber());
        assertEquals(password, user.getPassword());
        assertEquals(name, user.getName());
        assertEquals(emailid, user.getEmailid());
        assertEquals(phoneNumber, user.getPhoneNumber());
    }

    @Test
    public void testContactInformation(){
        String info = name + " | " + emailid + " | " + phoneNumber;
        assertEquals(info, user.contactInformation());
    }
}


text:
<?php

namespace BrasseursApplis\Arrows\Id;

use Assert\Assertion;
use Assert\AssertionFailedException;

class ResearcherId implements \JsonSerializable
{
    /** @var string */
    private $id;

    /**
     * ScenarioTemplateId constructor.
     *
     * @param string $id
     *
     * @throws AssertionFailedException
     */
    public function __construct($id)
    {
        Assertion::uuid($id);

        $this->id = (string) $id;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return $this->id;
    }

    /**
     * Specify data which should be serialized to JSON
     *
     * @link  http://php.net/manual/en/jsonserializable.jsonserialize.php
     * @return mixed data which can be serialized by <b>json_encode</b>,
     *        which is a value of any type other than a resource.
     * @since 5.4.0
     */
    public function jsonSerialize()
    {
        return $this->id;
    }
}


text:
<?php

namespace Crucial\Service;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\HandlerStack;
use Crucial\Service\Chargify\Exception\BadMethodCallException;
use Crucial\Service\Chargify\Adjustment;
use Crucial\Service\Chargify\Charge;
use Crucial\Service\Chargify\Component;
use Crucial\Service\Chargify\Coupon;
use Crucial\Service\Chargify\Customer;
use Crucial\Service\Chargify\Event;
use Crucial\Service\Chargify\Product;
use Crucial\Service\Chargify\Refund;
use Crucial\Service\Chargify\Statement;
use Crucial\Service\Chargify\Stats;
use Crucial\Service\Chargify\Subscription;
use Crucial\Service\Chargify\Transaction;
use Crucial\Service\Chargify\Webhook;

class Chargify
{
    /**
     * Version
     */
    const VERSION = '0.1.1';

    /**
     * Guzzle http client
     *
     * @var Client
     */
    private $httpClient;

    /**
     * The complete hostname; e.g. "my-app-subdomain.chargify.com",
     * not just "my-app-subdomain"
     *
     * @var string
     */
    protected $hostname;

    /**
     * Your http authentication password. The password is always "x".
     *
     * @var string
     */
    protected $password = 'x';

    /**
     * Your api key
     *
     * @var string
     */
    protected $apiKey;

    /**
     * Shared key
     *
     * @var string
     */
    protected $sharedKey;

    /**
     * Timeout
     *
     * @var int
     */
    protected $timeout = 10;

    /*
     * json
     *
     * @var string
     */
    protected $format = 'json';

    /**
     * Config used in constructor.
     *
     * @var array
     */
    protected $config;

    /**
     * @var Response|false|null
     */
    protected $lastResponse;

    /**
     * Initialize the service
     *
     * @param array $config
     */
    public function __construct($config)
    {
        // store a copy
        $this->config = $config;

        // set individual properties
        $this->hostname  = trim($config['hostname'], '/');
        $this->apiKey    = $config['api_key'];
        $this->sharedKey = $config['shared_key'];

        if (!empty($config['timeout'])) {
            $this->timeout   = $config['timeout'];
        }

        $this->httpClient = new Client([
            'base_uri'        => 'https://' . $this->hostname . '/',
            'handler'         => HandlerStack::create(),
            'timeout'         => $this->timeout,
            'allow_redirects' => false,
            'auth'            => [$this->apiKey, $this->password],
            'headers'         => [
                'User-Agent'   => 'chargify-sdk-php/' . self::VERSION . ' (https://github.com/chargely/chargify-sdk-php)',
                'Content-Type' => 'application/' . $this->format
            ]
        ]);
    }

    /**
     * @return Client
     */
    public function getHttpClient()
    {
        return $this->httpClient;
    }

    /**
     * Returns config sent in constructor
     *
     * @return array
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * Send the request to Chargify
     *
     * @param string $path   URL path we are requesting such as: /subscriptions/<subscription_id>/adjustments
     * @param string $method GET, POST, PUT, DELETE
     * @param string $rawData
     * @param array  $params
     *
     * @return Response|FALSE Response object or FALSE if there was no response (networking error, timeout, etc.)
     */
    public function request($path, $method, $rawData = null, $params = [])
    {
        $method  = strtoupper($method);
        $path    = ltrim($path, '/');
        $path    = $path . '.' . $this->format;
        $client  = $this->getHttpClient();
        $method  = strtoupper($method);
        $options = [
            'query' => $params,
            'body' => null,
        ];

        $request = new Request($method, $path);

        if (in_array($method, array('POST', 'PUT'))) {
            if (null === $rawData) {
                throw new BadMethodCallException('You must send raw data in a POST or PUT request');
            }
        }

        if (!empty($rawData)) {
            $options['body'] = Psr7\stream_for($rawData);
        }

        try {
            $response = $client->send($request, $options);
        } catch (RequestException $e) {
            if ($e->hasResponse()) {
                $response = $e->getResponse();
            } else {
                $response = false;
            }
        }

        $this->lastResponse = $response;

        return $response;
    }

    /**
     * @return Response
     */
    public function getLastResponse()
    {
        return $this->lastResponse;
    }

    /**
     * Helper for instantiating an instance of Customer
     *
     * @return Customer
     */
    public function customer()
    {
        return new Customer($this);
    }

    /**
     * Helper for instantiating an instance of Subscription
     *
     * @return Subscription
     */
    public function subscription()
    {
        return new Subscription($this);
    }

    /**
     * Helper for instantiating an instance of Product
     *
     * @return Product
     */
    public function product()
    {
        return new Product($this);
    }

    /**
     * Helper for instantiating an instance of Adjustment
     *
     * @return Adjustment
     */
    public function adjustment()
    {
        return new Adjustment($this);
    }

    /**
     * Helper for instantiating an instance of Charge
     *
     * @return Charge
     */
    public function charge()
    {
        return new Charge($this);
    }

    /**
     * Helper for instantiating an instance of Component
     *
     * @return Component
     */
    public function component()
    {
        return new Component($this);
    }

    /**
     * Helper for instantiating an instance of Coupon
     *
     * @return Coupon
     */
    public function coupon()
    {
        return new Coupon($this);
    }

    /**
     * Helper for instantiating an instance of Transaction
     *
     * @return Transaction
     */
    public function transaction()
    {
        return new Transaction($this);
    }

    /**
     * Helper for instantiating an instance of Refund
     *
     * @return Refund
     */
    public function refund()
    {
        return new Refund($this);
    }

    /**
     * Helper for instantiating an instance of Statement
     *
     * @return Statement
     */
    public function statement()
    {
        return new Statement($this);
    }

    /**
     * Helper for instantiating an instance of Event
     *
     * @return Event
     */
    public function event()
    {
        return new Event($this);
    }

    /**
     * Helper for instantiating an instance of Webhook
     *
     * @return Webhook
     */
    public function webhook()
    {
        return new Webhook($this);
    }

    /**
     * Helper for instantiating an instance of Stats
     *
     * @return Stats
     */
    public function stats()
    {
        return new Stats($this);
    }
}


text:
<model>
    <mount>//OPNsense/Firewall/Alias</mount>
    <version>1.0.1</version>
    <description>
        Firewall aliases
    </description>
    <items>
        <geoip>
            <url type="UrlField">
            </url>
        </geoip>
        <aliases>
            <alias type=".\AliasField">
                <enabled type="BooleanField">
                    <default>1</default>
                    <Required>Y</Required>
                </enabled>
                <name type=".\AliasNameField">
                    <Required>Y</Required>
                    <Constraints>
                        <check001>
                            <ValidationMessage>An alias with this name already exists.</ValidationMessage>
                            <type>UniqueConstraint</type>
                        </check001>
                    </Constraints>
                </name>
                <type type="OptionField">
                    <Required>Y</Required>
                    <default>alert</default>
                    <OptionValues>
                        <host>Host(s)</host>
                        <network>Network(s)</network>
                        <port>Port(s)</port>
                        <url>URL (IPs)</url>
                        <urltable>URL Table (IPs)</urltable>
                        <geoip>GeoIP</geoip>
                        <networkgroup>Network group</networkgroup>
                        <mac>MAC address</mac>
                        <asn>BGP ASN</asn>
                        <dynipv6host>Dynamic IPv6 Host</dynipv6host>
                        <internal>Internal (automatic)</internal>
                        <external>External (advanced)</external>
                    </OptionValues>
                    <Constraints>
                        <check001>
                            <reference>interface.check001</reference>
                        </check001>
                    </Constraints>
                </type>
                <proto type="OptionField">
                    <Multiple>Y</Multiple>
                    <OptionValues>
                        <IPv4>IPv4</IPv4>
                        <IPv6>IPv6</IPv6>
                    </OptionValues>
                </proto>
                <interface type="InterfaceField">
                  <Constraints>
                      <check001>
                          <ValidationMessage>IPv6 Dynamic Host require an interface to track.</ValidationMessage>
                          <type>SetIfConstraint</type>
                          <field>type</field>
                          <check>dynipv6host</check>
                      </check001>
                  </Constraints>
                </interface>
                <counters type="BooleanField">
                    <default>0</default>
                </counters>
                <updatefreq type="NumericField">
                    <ValidationMessage>Days and hours should be numeric values or left empty</ValidationMessage>
                </updatefreq>
                <content type=".\AliasContentField"/>
                <categories type="ModelRelationField">
                    <Model>
                        <rulesets>
                            <source>OPNsense.Firewall.Category</source>
                            <items>categories.category</items>
                            <display>name</display>
                        </rulesets>
                    </Model>
                    <multiple>Y</multiple>
                    <ValidationMessage>Related category not found.</ValidationMessage>
                    <Required>N</Required>
                </categories>
                <description type="TextField">
                    <Required>N</Required>
                    <mask>/^(.){1,255}$/u</mask>
                    <ValidationMessage>Description should be a string between 1 and 255 characters</ValidationMessage>
                </description>
            </alias>
        </aliases>
    </items>
</model>


text:
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'(?P<podcast_slug>[\w-]+)/(?P<episode_id>[\w-]+)$', views.ep_comment_box, name='ep_comment_box'),
    url(r'(?P<podcast_slug>[\w-]+)$', views.podcast_comment_box, name='podcast_comment_box'),
]


text:
import React from 'react';
import {mount} from 'enzyme';
import sinon from 'sinon';
import test from 'tape';

import TextField from '../../../../../frontend/app/components/ui/text-field';

test('Rendering default TextField', (t) => {
  const field = mount(
    <TextField />
  );

  t.equal(field.find('input').length, 1, 'Contains an input element');
  t.equal(field.find('input').props().className, 'text-field transition ', 'Default class is applied');

  t.end();
});

test('TextField change handler', (t) => {
  const onChangeSpy = sinon.spy();
  const field = mount(
    <TextField
      onChange={onChangeSpy}
    />
  );

  t.notOk(onChangeSpy.called, 'Change handler is not called');
  field.find('input').simulate('change', {target: {value: 'text'}});
  t.ok(onChangeSpy.called, 'Change handler is triggered');

  t.end();
});

test('Setting and getting TextField contents', (t) => {
  const field = mount(
    <TextField />
  );

  t.equal(field.instance().getValue(), '', 'Initially empty contents');
  field.instance().setValue('text');
  t.equal(field.instance().getValue(), 'text', 'Contents are properly modified');

  t.end();
});


text:
class Grouping < ActiveRecord::Base
  belongs_to :board
  belongs_to :video

  validates :board_id, :video_id, presence: true

  validates :board_id, uniqueness: {scope: :video_id}
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<title>
Code breakdown
</title>

<colgroup>
<col id="soyc-splitpoint-type-col">
<col id="soyc-splitpoint-size-col">
</colgroup>

Type

Size (Bytes)

% of total

allOther

392,298

83.3%

jre

33,369

7.1%

gwtLang

30,780

6.5%

rpcGen

13,373

2.8%

rpcUser

1,036

0.2%

14865 bytes occupied by Strings

9333 bytes of the JavaScript output cannot be attributed to any package or code type.


text:
package groupcache.peers.http

import com.twitter.finagle.Service
import com.twitter.util.{Promise, Future}
import com.google.protobuf.ByteString
import org.jboss.netty.handler.codec.http.{DefaultHttpResponse, HttpResponse, HttpRequest}
import org.jboss.netty.handler.codec.http.HttpVersion._
import org.jboss.netty.handler.codec.http.HttpResponseStatus._
import org.jboss.netty.buffer.ChannelBuffers._
import scala.util._
import scala.concurrent.ExecutionContext.Implicits.global
import groupcachepb.GetResponse

/**
 * Serves cached values over HTTP.
 *
 * @param contextFn Optional callback that allows for a user to specify context for
 *                  this peer (when acting as a server) when a request is received.
 *                  The callback accepts an HttpRequest as a parameter and returns
 *                  any optional value that this peer will treat as opaque.
 */
private[groupcache] class CacheService(
  private[this] val contextFn: Option[(HttpRequest) => Option[Any]] = None) extends Service[GroupHttpRequest, HttpResponse] {

  def apply(groupRequest: GroupHttpRequest): Future[HttpResponse] = {
    val context: Option[Any] = contextFn match {
      case Some(fn) => {
        fn(groupRequest.rawRequest)
      }
      case _ => None
    }

    groupRequest.group.groupStats.serverRequests.incrementAndGet()
    val futureValue = groupRequest.group.get(groupRequest.key, context)
    val promise = new Promise[HttpResponse]()

    futureValue onComplete {
      case Success(byteView) => {
        try {
          val getResponse = new GetResponse(Some(ByteString.copyFrom(byteView.byteSlice)))
          val successResponse = new DefaultHttpResponse(HTTP_1_1, OK)
          successResponse.setHeader("Content-Type", "application/x-protobuf")
          successResponse.setContent(copiedBuffer(getResponse.toByteArray))
          promise.setValue(successResponse)
        }
        catch {
          case t: Throwable => promise.setException(t)
        }
      }
      case Failure(t) => promise.setException(t)
    }

    promise
  }
}


text:
## Inputs

| Name | Description | Type | Default | Required |
|------|-------------|------|---------|:--------:|
| bastion\_members | The emails of the members with access to the bastion server. | `list(string)` | `[]` | no |
| bin\_auth\_attestor\_names | Binary Authorization Attestor Names set up in shared app\_cicd project | `list(string)` |
[
  "build-attestor",
  "quality-attestor",
  "security-attestor"
]
 | no |
| bin\_auth\_attestor\_project\_id | Project id where binary attestors are created (app\_cicd project from shared) | `string` | n/a | yes |
| boa\_gke\_project\_id | Project ID for GKE | `string` | n/a | yes |
| boa\_ops\_project\_id | Project ID for ops | `string` | n/a | yes |
| boa\_sec\_project\_id | Project ID for secrets | `string` | n/a | yes |
| boa\_sql\_project\_id | Project ID for SQL | `string` | n/a | yes |
| enforce\_bin\_auth\_policy | Enable or Disable creation of binary authorization policy | `bool` | `false` | no |
| gcp\_shared\_vpc\_project\_id | The host project id of the shared VPC | `string` | n/a | yes |
| gke\_cluster\_1\_cidr\_block | The primary IPv4 cidr block for the first GKE cluster. | `string` | `"100.64.142.0/28"` | no |
| gke\_cluster\_2\_cidr\_block | The primary IPv4 cidr block for the second GKE cluster. | `string` | `"100.65.134.0/28"` | no |
| gke\_mci\_cluster\_cidr\_block | The primary IPv4 cidr block for multi-cluster ingress (MCI). | `string` | `"100.64.134.0/28"` | no |
| location\_primary | The primary region for deployment | `string` | `"us-east1"` | no |
| location\_secondary | The secondary region for deployment | `string` | `"us-west1"` | no |
| shared\_vpc\_name | The shared VPC network name | `string` | n/a | yes |
| sql\_admin\_password | Admin Password for SQL Instances. | `string` | `"admin"` | no |
| sql\_admin\_username | Admin Username for SQL Instances. | `string` | `"admin"` | no |
| terraform\_service\_account | Service account email of the account to impersonate to run Terraform. | `string` | n/a | yes |

## Outputs

| Name | Description |
|------|-------------|
| bastion\_hostname | Host name of the bastion |
| bastion\_ip\_address | Internal IP address of the bastion host |
| bastion\_service\_account\_email | Email address of the SA created for the bastion host |
| external\_ip\_address | The external IP for HTTP load balancing. |
| gke\_1\_cluster\_name | Cluster 1 Name |
| gke\_1\_master\_ipv4 | Cluster 1 Master IPV4 Address CIDR |
| gke\_1\_region | Cluster 1 Region |
| gke\_2\_cluster\_name | Cluster 2 Name |
| gke\_2\_master\_ipv4 | Cluster 2 Master IPV4 Address CIDR |
| gke\_2\_region | Cluster 2 Region |
| mci\_cluster\_name | MCI Cluster Name |
| mci\_master\_ipv4 | MCI Cluster Master IPV4 Address CIDR |
| mci\_region | MCI Cluster Region |
| sql\_1\_instance\_name | PostgreSQL Instance 1 Name |
| sql\_1\_ip\_address | PostgreSQL Instance 1 Private Ip |
| sql\_2\_instance\_name | PostgreSQL Instance 2 Name |
| sql\_2\_ip\_address | PostgreSQL Instance 2 Private Ip |


text:
import rospy

from vigir_synthesis_msgs.srv import GenerateFlexBESM

def sm_generate_client(synthesized_automata, system):
    '''A wrapper for a call to the GenerateFlexBESM service.'''

    rospy.wait_for_service('sm_generate')

    try:
        sm_generate_srv = rospy.ServiceProxy('sm_generate', GenerateFlexBESM)
        response = sm_generate_srv(synthesized_automata, system)

        #DEBUG
        for si in response.state_definition:
            print(si)

        return response

    except rospy.ServiceException as e:
        print("Service call failed: %s" % e)

if __name__ == "__main__":
    sm_generate_client()


text:
int g_status = 0;

static void ExpectGameState(
		bool const iGameStarted,
		orwell::com::Receiver & ioSubscriber)
{
	orwell::com::RawMessage aResponse;
	bool aGotWhatExpected = false;
	int const aMaxLoops = 100;
	int aCurrentLoop = 0;

	while (not aGotWhatExpected)
	{
		if (not Common::ExpectMessage("GameState", ioSubscriber, aResponse))
		{
			ORWELL_LOG_DEBUG("Expected gamestate but we got something else : " << aResponse._type);
		}
		else
		{
			orwell::messages::GameState aGameState;
			aGameState.ParsePartialFromString(aResponse._payload);

			if (aGameState.playing() == iGameStarted)
			{
				ORWELL_LOG_DEBUG("State of the game is what was expected :" << aGameState.playing());
				aGotWhatExpected = true;
			}
		}
		++aCurrentLoop;
		if (aCurrentLoop > aMaxLoops)
		{
			ORWELL_LOG_ERROR("State of the game is not what was expected");
			g_status = -1;
			break;
		}
	}
}

static void client(
		uint16_t const iPusherPort,
		uint16_t const iSubscriberPort,
		uint16_t const iFakeAgentPort)
{
	log4cxx::NDC ndc("client");
	ORWELL_LOG_INFO("client ...");
	zmq::context_t aContext(1);
	ORWELL_LOG_INFO("create pusher");
	orwell::com::Sender aPusher(
			orwell::com::Url("tcp", "localhost", iPusherPort).toString(),
			ZMQ_PUSH,
			orwell::com::ConnectionMode::CONNECT,
			aContext);
	ORWELL_LOG_INFO("create subscriber");
	orwell::com::Receiver aSubscriber(
			orwell::com::Url("tcp", "localhost", iSubscriberPort).toString(),
			ZMQ_SUB,
			orwell::com::ConnectionMode::CONNECT,
			aContext);

	TestAgent aTestAgent(iFakeAgentPort);
	ORWELL_LOG_INFO("Synchronizing ping sent");
	aTestAgent.sendCommand("ping", std::string("pong"));
	ORWELL_LOG_INFO("Synchronizing pong received");

	orwell::messages::Hello aHelloMessage;
	aHelloMessage.set_name("playername");
	aHelloMessage.set_ready(true);
	orwell::com::RawMessage aMessage("randomid", "Hello", aHelloMessage.SerializeAsString());
	aPusher.send(aMessage);

	ExpectGameState(true, aSubscriber);

	aPusher.send(aMessage);

	ORWELL_LOG_INFO("quit client");
}

static void const server(
		std::shared_ptr< orwell::Server > ioServer,
		uint16_t const iFakeAgentPort)
{
	log4cxx::NDC ndc("server");
	ORWELL_LOG_INFO("server ...");
	zmq::context_t aContext(1);
	orwell::com::Socket aFakeAgentSocket(
				orwell::com::Url("tcp", "*", iFakeAgentPort).toString(),
				ZMQ_REP,
				orwell::com::ConnectionMode::BIND,
				aContext,
				0);
	std::string aPing;
	aFakeAgentSocket.receiveString(aPing, true);
	ORWELL_LOG_INFO("Synchronizing ping received");
	aFakeAgentSocket.sendString("pong");
	ORWELL_LOG_INFO("Synchronizing pong sent");
	for (int i = 0 ; i < 2 ; ++i)
	{
		usleep(3 * 1000); // sleep for 3 ms
		ORWELL_LOG_INFO("server loop " << i);
		ioServer->loopUntilOneMessageIsProcessed();
	}
	ORWELL_LOG_INFO("quit server");
}

int main()
{
	using ::testing::_;
	orwell::support::GlobalLogger::Create(
			"test_start_game_condition",
			"test_start_game_condition.log",
			true);
	log4cxx::NDC ndc("test_start_game_condition");
	uint16_t const aPusherPort(9000);
	uint16_t const aSubscriberPort(9001);
	uint16_t const aFakeAgentPort(9004);
	FakeAgentProxy aFakeAgentProxy;
	orwell::game::Ruleset aRuleset;
	aRuleset.m_scoreToWin = 1;
	FakeSystemProxy aFakeSystemProxy;
	EXPECT_CALL(aFakeSystemProxy, mkstemp(_)).Times(0);
	EXPECT_CALL(aFakeSystemProxy, system(_)).Times(0);
	std::shared_ptr< orwell::Server > aServer =
		std::make_shared< orwell::Server >(
			aFakeSystemProxy,
			aFakeAgentProxy,
			aRuleset,
			"tcp://*:9003",
			orwell::com::Url("tcp", "*", aPusherPort).toString(),
			orwell::com::Url("tcp", "*", aSubscriberPort).toString(),
			"tcp://*:9002");
	ORWELL_LOG_INFO("server created");
	std::vector< std::string > aRobots = {"Gipsy Danger"};
	std::string const aTeamName("TEAM");
	aServer->accessContext().addTeam(aTeamName);
	aServer->accessContext().addRobot(aRobots[0], aTeamName, 8001, 8004, "robot1");
	aServer->accessContext().accessRobot(aRobots[0])->setHasRealRobot(true);
	ORWELL_LOG_INFO("robot added 1");
	std::thread aServerThread(server, aServer, aFakeAgentPort);
	std::thread aClientThread(
			client,
			aPusherPort,
			aSubscriberPort,
			aFakeAgentPort);
	aClientThread.join();
	aServerThread.join();
	orwell::support::GlobalLogger::Clear();
	return g_status;
}


text:
cask 'eventstore' do
  version '3.9.4'
  sha256 '337152fa65fa8472052cc02d5efaf872230b7ecad07e3d7979f5fd238e69e3f6'

  url "http://download.geteventstore.com/binaries/EventStore-OSS-MacOSX-v#{version}.tar.gz"
  name 'Event Store'
  homepage 'https://geteventstore.com/'

  binary "EventStore-OSS-MacOSX-v#{version}/eventstore"
  binary "EventStore-OSS-MacOSX-v#{version}/eventstore-testclient"

  # shim script (https://github.com/caskroom/homebrew-cask/issues/18809)
  eventstore_shimscript = "#{staged_path}/EventStore-OSS-MacOSX-v#{version}/eventstore"
  testclient_shimscript = "#{staged_path}/EventStore-OSS-MacOSX-v#{version}/eventstore-testclient"

  preflight do
    IO.write eventstore_shimscript, <<~EOS
      #!/bin/sh
      cd "#{staged_path}/EventStore-OSS-MacOSX-v#{version}"
      exec "#{staged_path}/EventStore-OSS-MacOSX-v#{version}/run-node.sh" "$@"
    EOS

    IO.write testclient_shimscript, <<~EOS
      #!/bin/sh
      exec "#{staged_path}/EventStore-OSS-MacOSX-v#{version}/testclient" "$@"
    EOS
  end
end


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Deleting field 'ComicSite.comment'
        db.delete_column('comicsite_comicsite', 'comment')

    def backwards(self, orm):
        # Adding field 'ComicSite.comment'
        db.add_column('comicsite_comicsite', 'comment',
                      self.gf('django.db.models.fields.CharField')(default='', max_length=1024, blank=True),
                      keep_default=False)

    models = {
        'comicsite.comicsite': {
            'Meta': {'object_name': 'ComicSite'},
            'description': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'short_name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '50'}),
            'skin': ('django.db.models.fields.CharField', [], {'max_length': '225'})
        },
        'comicsite.comicsitemodel': {
            'Meta': {'object_name': 'ComicSiteModel'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        'comicsite.page': {
            'ComicSite': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['comicsite.ComicSite']"}),
            'Meta': {'ordering': "['ComicSite', 'order']", 'unique_together': "(('ComicSite', 'title'),)", 'object_name': 'Page'},
            'display_title': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}),
            'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'html': ('django.db.models.fields.TextField', [], {}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'order': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
        }
    }

    complete_apps = ['comicsite']


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
ImageConverterWMF2G2D (Apache FOP 2.1 API)
</TITLE>

<META NAME="date" CONTENT="2016-01-07">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.fop.image.loader.batik

Class ImageConverterWMF2G2D

java.lang.Object
  org.apache.xmlgraphics.image.loader.impl.AbstractImageConverter
      org.apache.fop.image.loader.batik.ImageConverterWMF2G2D

All Implemented Interfaces:
org.apache.xmlgraphics.image.loader.spi.ImageConverter

public class ImageConverterWMF2G2D
extends org.apache.xmlgraphics.image.loader.impl.AbstractImageConverter

This ImageConverter converts WMF (Windows Metafile) images (represented by Batik's
 WMFRecordStore) to Java2D.

Field Summary

Fields inherited from interface org.apache.xmlgraphics.image.loader.spi.ImageConverter

MEDIUM_CONVERSION_PENALTY, MINIMAL_CONVERSION_PENALTY, NO_CONVERSION_PENALTY

Constructor Summary

ImageConverterWMF2G2D()

Method Summary

 org.apache.xmlgraphics.image.loader.Image
convert(org.apache.xmlgraphics.image.loader.Image src,
        java.util.Map hints)

 org.apache.xmlgraphics.image.loader.ImageFlavor
getSourceFlavor()

 org.apache.xmlgraphics.image.loader.ImageFlavor
getTargetFlavor()

Methods inherited from class org.apache.xmlgraphics.image.loader.impl.AbstractImageConverter

checkSourceFlavor, getConversionPenalty

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ImageConverterWMF2G2D

public ImageConverterWMF2G2D()

Method Detail

convert

public org.apache.xmlgraphics.image.loader.Image convert(org.apache.xmlgraphics.image.loader.Image src,
                                                         java.util.Map hints)

getSourceFlavor

public org.apache.xmlgraphics.image.loader.ImageFlavor getSourceFlavor()

getTargetFlavor

public org.apache.xmlgraphics.image.loader.ImageFlavor getTargetFlavor()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright 1999-2016 The Apache Software Foundation. All Rights Reserved.


text:
<?php

namespace Ivory\Tests\Serializer;

use Ivory\Serializer\Context\Context;
use Ivory\Serializer\Context\ContextInterface;
use Ivory\Serializer\Exclusion\GroupsExclusionStrategy;
use Ivory\Serializer\Exclusion\MaxDepthExclusionStrategy;
use Ivory\Serializer\Exclusion\VersionExclusionStrategy;
use Ivory\Serializer\Format;
use Ivory\Serializer\Naming\CamelCaseNamingStrategy;
use Ivory\Serializer\Naming\KebabCaseNamingStrategy;
use Ivory\Serializer\Naming\SnakeCaseNamingStrategy;
use Ivory\Serializer\Naming\SpaceNamingStrategy;
use Ivory\Serializer\Naming\StudlyCapsNamingStrategy;
use Ivory\Serializer\Navigator\Navigator;
use Ivory\Serializer\Registry\TypeRegistry;
use Ivory\Serializer\Serializer;
use Ivory\Serializer\Type\ExceptionType;
use Ivory\Serializer\Type\Type;
use Ivory\Tests\Serializer\Fixture\AccessorFixture;
use Ivory\Tests\Serializer\Fixture\ArrayFixture;
use Ivory\Tests\Serializer\Fixture\AscFixture;
use Ivory\Tests\Serializer\Fixture\DateTimeFixture;
use Ivory\Tests\Serializer\Fixture\DescFixture;
use Ivory\Tests\Serializer\Fixture\ExcludeFixture;
use Ivory\Tests\Serializer\Fixture\ExposeFixture;
use Ivory\Tests\Serializer\Fixture\FixtureInterface;
use Ivory\Tests\Serializer\Fixture\GroupFixture;
use Ivory\Tests\Serializer\Fixture\IgnoreNullFixture;
use Ivory\Tests\Serializer\Fixture\MaxDepthFixture;
use Ivory\Tests\Serializer\Fixture\MutatorFixture;
use Ivory\Tests\Serializer\Fixture\NamingFixture;
use Ivory\Tests\Serializer\Fixture\OrderFixture;
use Ivory\Tests\Serializer\Fixture\ReadableClassFixture;
use Ivory\Tests\Serializer\Fixture\ReadableFixture;
use Ivory\Tests\Serializer\Fixture\ScalarFixture;
use Ivory\Tests\Serializer\Fixture\VersionFixture;
use Ivory\Tests\Serializer\Fixture\WritableClassFixture;
use Ivory\Tests\Serializer\Fixture\WritableFixture;
use Ivory\Tests\Serializer\Fixture\XmlFixture;
use Ivory\Tests\Serializer\Fixture\XmlValueFixture;

/**
 * @author GeLo <geloen.eric@gmail.com>
 */
class SerializerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Serializer
     */
    private $serializer;

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->serializer = new Serializer();
    }

    /**
     * @param string                $name
     * @param mixed                 $data
     * @param string                $format
     * @param ContextInterface|null $context
     *
     * @dataProvider serializeProvider
     */
    public function testSerialize($name, $data, $format, ContextInterface $context = null)
    {
        $this->assertSame($this->getDataSet($name, $format), $this->serializer->serialize($data, $format, $context));
    }

    /**
     * @param string $name
     * @param mixed  $data
     * @param string $format
     *
     * @dataProvider serializeExceptionProvider
     */
    public function testSerializeException($name, $data, $format)
    {
        $this->serializer = new Serializer(new Navigator(TypeRegistry::create([
            Type::EXCEPTION => new ExceptionType(true),
        ])));

        $this->assertRegExp(
            '/^'.$this->getDataSet($name.'_debug', $format).'$/s',
            $this->serializer->serialize($data, $format)
        );
    }

    /**
     * @param string                $name
     * @param mixed                 $data
     * @param string                $type
     * @param string                $format
     * @param ContextInterface|null $context
     *
     * @dataProvider deserializeProvider
     */
    public function testDeserialize($name, $data, $type, $format, ContextInterface $context = null)
    {
        $result = $this->serializer->deserialize($this->getDataSet($name, $format), $type, $format, $context);

        foreach ([&$data, &$result] as &$value) {
            if ($value instanceof FixtureInterface) {
                $value = $value->toArray();
            } elseif ($value instanceof \DateTimeInterface) {
                $value = $value->format(\DateTime::RFC3339);
            } elseif ($value instanceof \stdClass) {
                $value = (array) $value;
            }
        }

        $this->assertSame($data, $result);
    }

    /**
     * @param string $message
     * @param string $type
     * @param string $format
     *
     * @dataProvider unsupportedTypeProvider
     */
    public function testDeserializeWithInvalidType($message, $type, $format)
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage($message);

        $this->serializer->deserialize($this->getDataSet('string', $format), $type, $format);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The visitor for direction "deserialization" and format "txt" does not exist.
     */
    public function testDeserializeWithInvalidFormat()
    {
        $this->serializer->deserialize('data', Type::STRING, 'txt');
    }

    /**
     * @return mixed[]
     */
    public function serializeProvider()
    {
        return $this->expandCases(array_merge($this->exceptionCases(), $this->commonCases()));
    }

    /**
     * @return mixed[]
     */
    public function serializeExceptionProvider()
    {
        return $this->expandCases($this->exceptionCases());
    }

    /**
     * @return mixed[]
     */
    public function deserializeProvider()
    {
        $cases = [];

        foreach ($this->expandCases($this->commonCases()) as $provider) {
            if (isset($provider[3])) {
                continue;
            }

            $cases[] = [
                $provider[0],
                $data = $provider[1],
                is_object($data) ? get_class($data) : strtolower(gettype($data)),
                $provider[2],
            ];
        }

        return $cases;
    }

    /**
     * @return mixed[]
     */
    public function unsupportedTypeProvider()
    {
        return $this->expandCases([
            ['The type "foo" for direction "deserialization" does not exist.', 'foo'],
            ['The type must be a string or a "Ivory\Serializer\Mapping\TypeMetadataInterface", got "boolean".', true],
        ]);
    }

    /**
     * @return mixed[]
     */
    private function exceptionCases()
    {
        $parentException = new \Exception('Parent exception', 321);
        $childException = new \Exception('Child exception', 123, $parentException);

        return [
            ['exception_parent', $parentException],
            ['exception_child', $childException],
        ];
    }

    /**
     * @return mixed[]
     */
    public function commonCases()
    {
        $emptyArrayFixture = new ArrayFixture();
        $arrayFixture = clone $emptyArrayFixture;
        $arrayFixture->setScalars(['foo', 'bar' => 'baz']);
        $arrayFixture->setObjects([clone $emptyArrayFixture]);
        $arrayFixture->setTypes(['foo', 'bar']);
        $arrayFixture->setInceptions(['foo' => ['bar', 'baz']]);

        $date = '2017-01-01T00:00:00';
        $dateTime = new \DateTime($date, new \DateTimeZone('UTC'));
        $timeZonedDateTime = new \DateTime($date, new \DateTimeZone('Europe/Paris'));
        $dateTimeImmutable = new \DateTimeImmutable($date, new \DateTimeZone('UTC'));
        $timeZonedDateTimeImmutable = new \DateTimeImmutable($date, new \DateTimeZone('Europe/Paris'));

        $emptyDateTimeFixture = new DateTimeFixture();
        $dateTimeFixture = clone $emptyDateTimeFixture;
        $dateTimeFixture->dateTime = $dateTime;
        $dateTimeFixture->formattedDateTime = $dateTime;
        $dateTimeFixture->timeZonedDateTime = $timeZonedDateTime;
        $dateTimeFixture->immutableDateTime = $dateTimeImmutable;
        $dateTimeFixture->formattedImmutableDateTime = $dateTimeImmutable;
        $dateTimeFixture->timeZonedImmutableDateTime = $timeZonedDateTimeImmutable;

        $emptyIgnoreNullFixture = new IgnoreNullFixture();
        $ignoreNullFixture = clone $emptyIgnoreNullFixture;
        $ignoreNullFixture->foo = 'oof';
        $ignoreNullFixture->bar = [null, null];

        $namingFixture = new NamingFixture();
        $namingFixture->fooBar = 'foo';
        $namingFixture->baz_bat = 'baz';

        $excludeFixture = new ExcludeFixture();
        $excludeFixture->foo = 'oof';
        $excludeFixture->bar = 'rab';

        $exposeFixture = new ExposeFixture();
        $exposeFixture->foo = 'oof';
        $exposeFixture->bar = 'rab';

        $accessorFixture = new AccessorFixture();
        $accessorFixture->setName(' foo ');

        $mutatorFixture = new MutatorFixture();
        $mutatorFixture->setRawName(' foo ');

        $emptyGroupFixture = new GroupFixture();
        $groupFixture = clone $emptyGroupFixture;
        $groupFixture->setFoo('oof');
        $groupFixture->setBar('rab');
        $groupFixture->setBaz('zab');
        $groupFixture->setBat('tab');

        $emptyMaxDepthFixture = new MaxDepthFixture();
        $maxDepthFixture = clone $emptyMaxDepthFixture;
        $maxDepthFixture->setParent($maxDepthParentFixture = clone $emptyMaxDepthFixture);
        $maxDepthParentFixture->setParent(clone $emptyMaxDepthFixture);
        $maxDepthFixture->addChild($maxDepthChildFixture = clone $emptyMaxDepthFixture);
        $maxDepthFixture->orphanChildren[] = clone $emptyArrayFixture;
        $maxDepthChildFixture->addChild(clone $emptyMaxDepthFixture);

        $circularReference = new MaxDepthFixture();
        $circularReference->setParent($circularReference);

        $ascFixture = new AscFixture();
        $ascFixture->foo = 'oof';
        $ascFixture->bar = 'rab';

        $descFixture = new DescFixture();
        $descFixture->foo = 'oof';
        $descFixture->bar = 'rab';

        $orderFixture = new OrderFixture();
        $orderFixture->foo = 'oof';
        $orderFixture->bar = 'rab';

        $readableFixture = new ReadableFixture();
        $readableFixture->foo = 'oof';
        $readableFixture->bar = 'rab';

        $readableClassFixture = new ReadableClassFixture();
        $readableClassFixture->foo = 'oof';
        $readableClassFixture->bar = 'rab';

        $writableFixture = new WritableFixture();
        $writableFixture->foo = 'oof';
        $writableFixture->bar = 'rab';

        $writableClassFixture = new WritableClassFixture();
        $writableClassFixture->foo = 'oof';
        $writableClassFixture->bar = 'rab';

        $emptyScalarFixture = new ScalarFixture();
        $scalarFixture = clone $emptyScalarFixture;
        $scalarFixture->bool = true;
        $scalarFixture->float = 123.0;
        $scalarFixture->int = 123;
        $scalarFixture->string = 'foo';
        $scalarFixture->setType(clone $scalarFixture);

        $emptyScalarExtendedFixture = new ScalarFixture();
        $scalarExtendedFixture = clone $emptyScalarExtendedFixture;
        $scalarExtendedFixture->bool = true;
        $scalarExtendedFixture->float = 123.0;
        $scalarExtendedFixture->int = 123;
        $scalarExtendedFixture->string = 'foo';
        $scalarExtendedFixture->setType(clone $scalarExtendedFixture);

        $emptyStdClass = new \stdClass();
        $stdClass = clone $emptyStdClass;
        $stdClass->foo = 'bar';
        $stdClass->baz = ['bat'];

        $emptyVersionFixture = new VersionFixture();
        $versionFixture = clone $emptyVersionFixture;
        $versionFixture->foo = 'oof';
        $versionFixture->bar = 'rab';
        $versionFixture->baz = 'zab';
        $versionFixture->bat = 'tab';

        $xmlFixture = new XmlFixture();
        $xmlFixture->foo = 'oof';
        $xmlFixture->bar = 'rab';
        $xmlFixture->list = ['foo', 'bar' => 'rab', 'zib<' => 'biz'];
        $xmlFixture->keyAsAttribute = ['ban', 'bor>' => 'rob', 'bit' => 'bot'];
        $xmlFixture->keyAsNode = ['bit', 'bir<' => 'rib', 'bot' => 'ban'];
        $xmlFixture->entry = ['baz', 'bat' => 'tab', 'opo<' => 'opo'];
        $xmlFixture->entryAttribute = ['baz', 'bin' => 'bat', 'bin<' => 'nib'];
        $xmlFixture->inline = ['biz' => 'boz', 'bot' => 'ban', '<zop' => 'poz'];

        $xmlValueFixture = new XmlValueFixture();
        $xmlValueFixture->foo = 'oof';
        $xmlValueFixture->bar = 'rab';

        return [
            ['array', []],
            ['boolean', true],
            ['integer', 123],
            ['float', 123.0],
            ['null', null],
            ['string', 'foo'],
            ['date_time', $dateTime],
            ['std_class', $stdClass],
            ['std_class_empty', $emptyStdClass],
            ['object_array', $arrayFixture],
            ['object_array_empty', $emptyArrayFixture],
            ['object_date_time', $dateTimeFixture],
            ['object_date_time_empty', $emptyDateTimeFixture],
            ['object_ignore_null', $ignoreNullFixture, (new Context())->setIgnoreNull(true)],
            ['object_ignore_null_empty', $emptyIgnoreNullFixture, (new Context())->setIgnoreNull(true)],
            ['object_naming', $namingFixture],
            ['object_naming_camel_case', $namingFixture, (new Context())->setNamingStrategy(new CamelCaseNamingStrategy())],
            ['object_naming_kebab_case', $namingFixture, (new Context())->setNamingStrategy(new KebabCaseNamingStrategy())],
            ['object_naming_snake_case', $namingFixture, (new Context())->setNamingStrategy(new SnakeCaseNamingStrategy())],
            ['object_naming_space', $namingFixture, (new Context())->setNamingStrategy(new SpaceNamingStrategy())],
            ['object_naming_studly_caps', $namingFixture, (new Context())->setNamingStrategy(new StudlyCapsNamingStrategy())],
            ['object_exclude', $excludeFixture],
            ['object_expose', $exposeFixture],
            ['object_accessor', $accessorFixture],
            ['object_mutator', $mutatorFixture],
            ['object_groups', $groupFixture],
            ['object_groups_empty', $emptyGroupFixture],
            ['object_groups_group1', $groupFixture, (new Context())->setExclusionStrategy(new GroupsExclusionStrategy(['group1']))],
            ['object_groups_group2', $groupFixture, (new Context())->setExclusionStrategy(new GroupsExclusionStrategy(['group2']))],
            ['object_groups_group1_group2', $groupFixture, (new Context())->setExclusionStrategy(new GroupsExclusionStrategy(['group1', 'group2']))],
            ['object_circular_reference', $circularReference, (new Context())->setExclusionStrategy(new MaxDepthExclusionStrategy())],
            ['object_max_depth', $maxDepthFixture, (new Context())->setExclusionStrategy(new MaxDepthExclusionStrategy())],
            ['object_max_depth_empty', $emptyMaxDepthFixture],
            ['object_order', $orderFixture],
            ['object_order_asc', $ascFixture],
            ['object_order_desc', $descFixture],
            ['object_readable', $readableFixture],
            ['object_readable_class', $readableClassFixture],
            ['object_writable', $writableFixture],
            ['object_writable_class', $writableClassFixture],
            ['object_scalar', $scalarFixture],
            ['object_scalar_empty', $emptyScalarFixture],
            ['object_scalar', $scalarExtendedFixture],
            ['object_scalar_empty', $emptyScalarExtendedFixture],
            ['object_version_empty', $emptyVersionFixture],
            ['object_version_0_9', $versionFixture, (new Context())->setExclusionStrategy(new VersionExclusionStrategy('0.9'))],
            ['object_version_1_0', $versionFixture, (new Context())->setExclusionStrategy(new VersionExclusionStrategy('1.0'))],
            ['object_version_2_0', $versionFixture, (new Context())->setExclusionStrategy(new VersionExclusionStrategy('2.0'))],
            ['object_version_2_1', $versionFixture, (new Context())->setExclusionStrategy(new VersionExclusionStrategy('2.1'))],
            ['xml', $xmlFixture],
            ['xml_value', $xmlValueFixture],
        ];
    }

    /**
     * @param mixed[] $cases
     *
     * @return mixed[]
     */
    private function expandCases(array $cases)
    {
        $providers = [];

        foreach ([Format::CSV, Format::JSON, Format::XML, Format::YAML] as $format) {
            foreach ($cases as $case) {
                if (isset($case[2])) {
                    $case[3] = $case[2];
                }

                $case[2] = $format;
                $providers[] = $case;
            }
        }

        return $providers;
    }

    /**
     * @param string $name
     * @param string $format
     *
     * @return string
     */
    private function getDataSet($name, $format)
    {
        $extension = $format;

        if ($extension === Format::YAML) {
            $extension = 'yml';
        }

        return file_get_contents(__DIR__.'/Fixture/data/'.strtolower($format).'/'.$name.'.'.strtolower($extension));
    }
}


text:
#ifdef OS_WINDOWS
   #define WIN32_LEAN_AND_MEAN
   #include <windows.h>

   typedef HANDLE channel;
#else
   typedef int channel;
#endif

channel create_channel(const char *name, u32 out_buffer_size, u32 in_buffer_size, u32 timeout);
void close_channel(channel c);
channel connect_to_channel(const char *name);
void disconnect_channel(channel c);

// read_channel and write_channel return false if the channel has been closed.
bool read_channel(channel c, void *buffer, u32 buffer_length);
bool write_channel(channel c, void *buffer, u32 buffer_length);

u32 bytes_in_channel(channel c);


text:
class CustomCitableRecord < ActiveRecord::Base
  acts_as_citable do |c|
    c.data_field = "my_data"
    c.format_field = :my_format
  end
end


text:
var appConfig = require("./config/app.config");
var webpack = require("webpack");
const DefinePlugin = require("webpack/lib/DefinePlugin");
const LoaderOptionsPlugin = require("webpack/lib/LoaderOptionsPlugin");

module.exports = {
    plugins: [
       new DefinePlugin({
           APP_CONFIG: appConfig
       }),
        new LoaderOptionsPlugin({
            options: {
                tslint: {
                    configuration: {
                        rules: {
                            quotemark: [true, "double"]
                        }
                    },

                    // tslint errors are displayed by default as warnings
                    // set emitErrors to true to display them as errors
                    emitErrors: false,

                    // tslint does not interrupt the compilation by default
                    // if you want any file with tslint errors to fail
                    // set failOnHint to true
                    failOnHint: true,

                    // name of your formatter (optional)
                    formatter: "",

                    // path to directory containing formatter (optional)
                    formattersDirectory: "node_modules/tslint-loader/formatters/",

                    // These options are useful if you want to save output to files
                    // for your continuous integration server
                    fileOutput: {
                        // The directory where each file"s report is saved
                        dir: "./webpack-log/",

                        // The extension to use for each report"s filename. Defaults to "txt"
                        ext: "xml",

                        // If true, all files are removed from the report directory at the beginning of run
                        clean: true,

                        // A string to include at the top of every report file.
                        // Useful for some report formats.
                        header: "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<checkstyle version=\"5.7\">",

                        // A string to include at the bottom of every report file.
                        // Useful for some report formats.
                        footer: "</checkstyle>"
                    }
                }
            }
        })

    ],
    devtool: 'source-map',
    entry: {
        "app": ["./client/ts/app/main.ts"]
    },
    output: {
        path: __dirname,
        filename: "./dist/bundle.js"
    },
    resolve: {
        extensions: [".js", ".ts"],
    },
    module: {
        loaders: [
            {
                test: /\.json$/,
                loader: "json-loader"
            },
            {
                test: /\.ts$/,
                loader: 'awesome-typescript-loader'
            },
            {
                test: /\.ts$/,
                loader: 'tslint',
                exclude: /(node_modules)/,
                enforce: 'pre'
            },
        ],
    }
}


text:
package io.fabric8.utils.cxf;

import io.fabric8.utils.IOHelpers;
import org.apache.cxf.jaxrs.client.ResponseExceptionMapper;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.io.InputStream;

public class ExceptionResponseMapper implements ResponseExceptionMapper<Exception> {

    @Override
    public Exception fromResponse(Response response) {
        try {
            Object entity = response.getEntity();
            String message = "No message";
            if (entity instanceof InputStream) {
                InputStream inputStream = (InputStream) entity;
                message = IOHelpers.readFully(inputStream);
            } else if (entity != null) {
                message = entity.toString();
            }
            message = "HTTP " + response.getStatus() + " " + message;
            return new WebApplicationException(message, response);
        } catch (Exception ex) {
            return new Exception("Could not deserialize server side exception: " + ex.getMessage());
        }
    }

}


text:
package digitalocean

import (
	"fmt"
	"testing"

	"github.com/digitalocean/godo"
	"github.com/hashicorp/terraform/helper/acctest"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccDigitalOceanDomain_Basic(t *testing.T) {
	var domain godo.Domain
	domainName := fmt.Sprintf("foobar-test-terraform-%s.com", acctest.RandString(10))

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckDigitalOceanDomainDestroy,
		Steps: []resource.TestStep{
			{
				Config: fmt.Sprintf(testAccCheckDigitalOceanDomainConfig_basic, domainName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckDigitalOceanDomainExists("digitalocean_domain.foobar", &domain),
					testAccCheckDigitalOceanDomainAttributes(&domain, domainName),
					resource.TestCheckResourceAttr(
						"digitalocean_domain.foobar", "name", domainName),
					resource.TestCheckResourceAttr(
						"digitalocean_domain.foobar", "ip_address", "192.168.0.10"),
				),
			},
		},
	})
}

func testAccCheckDigitalOceanDomainDestroy(s *terraform.State) error {
	client := testAccProvider.Meta().(*godo.Client)

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "digitalocean_domain" {
			continue
		}

		// Try to find the domain
		_, _, err := client.Domains.Get(rs.Primary.ID)

		if err == nil {
			return fmt.Errorf("Domain still exists")
		}
	}

	return nil
}

func testAccCheckDigitalOceanDomainAttributes(domain *godo.Domain, name string) resource.TestCheckFunc {
	return func(s *terraform.State) error {

		if domain.Name != name {
			return fmt.Errorf("Bad name: %s", domain.Name)
		}

		return nil
	}
}

func testAccCheckDigitalOceanDomainExists(n string, domain *godo.Domain) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]

		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No Record ID is set")
		}

		client := testAccProvider.Meta().(*godo.Client)

		foundDomain, _, err := client.Domains.Get(rs.Primary.ID)

		if err != nil {
			return err
		}

		if foundDomain.Name != rs.Primary.ID {
			return fmt.Errorf("Record not found")
		}

		*domain = *foundDomain

		return nil
	}
}

const testAccCheckDigitalOceanDomainConfig_basic = `
resource "digitalocean_domain" "foobar" {
	name       = "%s"
	ip_address = "192.168.0.10"
}`


text:
class Profile;

namespace content {
struct FileChooserFileInfo;
class RenderViewHost;
class WebContents;
}

namespace ui {
struct SelectedFileInfo;
}

// This class handles file-selection requests coming from WebUI elements
// (via the extensions::ExtensionHost class). It implements both the
// initialisation and listener functions for file-selection dialogs.
//
// Since FileSelectHelper has-a NotificationRegistrar, it needs to live on and
// be destroyed on the UI thread. References to FileSelectHelper may be passed
// on to other threads.
class FileSelectHelper : public base::RefCountedThreadSafe<
                             FileSelectHelper,
                             content::BrowserThread::DeleteOnUIThread>,
                         public ui::SelectFileDialog::Listener,
                         public content::WebContentsObserver,
                         public content::NotificationObserver {
 public:
  // Show the file chooser dialog.
  static void RunFileChooser(content::WebContents* tab,
                             const content::FileChooserParams& params);

  // Enumerates all the files in directory.
  static void EnumerateDirectory(content::WebContents* tab,
                                 int request_id,
                                 const base::FilePath& path);

 private:
  friend class base::RefCountedThreadSafe<FileSelectHelper>;
  friend class base::DeleteHelper<FileSelectHelper>;
  friend struct content::BrowserThread::DeleteOnThread<
      content::BrowserThread::UI>;

  FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest, IsAcceptTypeValid);
  FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest, ZipPackage);
  FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest, GetSanitizedFileName);
  explicit FileSelectHelper(Profile* profile);
  ~FileSelectHelper() override;

  // Utility class which can listen for directory lister events and relay
  // them to the main object with the correct tracking id.
  class DirectoryListerDispatchDelegate
      : public net::DirectoryLister::DirectoryListerDelegate {
   public:
    DirectoryListerDispatchDelegate(FileSelectHelper* parent, int id)
        : parent_(parent),
          id_(id) {}
    ~DirectoryListerDispatchDelegate() override {}
    void OnListFile(
        const net::DirectoryLister::DirectoryListerData& data) override;
    void OnListDone(int error) override;

   private:
    // This FileSelectHelper owns this object.
    FileSelectHelper* parent_;
    int id_;

    DISALLOW_COPY_AND_ASSIGN(DirectoryListerDispatchDelegate);
  };

  void RunFileChooser(content::RenderViewHost* render_view_host,
                      content::WebContents* web_contents,
                      std::unique_ptr<content::FileChooserParams> params);
  void GetFileTypesOnFileThread(
      std::unique_ptr<content::FileChooserParams> params);
  void GetSanitizedFilenameOnUIThread(
      std::unique_ptr<content::FileChooserParams> params);
#if defined(FULL_SAFE_BROWSING)
  void CheckDownloadRequestWithSafeBrowsing(
      const base::FilePath& default_path,
      std::unique_ptr<content::FileChooserParams> params);
  void ProceedWithSafeBrowsingVerdict(
      const base::FilePath& default_path,
      std::unique_ptr<content::FileChooserParams> params,
      bool allowed_by_safe_browsing);
#endif
  void RunFileChooserOnUIThread(
      const base::FilePath& default_path,
      std::unique_ptr<content::FileChooserParams> params);

  // Cleans up and releases this instance. This must be called after the last
  // callback is received from the file chooser dialog.
  void RunFileChooserEnd();

  // SelectFileDialog::Listener overrides.
  void FileSelected(const base::FilePath& path,
                    int index,
                    void* params) override;
  void FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file,
                                 int index,
                                 void* params) override;
  void MultiFilesSelected(const std::vector<base::FilePath>& files,
                          void* params) override;
  void MultiFilesSelectedWithExtraInfo(
      const std::vector<ui::SelectedFileInfo>& files,
      void* params) override;
  void FileSelectionCanceled(void* params) override;

  // content::NotificationObserver overrides.
  void Observe(int type,
               const content::NotificationSource& source,
               const content::NotificationDetails& details) override;

  // content::WebContentsObserver overrides.
  void RenderViewHostChanged(content::RenderViewHost* old_host,
                             content::RenderViewHost* new_host) override;
  void WebContentsDestroyed() override;

  void EnumerateDirectory(int request_id,
                          content::RenderViewHost* render_view_host,
                          const base::FilePath& path);

  // Kicks off a new directory enumeration.
  void StartNewEnumeration(const base::FilePath& path,
                           int request_id,
                           content::RenderViewHost* render_view_host);

  // Callbacks from directory enumeration.
  virtual void OnListFile(
      int id,
      const net::DirectoryLister::DirectoryListerData& data);
  virtual void OnListDone(int id, int error);

  // Cleans up and releases this instance. This must be called after the last
  // callback is received from the enumeration code.
  void EnumerateDirectoryEnd();

#if defined(OS_MACOSX)
  // Must be called on the FILE_USER_BLOCKING thread. Each selected file that is
  // a package will be zipped, and the zip will be passed to the render view
  // host in place of the package.
  void ProcessSelectedFilesMac(const std::vector<ui::SelectedFileInfo>& files);

  // Saves the paths of |zipped_files| for later deletion. Passes |files| to the
  // render view host.
  void ProcessSelectedFilesMacOnUIThread(
      const std::vector<ui::SelectedFileInfo>& files,
      const std::vector<base::FilePath>& zipped_files);

  // Zips the package at |path| into a temporary destination. Returns the
  // temporary destination, if the zip was successful. Otherwise returns an
  // empty path.
  static base::FilePath ZipPackage(const base::FilePath& path);
#endif  // defined(OS_MACOSX)

  // Utility method that passes |files| to the render view host, and ends the
  // file chooser.
  void NotifyRenderViewHostAndEnd(
      const std::vector<ui::SelectedFileInfo>& files);

  // Sends the result to the render process, and call |RunFileChooserEnd|.
  void NotifyRenderViewHostAndEndAfterConversion(
      const std::vector<content::FileChooserFileInfo>& list);

  // Schedules the deletion of the files in |temporary_files_| and clears the
  // vector.
  void DeleteTemporaryFiles();

  // Cleans up when the RenderViewHost of our WebContents changes.
  void CleanUpOnRenderViewHostChange();

  // Helper method to get allowed extensions for select file dialog from
  // the specified accept types as defined in the spec:
  //   http://whatwg.org/html/number-state.html#attr-input-accept
  // |accept_types| contains only valid lowercased MIME types or file extensions
  // beginning with a period (.).
  static std::unique_ptr<ui::SelectFileDialog::FileTypeInfo>
  GetFileTypesFromAcceptType(const std::vector<base::string16>& accept_types);

  // Check the accept type is valid. It is expected to be all lower case with
  // no whitespace.
  static bool IsAcceptTypeValid(const std::string& accept_type);

  // Get a sanitized filename suitable for use as a default filename. The
  // suggested filename coming over the IPC may contain invalid characters or
  // may result in a filename that's reserved on the current platform.
  //
  // If |suggested_path| is empty, the return value is also empty.
  //
  // If |suggested_path| is non-empty, but can't be safely converted to UTF-8,
  // or is entirely lost during the sanitization process (e.g. because it
  // consists entirely of invalid characters), it's replaced with a default
  // filename.
  //
  // Otherwise, returns |suggested_path| with any invalid characters will be
  // replaced with a suitable replacement character.
  static base::FilePath GetSanitizedFileName(
      const base::FilePath& suggested_path);

  // Profile used to set/retrieve the last used directory.
  Profile* profile_;

  // The RenderViewHost and WebContents for the page showing a file dialog
  // (may only be one such dialog).
  content::RenderViewHost* render_view_host_;
  content::WebContents* web_contents_;

  // Dialog box used for choosing files to upload from file form fields.
  scoped_refptr<ui::SelectFileDialog> select_file_dialog_;
  std::unique_ptr<ui::SelectFileDialog::FileTypeInfo> select_file_types_;

  // The type of file dialog last shown.
  ui::SelectFileDialog::Type dialog_type_;

  // The mode of file dialog last shown.
  content::FileChooserParams::Mode dialog_mode_;

  // Maintain a list of active directory enumerations.  These could come from
  // the file select dialog or from drag-and-drop of directories, so there could
  // be more than one going on at a time.
  struct ActiveDirectoryEnumeration;
  std::map<int, ActiveDirectoryEnumeration*> directory_enumerations_;

  // Registrar for notifications regarding our RenderViewHost.
  content::NotificationRegistrar notification_registrar_;

  // Temporary files only used on OSX. This class is responsible for deleting
  // these files when they are no longer needed.
  std::vector<base::FilePath> temporary_files_;

  DISALLOW_COPY_AND_ASSIGN(FileSelectHelper);
};

#endif  // CHROME_BROWSER_FILE_SELECT_HELPER_H_


text:
using System;
using System.Linq.Expressions;
using CqlQueryBuilder.Base;
using CqlQueryBuilder.Builders.Contracts;

namespace CqlQueryBuilder.Builders
{
    public class SelectBuilder<T> : CqlStatementBase, ISelectBuilder<T>,
        IWhereBuilder<WhereBuilder<T>, T> where T : class
    {
        public SelectBuilder(string query) : base(query) { }

        public SelectBuilder<T> Limit(int limit)
        {
            AddStatement(QueryHelper.Limit(limit));
            return new SelectBuilder<T>(Build());
        }

        public SelectBuilder<T> OrderByAsc(Expression<Func<T, object>> parameter)
        {
            var param = QueryCreate.GetParameterName(parameter);
            AddStatement(QueryHelper.OrderBy(param, true));
            return new SelectBuilder<T>(Build());
        }

        public SelectBuilder<T> OrderByDesc(Expression<Func<T, object>> parameter)
        {
            var param = QueryCreate.GetParameterName(parameter);
            AddStatement(QueryHelper.OrderBy(param, false));
            return new SelectBuilder<T>(Build());
        }

        public WhereBuilder<T> Where(Expression<Func<T, bool>> parameters)
        {
            AddStatement(QueryHelper.Where(parameters));
            return new WhereBuilder<T>(Build());
        }

        public WhereBuilder<T> WhereIn(Expression<Func<T, object>> parameter, object[] values)
        {
            AddStatement(QueryHelper.WhereIn(parameter, values));
            return new WhereBuilder<T>(Build());
        }
    }
}


text:
include_recipe 'websphere-test::was_install_basic'

websphere_dmgr 'Dmgr01 create' do
  profile_name 'Dmgr01'
  cell_name 'MyNewCell'
  admin_user 'admin'
  admin_password 'admin'
  sensitive_exec false
  action [:create, :start]
end

websphere_profile 'Custom profile create and federate' do
  profile_name 'Custom'
  profile_type 'custom'
  admin_user 'admin'
  admin_password 'admin'
  sensitive_exec false
  action [:create, :federate]
end

websphere_app_server 'app_server1' do
  node_name 'Custom_node'
  admin_user 'admin'
  admin_password 'admin'
  # rubocop:disable Lint/ParenthesesAsGroupedExpression
  attributes ({
    'processDefinitions' => {
      'monitoringPolicy' => {
        'newvalue' => "[['maximumStartupAttempts', '2'], ['pingInterval', '222'], ['autoRestart', 'true'], ['nodeRestartState', 'PREVIOUS']]",
      },
      'jvmEntries' => {
        'newvalue' => "[['debugMode', 'true'], ['initialHeapSize', 1024], ['maximumHeapSize', 3072], ['systemProperties',[[['name','my_system_property'],['value','testing123']]]]]",
      },
    },
  })
  # rubocop:enable Lint/ParenthesesAsGroupedExpression
  sensitive_exec false
  action [:create, :start]
end

websphere_app_server 'app_server2' do
  node_name 'Custom_node'
  admin_user 'admin'
  admin_password 'admin'
  sensitive_exec false
  action [:create, :start, :delete]
end

remote_file File.join(Chef::Config[:file_cache_path], 'sample.war') do
  source 'https://s3-eu-west-1.amazonaws.com/jsidentity/was_sample_apps/sample.war'
  mode '0755'
  action :create
end

# deploy an unclustered application on the managed appserver
# start it and stop it. start it again.
websphere_app 'sample_app' do
  app_file File.join(Chef::Config[:file_cache_path], 'sample.war')
  server_name 'app_server1'
  node_name 'Custom_node'
  admin_user 'admin'
  admin_password 'admin'
  sensitive_exec false
  action [:deploy_to_server, :start]
end

log 'test restarting app' do
  message 'test restarting app'
  level :info
  notifies :stop, 'websphere_app[sample_app]', :immediately
  notifies :start, 'websphere_app[sample_app]', :immediately
end

websphere_profile 'App_Profile create/federate/start' do
  profile_name 'App_Profile'
  profile_type 'appserver'
  server_name 'AppProfile_server'
  admin_user 'admin'
  admin_password 'admin'
  sensitive_exec false
  action [:create, :federate, :start]
end


text:
${nls.settingsHeader}

${nls.settingsDesc}

${nls.noPolygonLayers}

                        ${nls.symbolArea.symbolLabelWithin}

                        ${nls.symbolArea.symbolLabelOutside}


text:
require 'net/http'
require 'json'
require 'time'

JENKINS_URI = URI.parse("http://rtbfittci001.infomaniak.ch:8080")

JENKINS_AUTH = {
  'name' => 'pi',
  'password' => 'rtbf2011'
}

# the key of this mapping must be a unique identifier for your job, the according value must be the name that is specified in jenkins
job_mapping = {
  'job1' => { :job => 'Library_General'},
  'job2' => { :job => 'ME-Qa-Admin'}
}

def get_number_of_failing_tests(job_name)
  info = get_json_for_job(job_name, 'lastCompletedBuild')
  info['actions'][4]['failCount']
end

def get_completion_percentage(job_name)
  build_info = get_json_for_job(job_name)
  prev_build_info = get_json_for_job(job_name, 'lastCompletedBuild')

  return 0 if not build_info["building"]
  last_duration = (prev_build_info["duration"] / 1000).round(2)
  current_duration = (Time.now.to_f - build_info["timestamp"] / 1000).round(2)
  return 99 if current_duration >= last_duration
  ((current_duration * 100) / last_duration).round(0)
end

def get_json_for_job(job_name, build = 'lastBuild')
  job_name = URI.encode(job_name)
  http = Net::HTTP.new(JENKINS_URI.host, JENKINS_URI.port)
  request = http.request(Net::HTTP::Get.new("/job/#{job_name}/#{build}/api/json"))
  if JENKINS_AUTH['name']
    request.basic_auth(JENKINS_AUTH['name'], JENKINS_AUTH['password'])
  end
  response = http.request(request)
  JSON.parse(response.body)
end

job_mapping.each do |title, jenkins_project|
  current_status = nil
  SCHEDULER.every '30s', :first_in => 0 do |job|
    last_status = current_status
    build_info = get_json_for_job(jenkins_project[:job])
    current_status = build_info["result"]
    if build_info["building"]
      current_status = "BUILDING"
      percent = get_completion_percentage(jenkins_project[:job])
    elsif jenkins_project[:pre_job]
      pre_build_info = get_json_for_job(jenkins_project[:pre_job])
      current_status = "PREBUILD" if pre_build_info["building"]
      percent = get_completion_percentage(jenkins_project[:pre_job])
    end

    send_event(title, {
      currentResult: current_status,
      lastResult: last_status,
      timestamp: build_info["timestamp"],
      value: percent
    })
  end
end


text:
title: "RESTful API Overview"
description: "Overview of Sensu API endpoints"
product: "Sensu Core"
version: "1.4"
weight: 1
menu:
  sensu-core-1.4:
    parent: api
---
## Sensu API

The Sensu API provides access to monitoring data collected by Sensu, such as
a [client registry][1], [check results][2], and [event data][3]. The API can be
used to request adhoc check executions, and resolve events, among other things.

## RESTful JSON API

The Sensu API is [JSON][4]-based [RESTful API][5]. Familiarity with (or
willingness to Google) industry standard RESTful API behaviors – including
[HTTP response codes][6] – are strongly recommended.

## Reference documentation

- [Clients API](../clients)
- [Checks API](../checks)
- [Results API](../results)
- [Aggregates API](../aggregates)
- [Events API](../events)
- [Stashes API](../stashes)
- [Health & Info API](../health-and-info)
- [Settings API](../settings)
- [API configuration](../configuration)

## Response Content Filtering

Sensu API endpoints that support the `GET` HTTP method support HTTP
response content filtering on one or more Sensu attributes.
To use response content filtering, construct the URL for your API request
using a dot notation query beginning with `filter`.

For example, to return only events that match the `production` environment and `ops` contact, use the following request.

{{< code shell >}}
curl -i 'http://127.0.0.1:4567/events?filter.client.environment=production&filter.check.contact=ops'
{{< /code >}}

Response filtering is only available for string values; integers (for example: `filter.check.status=2`) are not supported.

## Response Content Pagination {#pagination}
By default, the Sensu API will return all available results, but sometimes this result can be massive.
To paginate the returned result, the `limit` and `offset` query string parameters can be used.
This method also sets the "X-Pagination" HTTP response header to a JSON object containing the `limit`, `offset`, and `total` number of items that are being paginated.

parameters  |  description
------------|----------
limit       |  The number of items to return
offset      |  The number of items to offset before returning.

### Examples
The following example demonstrates a /clients API query with limit=1 and offset=1.
{{< code shell >}}
$ curl -i 'http://127.0.0.1:4567/clients?limit=1&offset=1'

HTTP/1.1 200 OK
Content-type: application/json
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization
Connection: close
X-Pagination: {"limit":1,"offset":1,"total":848}

[
  {
    "name": "client-02",
    "address": "127.0.0.1",
    "subscriptions": [],
    "timestamp": 1538843586
  }
]
{{< /code >}}

[1]:  ../../reference/clients#registration-and-registry
[2]:  ../../reference/checks#check-results
[3]:  ../../reference/events#event-data
[4]:  http://www.json.org/
[5]:  https://en.wikipedia.org/wiki/Representational_state_transfer
[6]:  https://en.wikipedia.org/wiki/List_of_HTTP_status_codes