text:
package com.linecorp.armeria.server.healthcheck;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.awaitility.Awaitility.await;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.slf4j.Logger;

import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams;

import com.linecorp.armeria.client.BlockingWebClient;
import com.linecorp.armeria.client.WebClient;
import com.linecorp.armeria.common.AggregatedHttpResponse;
import com.linecorp.armeria.common.HttpData;
import com.linecorp.armeria.common.HttpHeaderNames;
import com.linecorp.armeria.common.HttpHeaders;
import com.linecorp.armeria.common.HttpMethod;
import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.common.MediaType;
import com.linecorp.armeria.common.RequestHeaders;
import com.linecorp.armeria.common.ResponseHeaders;
import com.linecorp.armeria.server.HttpStatusException;
import com.linecorp.armeria.server.ServerBuilder;
import com.linecorp.armeria.server.logging.LoggingService;
import com.linecorp.armeria.testing.junit5.server.ServerExtension;

import io.netty.util.NetUtil;

class HealthCheckServiceTest {

    private static final SettableHealthChecker checker = new SettableHealthChecker();
    private static final AtomicReference<Boolean> capturedHealthy = new AtomicReference<>();
    private static final HealthChecker unfinishedHealthChecker = HealthChecker.of(CompletableFuture::new,
                                                                                Duration.ofDays(1));
    private static final Logger logger = mock(Logger.class);

    @RegisterExtension
    static final ServerExtension server = new ServerExtension() {
        @Override
        protected void configure(ServerBuilder sb) throws Exception {
            sb.service("/hc", HealthCheckService.of(checker));
            sb.service("/hc_unfinished_1", HealthCheckService.of(unfinishedHealthChecker));
            sb.service("/hc_unfinished_2", HealthCheckService.of(unfinishedHealthChecker));
            sb.service("/hc_long_polling_disabled", HealthCheckService.builder()
                                                                      .longPolling(0)
                                                                      .build());
            sb.service("/hc_updatable", HealthCheckService.builder()
                                                          .updatable(true)
                                                          .build());
            sb.service("/hc_update_listener", HealthCheckService.builder()
                                                                .updatable(true)
                                                                .updateListener(capturedHealthy::set)
                                                                .build());
            sb.service("/hc_unhealthy_at_startup", HealthCheckService.builder()
                                                                     .updatable(true)
                                                                     .startUnhealthy()
                                                                     .build());
            sb.service("/hc_custom",
                       HealthCheckService.builder()
                                         .healthyResponse(AggregatedHttpResponse.of(
                                                 HttpStatus.OK,
                                                 MediaType.PLAIN_TEXT_UTF_8,
                                                 "ok"))
                                         .unhealthyResponse(AggregatedHttpResponse.of(
                                                 HttpStatus.SERVICE_UNAVAILABLE,
                                                 MediaType.PLAIN_TEXT_UTF_8,
                                                 "not ok"))
                                         .updatable((ctx, req) -> {
                                             if (req.method() != HttpMethod.PUT) {
                                                 throw HttpStatusException.of(HttpStatus.METHOD_NOT_ALLOWED);
                                             }
                                             return req.aggregate().thenApply(aReq -> {
                                                 final String content = aReq.contentAscii();
                                                 switch (content) {
                                                     case "OK":
                                                         return HealthCheckUpdateResult.HEALTHY;
                                                     case "KO":
                                                         return HealthCheckUpdateResult.UNHEALTHY;
                                                     case "NOOP":
                                                         return HealthCheckUpdateResult.AS_IS;
                                                     default:
                                                         throw HttpStatusException.of(HttpStatus.BAD_REQUEST);
                                                 }
                                             });
                                         })
                                         .build());
            sb.decorator(LoggingService.builder().logger(logger).newDecorator());
            sb.gracefulShutdownTimeout(Duration.ofSeconds(10), Duration.ofSeconds(10));
            sb.disableServerHeader();
            sb.disableDateHeader();
        }
    };

    @AfterAll
    static void ensureScheduledHealthCheckerStopped() {
        assertThat(((ScheduledHealthChecker) unfinishedHealthChecker).isActive()).isTrue();
        server.stop().join();
        assertThat(((ScheduledHealthChecker) unfinishedHealthChecker).isActive()).isFalse();
    }

    @BeforeEach
    void setUp() {
        reset(logger);
        when(logger.isDebugEnabled()).thenReturn(true);
        checker.setHealthy(true);
    }

    @AfterEach
    void ensureNoPendingResponses() {
        server.server().serviceConfigs().forEach(cfg -> {
            final HealthCheckService service = cfg.service().as(HealthCheckService.class);
            if (service != null) {
                await().untilAsserted(() -> {
                    if (service.pendingHealthyResponses != null) {
                        assertThat(service.pendingHealthyResponses).isEmpty();
                    }
                    if (service.pendingUnhealthyResponses != null) {
                        assertThat(service.pendingUnhealthyResponses).isEmpty();
                    }
                });
            }
        });
    }

    @Test
    void getWhenHealthy() throws Exception {
        assertResponseEquals("GET /hc HTTP/1.0",
                             "HTTP/1.1 200 OK\r\n" +
                             "content-type: application/json; charset=utf-8\r\n" +
                             "armeria-lphc: 60, 5\r\n" +
                             "content-length: 16\r\n\r\n" +
                             "{\"healthy\":true}");
        verifyDebugEnabled(logger);
        verifyNoMoreInteractions(logger);
    }

    @Test
    void getWhenUnhealthy() throws Exception {
        checker.setHealthy(false);
        assertResponseEquals("GET /hc HTTP/1.0",
                             "HTTP/1.1 503 Service Unavailable\r\n" +
                             "content-type: application/json; charset=utf-8\r\n" +
                             "armeria-lphc: 60, 5\r\n" +
                             "content-length: 17\r\n\r\n" +
                             "{\"healthy\":false}");
        await().untilAsserted(() -> {
            verify(logger).debug(anyString(), any(), any());
        });
    }

    @Test
    void headWhenHealthy() throws Exception {
        assertResponseEquals("HEAD /hc HTTP/1.0",
                             "HTTP/1.1 200 OK\r\n" +
                             "content-type: application/json; charset=utf-8\r\n" +
                             "armeria-lphc: 60, 5\r\n" +
                             "content-length: 16\r\n\r\n");
        verifyDebugEnabled(logger);
        verifyNoMoreInteractions(logger);
    }

    @Test
    void headWhenUnhealthy() throws Exception {
        checker.setHealthy(false);
        assertResponseEquals("HEAD /hc HTTP/1.0",
                             "HTTP/1.1 503 Service Unavailable\r\n" +
                             "content-type: application/json; charset=utf-8\r\n" +
                             "armeria-lphc: 60, 5\r\n" +
                             "content-length: 17\r\n\r\n");
        verify(logger).debug(anyString(), any(), any());
    }

    private static void assertResponseEquals(String request, String expectedResponse) throws Exception {
        final int port = server.httpPort();
        try (Socket s = new Socket(NetUtil.LOCALHOST, port)) {
            s.setSoTimeout(10000);
            final InputStream in = s.getInputStream();
            final OutputStream out = s.getOutputStream();
            out.write((request + "\r\n\r\n").getBytes(StandardCharsets.US_ASCII));

            // Should neither be chunked nor have content.
            assertThat(new String(ByteStreams.toByteArray(in), StandardCharsets.UTF_8))
                    .isEqualTo(expectedResponse);
        }
    }

    @Test
    void waitUntilUnhealthy() {
        final CompletableFuture<AggregatedHttpResponse> f = sendLongPollingGet("healthy");

        // Should not wake up until the server becomes unhealthy.
        assertThatThrownBy(() -> f.get(1, TimeUnit.SECONDS))
                .isInstanceOf(TimeoutException.class);

        // Make the server unhealthy so the response comes in.
        checker.setHealthy(false);
        assertThat(f.join()).isEqualTo(AggregatedHttpResponse.of(
                ImmutableList.of(ResponseHeaders.builder(HttpStatus.PROCESSING)
                                                .set("armeria-lphc", "60, 5")
                                                .build()),
                ResponseHeaders.of(HttpStatus.SERVICE_UNAVAILABLE,
                                   HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8,
                                   "armeria-lphc", "60, 5"),
                HttpData.ofUtf8("{\"healthy\":false}"),
                HttpHeaders.of()));
    }

    @Test
    void waitUntilUnhealthyWithImmediateWakeup() throws Exception {
        // Make the server unhealthy.
        checker.setHealthy(false);

        final CompletableFuture<AggregatedHttpResponse> f = sendLongPollingGet("healthy");

        // The server is unhealthy already, so the response has to come in immediately.
        assertThat(f.get()).isEqualTo(AggregatedHttpResponse.of(
                ResponseHeaders.of(HttpStatus.SERVICE_UNAVAILABLE,
                                   HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8,
                                   "armeria-lphc", "60, 5"),
                HttpData.ofUtf8("{\"healthy\":false}")));
    }

    @Test
    void waitUntilHealthy() throws Exception {
        // Make the server unhealthy.
        checker.setHealthy(false);

        final CompletableFuture<AggregatedHttpResponse> f = sendLongPollingGet("unhealthy");

        // Should not wake up until the server becomes unhealthy.
        assertThatThrownBy(() -> f.get(1, TimeUnit.SECONDS))
                .isInstanceOf(TimeoutException.class);

        // Make the server healthy so the response comes in.
        checker.setHealthy(true);
        assertThat(f.get()).isEqualTo(AggregatedHttpResponse.of(
                ImmutableList.of(ResponseHeaders.builder(HttpStatus.PROCESSING)
                                                .set("armeria-lphc", "60, 5")
                                                .build()),
                ResponseHeaders.of(HttpStatus.OK,
                                   HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8,
                                   "armeria-lphc", "60, 5"),
                HttpData.ofUtf8("{\"healthy\":true}"),
                HttpHeaders.of()));
    }

    @Test
    void waitUntilHealthyWithImmediateWakeUp() throws Exception {
        final CompletableFuture<AggregatedHttpResponse> f = sendLongPollingGet("unhealthy");

        // The server is healthy already, so the response has to come in immediately.
        assertThat(f.get()).isEqualTo(AggregatedHttpResponse.of(
                ResponseHeaders.of(HttpStatus.OK,
                                   HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8,
                                   "armeria-lphc", "60, 5"),
                HttpData.ofUtf8("{\"healthy\":true}")));
    }

    @Test
    void waitTimeout() throws Exception {
        final AggregatedHttpResponse res = sendLongPollingGet("healthy", 1).get();
        assertThat(res).isEqualTo(AggregatedHttpResponse.of(
                ImmutableList.of(ResponseHeaders.builder(HttpStatus.PROCESSING)
                                                .set("armeria-lphc", "60, 5")
                                                .build()),
                ResponseHeaders.builder()
                               .endOfStream(true)
                               .status(HttpStatus.NOT_MODIFIED)
                               .contentType(MediaType.JSON_UTF_8)
                               .set("armeria-lphc", "60, 5")
                               .build(),
                HttpData.empty(),
                HttpHeaders.of()));
    }

    @Test
    void waitWithWrongMethod() throws Exception {
        final WebClient client = WebClient.of(server.httpUri());
        final CompletableFuture<AggregatedHttpResponse> f = client.execute(
                RequestHeaders.of(HttpMethod.POST, "/hc_custom",
                                  HttpHeaderNames.PREFER, "wait=60",
                                  HttpHeaderNames.IF_NONE_MATCH, "\"healthy\"")).aggregate();
        assertThat(f.get().status()).isEqualTo(HttpStatus.METHOD_NOT_ALLOWED);
        verifyDebugEnabled(logger);
        verifyNoMoreInteractions(logger);
    }

    @Test
    void waitWithWrongTimeout() throws Exception {
        final AggregatedHttpResponse res = sendLongPollingGet("healthy", -1).get();
        assertThat(res.status()).isEqualTo(HttpStatus.BAD_REQUEST);
        verifyDebugEnabled(logger);
        verifyNoMoreInteractions(logger);
    }

    @Test
    void waitWithOtherETag() throws Exception {
        // A never-matching etag must disable polling.
        final AggregatedHttpResponse res = sendLongPollingGet("whatever", 1).get();
        assertThat(res.status()).isEqualTo(HttpStatus.OK);
        verifyDebugEnabled(logger);
        verifyNoMoreInteractions(logger);
    }

    @Test
    void longPollingDisabled() throws Exception {
        final WebClient client = WebClient.of(server.httpUri());
        final CompletableFuture<AggregatedHttpResponse> f = client.execute(
                RequestHeaders.of(HttpMethod.GET, "/hc_long_polling_disabled",
                                  HttpHeaderNames.PREFER, "wait=60",
                                  HttpHeaderNames.IF_NONE_MATCH, "\"healthy\"")).aggregate();
        assertThat(f.get(10, TimeUnit.SECONDS)).isEqualTo(AggregatedHttpResponse.of(
                ResponseHeaders.of(HttpStatus.OK,
                                   HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8,
                                   "armeria-lphc", "0, 0"),
                HttpData.ofUtf8("{\"healthy\":true}")));
        verifyDebugEnabled(logger);
        verifyNoMoreInteractions(logger);
    }

    @Test
    void notUpdatableByDefault() throws Exception {
        final BlockingWebClient client = BlockingWebClient.of(server.httpUri());
        final AggregatedHttpResponse res = client.execute(RequestHeaders.of(HttpMethod.POST, "/hc"),
                                                          "{\"healthy\":false}");
        assertThat(res.status()).isEqualTo(HttpStatus.METHOD_NOT_ALLOWED);
        verifyDebugEnabled(logger);
        verifyNoMoreInteractions(logger);
    }

    @Test
    void updateUsingPutOrPost() {
        final BlockingWebClient client = BlockingWebClient.of(server.httpUri());

        // Make unhealthy.
        final AggregatedHttpResponse res1 = client.execute(RequestHeaders.of(HttpMethod.PUT, "/hc_updatable"),
                                                           "{\"healthy\":false}");
        assertThat(res1).isEqualTo(AggregatedHttpResponse.of(
                ResponseHeaders.of(HttpStatus.SERVICE_UNAVAILABLE,
                                   HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8,
                                   "armeria-lphc", "60, 5"),
                HttpData.ofUtf8("{\"healthy\":false}")));

        // Make healthy.
        final AggregatedHttpResponse res2 = client.execute(RequestHeaders.of(HttpMethod.POST, "/hc_updatable"),
                                                           "{\"healthy\":true}");
        assertThat(res2).isEqualTo(AggregatedHttpResponse.of(
                ResponseHeaders.of(HttpStatus.OK,
                                   HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8,
                                   "armeria-lphc", "60, 5"),
                HttpData.ofUtf8("{\"healthy\":true}")));
    }

    @Test
    void updateUsingPatch() {
        final BlockingWebClient client = BlockingWebClient.of(server.httpUri());

        // Make unhealthy.
        final AggregatedHttpResponse res1 = client.execute(
                RequestHeaders.of(HttpMethod.PATCH, "/hc_updatable"),
                "[{\"op\":\"replace\",\"path\":\"/healthy\",\"value\":false}]");
        assertThat(res1).isEqualTo(AggregatedHttpResponse.of(
                ResponseHeaders.of(HttpStatus.SERVICE_UNAVAILABLE,
                                   HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8,
                                   "armeria-lphc", "60, 5"),
                HttpData.ofUtf8("{\"healthy\":false}")));

        // Make healthy.
        final AggregatedHttpResponse res2 = client.execute(
                RequestHeaders.of(HttpMethod.PATCH, "/hc_updatable"),
                "[{\"op\":\"replace\",\"path\":\"/healthy\",\"value\":true}]");
        assertThat(res2).isEqualTo(AggregatedHttpResponse.of(
                ResponseHeaders.of(HttpStatus.OK,
                                   HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8,
                                   "armeria-lphc", "60, 5"),
                HttpData.ofUtf8("{\"healthy\":true}")));
    }

    @Test
    void updateListener() {
        final BlockingWebClient client = BlockingWebClient.of(server.httpUri());

        capturedHealthy.set(null);

        // Make unhealthy.
        client.execute(RequestHeaders.of(HttpMethod.POST, "/hc_update_listener"), "{\"healthy\":false}");
        assertThat(capturedHealthy.get()).isFalse();

        capturedHealthy.set(null);

        // Make healthy.
        client.execute(RequestHeaders.of(HttpMethod.POST, "/hc_update_listener"), "{\"healthy\":true}");
        assertThat(capturedHealthy.get()).isTrue();
    }

    @Test
    void startUnhealthy() throws Exception {
        assertResponseEquals("GET /hc_unhealthy_at_startup HTTP/1.0",
                             "HTTP/1.1 503 Service Unavailable\r\n" +
                             "content-type: application/json; charset=utf-8\r\n" +
                             "armeria-lphc: 60, 5\r\n" +
                             "content-length: 17\r\n\r\n" +
                             "{\"healthy\":false}");
    }

    @Test
    void custom() {
        final BlockingWebClient client = BlockingWebClient.of(server.httpUri());

        // Make unhealthy.
        final AggregatedHttpResponse res1 = client.execute(RequestHeaders.of(HttpMethod.PUT, "/hc_custom"),
                                                           "KO");
        assertThat(res1).isEqualTo(AggregatedHttpResponse.of(
                ResponseHeaders.of(HttpStatus.SERVICE_UNAVAILABLE,
                                   HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8,
                                   "armeria-lphc", "60, 5"),
                HttpData.ofUtf8("not ok")));

        // Make healthy.
        final AggregatedHttpResponse res2 = client.execute(RequestHeaders.of(HttpMethod.PUT, "/hc_custom"),
                                                           "OK");
        assertThat(res2).isEqualTo(AggregatedHttpResponse.of(
                ResponseHeaders.of(HttpStatus.OK,
                                   HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8,
                                   "armeria-lphc", "60, 5"),
                HttpData.ofUtf8("ok")));

        // Send a no-op request.
        final AggregatedHttpResponse res3 = client.execute(RequestHeaders.of(HttpMethod.PUT, "/hc_custom"),
                                                           "NOOP");
        assertThat(res3).isEqualTo(AggregatedHttpResponse.of(
                ResponseHeaders.of(HttpStatus.OK,
                                   HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8,
                                   "armeria-lphc", "60, 5"),
                HttpData.ofUtf8("ok")));
    }

    @Test
    void customError() {
        final BlockingWebClient client = BlockingWebClient.of(server.httpUri());

        // Use an unsupported method.
        final AggregatedHttpResponse res1 = client.execute(RequestHeaders.of(HttpMethod.PATCH, "/hc_custom"));
        assertThat(res1.status()).isEqualTo(HttpStatus.METHOD_NOT_ALLOWED);

        // Send a wrong command.
        final AggregatedHttpResponse res2 = client.execute(RequestHeaders.of(HttpMethod.PUT, "/hc_custom"),
                                                           "BAD");
        assertThat(res2.status()).isEqualTo(HttpStatus.BAD_REQUEST);
    }

    private static void verifyDebugEnabled(Logger logger) {
        await().untilAsserted(() -> {
            // 2 times for the request and the response.
            verify(logger, times(2)).isDebugEnabled();
        });
    }

    private static CompletableFuture<AggregatedHttpResponse> sendLongPollingGet(String healthiness) {
        return sendLongPollingGet(healthiness, 120);
    }

    private static CompletableFuture<AggregatedHttpResponse> sendLongPollingGet(String healthiness,
                                                                                int timeoutSeconds) {
        final WebClient client = WebClient.of(server.httpUri());
        return client.execute(RequestHeaders.of(HttpMethod.GET, "/hc",
                                                HttpHeaderNames.PREFER, "wait=" + timeoutSeconds,
                                                HttpHeaderNames.IF_NONE_MATCH,
                                                '"' + healthiness + '"')).aggregate();
    }
}


text:
using System;
using Crossroads.Web.Common.MinistryPlatform;
using Newtonsoft.Json;

namespace MinistryPlatform.Translation.Models.DTO
{
    [MpRestApiTable(Name = "cr_Kiosk_Configs")]
    public class MpKioskConfigDto
    {
        [JsonProperty(PropertyName = "Kiosk_Config_ID")]
        public int KioskConfigId { get; set; }

        [JsonProperty(PropertyName = "_Kiosk_Identifier")]
        public Guid KioskIdentifier { get; set; }

        [JsonProperty(PropertyName = "Kiosk_Name")]
        public string KioskName { get; set; }

        [JsonProperty(PropertyName = "Kiosk_Description")]
        public string KioskDescription { get; set; }

        [JsonProperty(PropertyName = "Kiosk_Type_ID")]
        public int KioskTypeId { get; set; }

        [JsonProperty(PropertyName = "Location_ID")]
        public int LocationId { get; set; }

        [JsonProperty(PropertyName = "Congregation_ID")]
        public int CongregationId { get; set; }

        [JsonProperty(PropertyName = "Congregation_Name")]
        public string CongregationName { get; set; }

        [JsonProperty(PropertyName = "Room_ID")]
        public int RoomId { get; set; }

        [JsonProperty(PropertyName = "Room_Name")]
        public string RoomName { get; set; }

        [JsonProperty(PropertyName = "Start_Date")]
        public DateTime StartDate { get; set; }

        [JsonProperty(PropertyName = "End_Date")]
        public DateTime? EndDate { get; set; }

        [JsonProperty(PropertyName = "Printer_Map_ID")]
        public int? PrinterMapId { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// subsystem
//------------------------------------------
// synopsis:
// Class declaration for OODT subsystems
//
// description:
// Subsystems have containing and contained subsystems and "member" entries
// in the data dictionary.
//------------------------------------------
// Restrictions:
// ...
//------------------------------------------

#ifndef __subsystem
#define __subsystem

// include files

#include "objOper.h"
#include "ddict.h"
#include "subsys_header.h"
#include "steDocument.h"
#include "steTextNode.h"
#include "ddict.h"

#define SUBSYS_HEADER_NAME "ALL SUBSYSTEMS"

RelClass(Subsystem);

class Subsystem: public ddElement {
   friend class subsys_header;
public:
   define_relational(Subsystem, ddElement);
   copy_member(Subsystem);
   Subsystem(const char* name, appPtr smthdr = NULL);
   Subsystem(const Subsystem&);
   void print(ostream&, int) const;
   void send_string(ostream&) const;
   objTreePtr get_root() const;
   int save(void*, int);
   static Relational* restore(void*, app*, char* = 0);
   app* get_main_header();

   bool is_contained_in(SubsystemPtr) const;
   void add_to_subsys(SubsystemPtr, bool is_public);
   void add_subsys(SubsystemPtr, bool is_public);
   void add_to_subsys_nochk(SubsystemPtr, bool is_public);
   void add_subsys_nochk(SubsystemPtr, bool is_public);
   void add_element(HierarchicalPtr, bool is_public);
   void add_element(ddElementPtr, bool is_public);
   void add_selected_items(bool is_public);
   void make_public(RelationalPtr);
   void make_private(RelationalPtr);
private:
   Subsystem();
};

generate_descriptor(Subsystem, ddElement);

define_relation(pub_containing_subsys, pub_contained_subsys);
define_relation(pri_containing_subsys, pri_contained_subsys);
define_relation(pub_ddElement_of_subsys, pub_subsys_of_ddElement);
define_relation(pri_ddElement_of_subsys, pri_subsys_of_ddElement);

defrel_one_to_one(Subsystem,subsys,smtHeader,smthdr);
defrel_many_to_many(Subsystem,subsys,steTextNode,textnode);
defrel_many_to_many(Subsystem,subsys,steDocument,document);

#endif

/*
    START-LOG-------------------------------

    $Log: Subsystem.h  $
    Revision 1.1 1993/02/22 00:06:11EST builder
    made from unix file
 * Revision 1.2.1.2  1992/10/09  19:56:23  kws
 * Fix comments
 *

    END-LOG---------------------------------
*/


text:
using System.Web.Mvc;

namespace Oceanus.Service.Web.Controllers.Mvc
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}


text:
package om.sstvencoder.Modes;

import android.graphics.Bitmap;

import om.sstvencoder.ModeInterfaces.ModeSize;
import om.sstvencoder.Output.IOutput;
import om.sstvencoder.R;

@ModeSize(width = 320, height = 256)
@ModeDescription(name = R.string.action_pd90)
class PD90 extends PD {
    PD90(Bitmap bitmap, IOutput output) {
        super(bitmap, output);
        mVISCode = 99;
        mColorScanDurationMs = 170.24;
        mColorScanSamples = convertMsToSamples(mColorScanDurationMs);
    }
}


text:
<?php
namespace Controllers;
use Models,Resources;

include_once (dirname(__FILE__) . "/Main.php");

class Daftar extends Main{

	/**
		* @Author				: Localhost {Ferdhika Yudira}
		* @Email				: fer@dika.web.id
		* @Web					: http://dika.web.id
		* @Date					: 2015-02-18 23:24:18
	**/

	public function __construct(){
		parent::__construct();
		$this->dw = new Models\M_download;
		$this->pengguna = new Models\M_pengguna;
	}
	public function index(){
		$this->redirect('donlod');
	}

	public function file(){
        $this->global_data['data'] = $this->dw->tampilTop();

        $this->tampilan('topFile');
	}

	public function akun(){
        $this->global_data['data'] = $this->pengguna->tampilTop();

        $this->tampilan('topUser');
	}
}


text:
/**
 * Expose `Blink1`.
 */

exports = module.exports = Blink1;

/**
 * Initialize a new Blink1 reporter.
 *
 * @param {Runner} runner
 * @api public
 */

require('shelljs/global');

function Blink1(runner) {
  runner.on('start', function(){
    exec('blink1-tool --blue --blink 1')
  });

  runner.on('end', function(){
    if (this.failures)
      exec('blink1-tool --red');
    else
      exec('blink1-tool --green');
  });
}


text:
package org.apache.drill.metastore.operate;

import java.util.List;

/**
 * Abstract implementation of {@link Modify<T>} interface which contains
 * all boilerplace code for collecting overwrite units and delete operations.
 * Delete operations metadata types are validated
 * before adding to the list of pending delete operations.
 *
 * @param <T> Metastore metadata unit
 */
public abstract class AbstractModify<T> implements Modify<T> {

  private final MetadataTypeValidator metadataTypeValidator;

  protected AbstractModify(MetadataTypeValidator metadataTypeValidator) {
    this.metadataTypeValidator = metadataTypeValidator;
  }

  @Override
  public final Modify<T> overwrite(List<T> units) {
    addOverwrite(units);
    return this;
  }

  @Override
  public final Modify<T> delete(Delete delete) {
    metadataTypeValidator.validate(delete.metadataTypes());
    addDelete(delete);
    return this;
  }

  /**
   * Adds overwrite operation to the list of pending operations.
   * Is used to ensure operations execution order.
   *
   * @param units list of Metastore metadata units
   */
  protected abstract void addOverwrite(List<T> units);

  /**
   * Adds delete operation to the list of pending operations.
   * Is used to ensure operations execution order.
   *
   * @param delete Metastore delete operation holder
   */
  protected abstract void addDelete(Delete delete);
}


text:
//
//  HCProgressiveAlertView.h
//
//  Created by hechen on 2017/9/20.
//

#import <UIKit/UIKit.h>

/// Notification received when background view receive touch event.
extern NSString * _Nonnull const HCPAVDidReceiveTouchEventNotification;

/// Notification received when bottom button receive touch down inside event.
extern NSString * _Nonnull const HCPAVDidTouchDownInsideBottomButtonNotification;

/// Notification received when alert view will disappear (at the beginning of disappear animation).
extern NSString * _Nonnull const HCPAVWillDisappearNotification;

/// Notification received when alert view did disappear (at the end of disappear animation).
extern NSString * _Nonnull const HCPAVDidDisappearNotification;

/// Notification received when alert view will appear.
extern NSString * _Nonnull const HCPAVWillAppearNotification;

NS_ASSUME_NONNULL_BEGIN

/**

 */
@interface HCProgressiveAlertView : UIView

// ------------------------------------------------
// Appearance

// default is bold 17pt
@property (nonatomic) UIFont *titleTextFont;

// default is Black Color
@property (nonatomic) UIColor *titleTextColor;

// default is #007aff
@property (nonatomic) UIColor *progressForegroundColor;

// default is #c7c7c7
@property (nonatomic) UIColor *progressBackgroundColor;

// default is #BFBFBF
@property (nonatomic) UIColor *separatorColor;

// default is #007aff
@property (nonatomic) UIColor *cancelButtonTextColor;

// default is bold 17pt
@property (nonatomic) UIFont *cancelButtonTextFont;

// default is 0.15
@property (nonatomic) NSTimeInterval fadeInAnimationDuration;

// default is 0.15
@property (nonatomic) NSTimeInterval fadeOutAnimationDuration;

// default is 31
@property (nonatomic) CGFloat progressCircleRadius;

// default is 3
@property (nonatomic) CGFloat progressCircleThickness;

// default is 14
@property (nonatomic) CGFloat alertViewCornerRadius;

// default is 3
@property (nonatomic) CGFloat completionSignThickness;

// default is #007aff
@property (nonatomic) UIColor *completionSignColor;

// --------------------------------------------------
// Parameters for business logic

@property (nonatomic) NSString *topTitle;

@property (nonatomic) NSString *bottomButtonText;

@property (nonatomic) CGFloat progress;

@property (nonatomic, copy) void(^bottomButtonClickedBlock)(void);

@property (nonatomic, copy) void(^backgroundViewClickedBlock)(void);

// --------------------------------------------------
// Public Methods

+ (instancetype)sharedView;

- (BOOL)isVisible;

- (void)show;

- (void)dismiss;

- (void)dismissWithCompletion:(nullable void(^)(void))completion;

@end

NS_ASSUME_NONNULL_END


text:
from oslo_serialization import jsonutils

from nova import test
from nova.tests.unit.api.openstack import fakes
import nova.tests.unit.image.fake

class UrlmapTest(test.NoDBTestCase):
    def setUp(self):
        super(UrlmapTest, self).setUp()
        nova.tests.unit.image.fake.stub_out_image_service(self)

    def tearDown(self):
        super(UrlmapTest, self).tearDown()
        nova.tests.unit.image.fake.FakeImageService_reset()

    def test_path_version_v2(self):
        # Test URL path specifying v2 returns v2 content.
        req = fakes.HTTPRequest.blank('/v2/')
        req.accept = "application/json"
        res = req.get_response(fakes.wsgi_app_v21(v2_compatible=True))
        self.assertEqual(200, res.status_int)
        self.assertEqual("application/json", res.content_type)
        body = jsonutils.loads(res.body)
        self.assertEqual('v2.0', body['version']['id'])

    def test_content_type_version_v2(self):
        # Test Content-Type specifying v2 returns v2 content.
        req = fakes.HTTPRequest.blank('/')
        req.content_type = "application/json;version=2"
        req.accept = "application/json"
        res = req.get_response(fakes.wsgi_app_v21(v2_compatible=True))
        self.assertEqual(200, res.status_int)
        self.assertEqual("application/json", res.content_type)
        body = jsonutils.loads(res.body)
        self.assertEqual('v2.0', body['version']['id'])

    def test_accept_version_v2(self):
        # Test Accept header specifying v2 returns v2 content.
        req = fakes.HTTPRequest.blank('/')
        req.accept = "application/json;version=2"
        res = req.get_response(fakes.wsgi_app_v21(v2_compatible=True))
        self.assertEqual(200, res.status_int)
        self.assertEqual("application/json", res.content_type)
        body = jsonutils.loads(res.body)
        self.assertEqual('v2.0', body['version']['id'])

    def test_accept_content_type(self):
        # Test Accept header specifying JSON returns JSON content.
        url = ('/v2/%s/images/cedef40a-ed67-4d10-800e-17455edce175' %
               fakes.FAKE_PROJECT_ID)
        req = fakes.HTTPRequest.blank(url)
        req.accept = "application/xml;q=0.8, application/json"
        res = req.get_response(fakes.wsgi_app_v21())
        self.assertEqual(200, res.status_int)
        self.assertEqual("application/json", res.content_type)
        body = jsonutils.loads(res.body)
        self.assertEqual('cedef40a-ed67-4d10-800e-17455edce175',
                         body['image']['id'])

    def test_path_version_v21(self):
        # Test URL path specifying v2.1 returns v2.1 content.
        req = fakes.HTTPRequest.blank('/v2.1/')
        req.accept = "application/json"
        res = req.get_response(fakes.wsgi_app_v21())
        self.assertEqual(200, res.status_int)
        self.assertEqual("application/json", res.content_type)
        body = jsonutils.loads(res.body)
        self.assertEqual('v2.1', body['version']['id'])

    def test_content_type_version_v21(self):
        # Test Content-Type specifying v2.1 returns v2 content.
        req = fakes.HTTPRequest.blank('/')
        req.content_type = "application/json;version=2.1"
        req.accept = "application/json"
        res = req.get_response(fakes.wsgi_app_v21())
        self.assertEqual(200, res.status_int)
        self.assertEqual("application/json", res.content_type)
        body = jsonutils.loads(res.body)
        self.assertEqual('v2.1', body['version']['id'])

    def test_accept_version_v21(self):
        # Test Accept header specifying v2.1 returns v2.1 content.
        req = fakes.HTTPRequest.blank('/')
        req.accept = "application/json;version=2.1"
        res = req.get_response(fakes.wsgi_app_v21())
        self.assertEqual(200, res.status_int)
        self.assertEqual("application/json", res.content_type)
        body = jsonutils.loads(res.body)
        self.assertEqual('v2.1', body['version']['id'])

    def test_accept_content_type_v21(self):
        # Test Accept header specifying JSON returns JSON content.
        req = fakes.HTTPRequest.blank('/')
        req.content_type = "application/json;version=2.1"
        req.accept = "application/xml;q=0.8, application/json"
        res = req.get_response(fakes.wsgi_app_v21())
        self.assertEqual(200, res.status_int)
        self.assertEqual("application/json", res.content_type)
        body = jsonutils.loads(res.body)
        self.assertEqual('v2.1', body['version']['id'])


text:
<tool name="OrthoFinder OnlyGroups" id="orthofinder_onlygroups" version="2.1.2">
    <description>finds orthogroups in a set of proteomes</description>
    <requirements>
        <requirement type="package" version="2.1.2">orthofinder</requirement>
    </requirements>
    <command>
    <![CDATA[
        ## prepare inputs
        #if $init.start == "fasta":
            #set $infiles = ""
            #for $input in $init.input_fasta
                ln -s '$input' '${input.element_identifier}.fasta' &&
                #set $infiles = $infiles + str($input.element_identifier) + ","
            #end for
            #set $infiles = $infiles[:-1]
        #elif $init.start == "blast":
            #set $infilesbl = ""
            #for $input in $init.input_blast_out
                ln -s '$input' '$input.element_identifier' &&
                #set $infilesbl = $infilesbl + str($input.element_identifier) + ","
            #end for
            #set $infilesbl = $infilesbl[:-1]

            #set $infilesfa = ""
            #for $input in $init.input_blast_fa
                ln -s '$input' '$input.element_identifier' &&
                #set $infilesfa = $infilesfa + str($input.element_identifier) + ","
            #end for
            #set $infilesfa = $infilesfa[:-1]

            ln -s $init.specIDs $init.specIDs.element_identifier &&
            ln -s $init.seqIDs $init.seqIDs.element_identifier &&
        #end if

        ## start Orthofinder
        orthofinder
        #if $init.start == "fasta":
            -f .
            -S $init.search.search_program
        #elif $init.start == "blast":
            -b .
        #end if

        -I $I -og -t \${GALAXY_SLOTS:-1} -a \${GALAXY_SLOTS:-1} &&

        #if $init.start == "fasta":
            mv Results_* results
            #if $init.search.search_program == "blast":
                #if $init.search.keepblastout:
                    && mkdir -p results/WorkingDirectory/blast results/WorkingDirectory/fa &&
                    mv results/WorkingDirectory/Blast* results/WorkingDirectory/blast/ &&
                    mv results/WorkingDirectory/*.fa results/WorkingDirectory/fa/
                #end if
            #end if
        #elif $init.start == "blast":
            mkdir results  &&
            mv *.csv results/ &&
            mv Orthogroups.txt results/
        #end if
    ]]>
    </command>
    <inputs>
        <!-- Control where Orthofinder starts -->
        <conditional name="init">
            <param name="start" type="select" label="Orthofinder starting point" help="OrthoFinder_OnlyGroups works in 2 steps. Choose 'From fasta proteomes' to run OrthoFinder_OnlyGroups from scratch and 'From blast results' if you have all the blast results from a previous OrthoFinder_OnlyGroups run.">
                <option value="fasta" selected="true">From fasta proteomes</option>
                <option value="blast">From blast results</option>
            </param>

            <when value="fasta">
                <param name="input_fasta" type="data" format="fasta" multiple="true" label="Select input fasta proteomes" help="One fasta file per species; species and sequences names in the results will remain the same than in the input files."/>
                <conditional name="search">
                    <param name="search_program" type="select" label="Sequence search program" help="Choose between blast, blast_gz, diamond">
                        <option value="blast" selected="true">blast</option>
                        <option value="blast_gz">blast_gz</option>
                        <option value="diamond">diamond</option>
                    </param>
                    <when value="blast">
                        <param name="keepblastout" type="boolean" checked="true" label="Do you want to get the blast results?" help="Used to re-run OrthoFinder_OnlyGroups from pre-computed blast results"/>
                    </when>
                    <when value="diamond"></when>
                    <when value="blast_gz"></when>
                </conditional>
            </when>

            <when value="blast">
                <param name="input_blast_out" type="data_collection" collection_type="list" format="txt" label="Select the pre-computed blast files" help="blastX_Y.txt files from the blast output files of a previous OrthoFinder_OnlyGroups run." />
                <param name="input_blast_fa" type="data_collection" collection_type="list" format="fasta" label="Select the fasta files" help="= SpeciesX.fa files from the blast output files of a previous OrthoFinder_OnlyGroups run." />
                <param name="specIDs" type="data" format="txt" label="Select the SpeciesIds file" help="SpeciesIDs.txt file from the blast output files of a previous OrthoFinder_OnlyGroups run."/>
                <param name="seqIDs" type="data" format="txt" label="Select the SequencesIds file" help="SequencesIDs.txt file from the blast output files of a previous OrthoFinder_OnlyGroups run."/>
            </when>
        </conditional>
        <param argument="-I" type="float" value="1.5" label="Inflation parameter" help="Modify inflation parameter for MCL. Not recommended." />
    </inputs>
    <outputs>
        <!-- Orthogroups results -->
        <data format="txt" name="orthogroups1" label="Orthogroups.txt" from_work_dir="results/Orthogroups.txt" />
        <data format="csv" name="orthogroups2" label="Orthogroups.csv" from_work_dir="results/Orthogroups.csv" />
        <data format="csv" name="specs_overlap" label="Orthogroups_SpeciesOverlaps.csv" from_work_dir="results/Orthogroups_SpeciesOverlaps.csv" />
        <data format="csv" name="unassigned_genes" label="Orthogroups_UnassignedGenes.csv" from_work_dir="results/Orthogroups_UnassignedGenes.csv" />
        <data format="csv" name="stat_overall" label="Statistics_Overall.csv" from_work_dir="results/Statistics_Overall.csv" />
        <data format="csv" name="stat_specs" label="Statistics_PerSpecies.csv" from_work_dir="results/Statistics_PerSpecies.csv" />

        <!-- working directory : blast outputs-->
        <collection name="wdblast" type="list" label="Blast_outputs">
            <discover_datasets pattern="__name_and_ext__" directory="results/WorkingDirectory/blast" />
            <filter>init['start'] == "fasta" and init['search']['search_program'] == "blast" and init['search']['keepblastout']</filter>
        </collection>
        <collection name="wdfasta" type="list" label="Fasta_from_blast" >
            <discover_datasets pattern="(?P<designation>.+)\.fa" directory="results/WorkingDirectory/fa" format="fasta" />
            <filter>init['start'] == "fasta" and init['search']['search_program'] == "blast" and init['search']['keepblastout']</filter>
        </collection>
        <collection name="genetrees" type="list" label="Gene trees">
            <discover_datasets pattern="(?P<designation>.+)\.txt" directory="results/WorkingDirectory/trees" format="nhx" />
            <filter>dogenetrees</filter>
        </collection>
        <data format="txt" name="SpeciesIDs" label="SpeciesIDs.txt" from_work_dir="results/WorkingDirectory/SpeciesIDs.txt" >
            <filter>init['start'] == "fasta" and init['search']['search_program'] == "blast" and init['search']['keepblastout']"</filter>
        </data>
        <data format="txt" name="SequenceIDs" label="SequencesIDs.txt" from_work_dir="results/WorkingDirectory/SequenceIDs.txt" >
            <filter>init['start'] == "fasta" and init['search']['search_program'] == "blast" and init['search']['keepblastout']</filter>
        </data>
    </outputs>
    <tests>
        <!-- test orthofinder -f . -og when input files has no extension fasta/faa/fa ... -->
        <test>
            <conditional name="init">
                <param name="start" value="fasta" />
                <param name="input_fasta" ftype="fasta" value="inputs/no_fa_ext/AcAcaud_trinity,inputs/no_fa_ext/AmAmphi_trinity,inputs/no_fa_ext/ApApomp_trinity,inputs/no_fa_ext/AsAsp1_trinity" />
                <conditional name="search">
                    <param name="search_program" value="blast"/>
                    <param name="keepblastout" value="false" />
                </conditional>
            </conditional>
            <param name="inflation" value="1.5" />
            <output name="specs_overlap">
                <assert_contents>
                    <has_text text="AcAcaud_trinity"/>
                    <has_text text="AmAmphi_trinity"/>
                    <has_text text="ApApomp_trinity"/>
                    <has_text text="AsAsp1_trinity"/>
                    <has_n_columns n="5"/>
                </assert_contents>
            </output>
            <output name="unassigned_genes">
                <assert_contents>
                    <has_text text="AcAcaud_trinity"/>
                    <has_text text="AmAmphi_trinity"/>
                    <has_text text="ApApomp_trinity"/>
                    <has_text text="AsAsp1_trinity"/>
                    <has_n_columns n="5"/>
                </assert_contents>
            </output>
            <output name="stat_overall">
                <assert_contents>
                    <has_text text="Number of genes in orthogroups"/>
                    <has_text text="Number of unassigned genes"/>
                    <has_text text="Percentage of orthogroups"/>
                    <has_text text="Number of orthogroups"/>
                    <has_text text="Number of genes"/>
                    <has_text text="G50 (assigned genes)"/>
                    <has_text text="G50 (all genes)"/>
                    <has_text text="O50 (assigned genes)"/>
                    <has_text text="O50 (all genes)"/>
                </assert_contents>
            </output>
            <output name="stat_specs">
                <assert_contents>
                    <has_text text="AcAcaud_trinity"/>
                    <has_text text="AmAmphi_trinity"/>
                    <has_text text="ApApomp_trinity"/>
                    <has_text text="AsAsp1_trinity"/>
                    <has_text text="Number of genes per-species in orthogroup"/>
                    <has_text text="Percentage of orthogroups"/>
                    <has_text text="Number of orthogroups"/>
                    <has_text text="Number of genes"/>
                    <has_n_columns n="5"/>
                </assert_contents>
            </output>
        </test>
        <!-- test orthofinder -f -og -->
        <test>
            <conditional name="init">
                <param name="start" value="fasta" />
                <param name="input_fasta" ftype="fasta" value="inputs/proteomes/Mycoplasma_agalactiae.faa,inputs/proteomes/Mycoplasma_gallisepticum.faa,inputs/proteomes/Mycoplasma_genitalium.faa,inputs/proteomes/Mycoplasma_hyopneumoniae.faa" />
                <conditional name="search">
                    <param name="search_program" value="blast"/>
                    <param name="keepblastout" value="false" />
                </conditional>
            </conditional>
            <param name="inflation" value="1.5" />
            <output name="specs_overlap">
                <assert_contents>
                    <has_text text="Mycoplasma_agalactiae"/>
                    <has_text text="Mycoplasma_gallisepticum"/>
                    <has_text text="Mycoplasma_genitalium"/>
                    <has_text text="Mycoplasma_hyopneumoniae"/>
                    <has_n_columns n="5"/>
                </assert_contents>
            </output>
            <output name="unassigned_genes">
                <assert_contents>
                    <has_text text="Mycoplasma_agalactiae"/>
                    <has_text text="Mycoplasma_gallisepticum"/>
                    <has_text text="Mycoplasma_genitalium"/>
                    <has_text text="Mycoplasma_hyopneumoniae"/>
                    <has_n_columns n="5"/>
                </assert_contents>
            </output>
            <output name="stat_overall">
                <assert_contents>
                    <has_text text="Number of genes in orthogroups"/>
                    <has_text text="Number of unassigned genes"/>
                    <has_text text="Percentage of orthogroups"/>
                    <has_text text="Number of orthogroups"/>
                    <has_text text="Number of genes"/>
                    <has_text text="G50 (assigned genes)"/>
                    <has_text text="G50 (all genes)"/>
                    <has_text text="O50 (assigned genes)"/>
                    <has_text text="O50 (all genes)"/>
                </assert_contents>
            </output>
            <output name="stat_specs">
                <assert_contents>
                    <has_text text="Mycoplasma_agalactiae"/>
                    <has_text text="Mycoplasma_gallisepticum"/>
                    <has_text text="Mycoplasma_genitalium"/>
                    <has_text text="Mycoplasma_hyopneumoniae"/>
                    <has_text text="Number of genes per-species in orthogroup"/>
                    <has_text text="Percentage of orthogroups"/>
                    <has_text text="Number of orthogroups"/>
                    <has_text text="Number of genes"/>
                    <has_n_columns n="5"/>
                </assert_contents>
            </output>
        </test>

        <test>
            <conditional name="init">
                <param name="start" value="fasta" />
                <param name="input_fasta" ftype="fasta" value="inputs/proteomes/Mycoplasma_agalactiae.faa,inputs/proteomes/Mycoplasma_gallisepticum.faa,inputs/proteomes/Mycoplasma_genitalium.faa,inputs/proteomes/Mycoplasma_hyopneumoniae.faa" />
                <conditional name="search">
                    <param name="search_program" value="blast"/>
                    <param name="keepblastout" value="true" />
                </conditional>
            </conditional>
            <param name="inflation" value="1.5" />
            <output name="specs_overlap">
                <assert_contents>
                    <has_text text="Mycoplasma_agalactiae"/>
                    <has_text text="Mycoplasma_gallisepticum"/>
                    <has_text text="Mycoplasma_genitalium"/>
                    <has_text text="Mycoplasma_hyopneumoniae"/>
                    <has_n_columns n="5"/>
                </assert_contents>
            </output>
            <output name="unassigned_genes">
                <assert_contents>
                    <has_text text="Mycoplasma_agalactiae"/>
                    <has_text text="Mycoplasma_gallisepticum"/>
                    <has_text text="Mycoplasma_genitalium"/>
                    <has_text text="Mycoplasma_hyopneumoniae"/>
                    <has_n_columns n="5"/>
                </assert_contents>
            </output>
            <output name="stat_overall">
                <assert_contents>
                    <has_text text="Number of genes in orthogroups"/>
                    <has_text text="Number of unassigned genes"/>
                    <has_text text="Percentage of orthogroups"/>
                    <has_text text="Number of orthogroups"/>
                    <has_text text="Number of genes"/>
                    <has_text text="G50 (assigned genes)"/>
                    <has_text text="G50 (all genes)"/>
                    <has_text text="O50 (assigned genes)"/>
                    <has_text text="O50 (all genes)"/>
                </assert_contents>
            </output>
            <output name="stat_specs">
                <assert_contents>
                    <has_text text="Mycoplasma_agalactiae"/>
                    <has_text text="Mycoplasma_gallisepticum"/>
                    <has_text text="Mycoplasma_genitalium"/>
                    <has_text text="Mycoplasma_hyopneumoniae"/>
                    <has_text text="Number of genes per-species in orthogroup"/>
                    <has_text text="Percentage of orthogroups"/>
                    <has_text text="Number of orthogroups"/>
                    <has_text text="Number of genes"/>
                    <has_n_columns n="5"/>
                </assert_contents>
            </output>
            <output name="SequenceIDs" value="inputs/blastids/SequenceIDs.txt" />
            <output_collection name="wdfasta" type="list" count="4"/>
            <output_collection name="wdblast" type="list" count="16"/>
        </test>

        <!-- test -S diamond -->
        <test>
            <conditional name="init">
                <param name="start" value="fasta" />
                <param name="input_fasta" ftype="fasta" value="inputs/proteomes/Mycoplasma_agalactiae.faa,inputs/proteomes/Mycoplasma_gallisepticum.faa,inputs/proteomes/Mycoplasma_genitalium.faa,inputs/proteomes/Mycoplasma_hyopneumoniae.faa" />
                <conditional name="search">
                    <param name="search_program" value="diamond"/>
                </conditional>
            </conditional>
            <param name="inflation" value="1.5" />
            <output name="specs_overlap">
                <assert_contents>
                    <has_text text="Mycoplasma_agalactiae"/>
                    <has_text text="Mycoplasma_gallisepticum"/>
                    <has_text text="Mycoplasma_genitalium"/>
                    <has_text text="Mycoplasma_hyopneumoniae"/>
                    <has_n_columns n="5"/>
                </assert_contents>
            </output>
            <output name="unassigned_genes">
                <assert_contents>
                    <has_text text="Mycoplasma_agalactiae"/>
                    <has_text text="Mycoplasma_gallisepticum"/>
                    <has_text text="Mycoplasma_genitalium"/>
                    <has_text text="Mycoplasma_hyopneumoniae"/>
                    <has_n_columns n="5"/>
                </assert_contents>
            </output>
            <output name="stat_overall">
                <assert_contents>
                    <has_text text="Number of genes in orthogroups"/>
                    <has_text text="Number of unassigned genes"/>
                    <has_text text="Percentage of orthogroups"/>
                    <has_text text="Number of orthogroups"/>
                    <has_text text="Number of genes"/>
                    <has_text text="G50 (assigned genes)"/>
                    <has_text text="G50 (all genes)"/>
                    <has_text text="O50 (assigned genes)"/>
                    <has_text text="O50 (all genes)"/>
                </assert_contents>
            </output>
            <output name="stat_specs">
                <assert_contents>
                    <has_text text="Mycoplasma_agalactiae"/>
                    <has_text text="Mycoplasma_gallisepticum"/>
                    <has_text text="Mycoplasma_genitalium"/>
                    <has_text text="Mycoplasma_hyopneumoniae"/>
                    <has_text text="Number of genes per-species in orthogroup"/>
                    <has_text text="Percentage of orthogroups"/>
                    <has_text text="Number of orthogroups"/>
                    <has_text text="Number of genes"/>
                    <has_n_columns n="5"/>
                </assert_contents>
            </output>
        </test>

        <!-- test orthofinder -b -og -->
        <test>
            <conditional name="init">
                <param name="start" value="blast" />
                <param name="input_blast_out">
                    <collection type="list">
                        <element name="Blast0_0.txt" value="inputs/blastout/Blast0_0.txt"/>
                        <element name="Blast0_1.txt" value="inputs/blastout/Blast0_1.txt"/>
                        <element name="Blast0_2.txt" value="inputs/blastout/Blast0_2.txt"/>
                        <element name="Blast0_3.txt" value="inputs/blastout/Blast0_3.txt"/>
                        <element name="Blast1_0.txt" value="inputs/blastout/Blast1_0.txt"/>
                        <element name="Blast1_1.txt" value="inputs/blastout/Blast1_1.txt"/>
                        <element name="Blast1_2.txt" value="inputs/blastout/Blast1_2.txt"/>
                        <element name="Blast1_3.txt" value="inputs/blastout/Blast1_3.txt"/>
                        <element name="Blast2_0.txt" value="inputs/blastout/Blast2_0.txt"/>
                        <element name="Blast2_1.txt" value="inputs/blastout/Blast2_1.txt"/>
                        <element name="Blast2_2.txt" value="inputs/blastout/Blast2_2.txt"/>
                        <element name="Blast2_3.txt" value="inputs/blastout/Blast2_3.txt"/>
                        <element name="Blast3_0.txt" value="inputs/blastout/Blast3_0.txt"/>
                        <element name="Blast3_1.txt" value="inputs/blastout/Blast3_1.txt"/>
                        <element name="Blast3_2.txt" value="inputs/blastout/Blast3_2.txt"/>
                        <element name="Blast3_3.txt" value="inputs/blastout/Blast3_3.txt"/>
                    </collection>
                </param>
                <param name="input_blast_fa">
                    <collection type="list">
                        <element name="Species0.fa" value="inputs/blastfa/Species0.fa"/>
                        <element name="Species1.fa" value="inputs/blastfa/Species1.fa"/>
                        <element name="Species2.fa" value="inputs/blastfa/Species2.fa"/>
                        <element name="Species3.fa" value="inputs/blastfa/Species3.fa"/>
                    </collection>
                </param>
                <param name="specIDs" ftype="txt" value="inputs/blastids/SpeciesIDs.txt"/>
                <param name="seqIDs" ftype="txt" value="inputs/blastids/SequenceIDs.txt"/>
            </conditional>
            <param name="inflation" value="1.5" />
            <output name="orthogroups1" value="results_fromblast/Orthogroups.txt"/>
            <output name="orthogroups2" value="results_fromblast/Orthogroups.csv"/>
            <output name="specs_overlap" value="results_fromblast/Orthogroups_SpeciesOverlaps.csv"/>
            <output name="unassigned_genes" value="results_fromblast/Orthogroups_UnassignedGenes.csv"/>
            <output name="stat_overall" value="results_fromblast/Statistics_Overall.csv" lines_diff="2"/>
            <output name="stat_specs" value="results_fromblast/Statistics_PerSpecies.csv"/>
        </test>
    </tests>
    <help>
======================
OrthoFinder OnlyGroups
======================

Full readme at https://github.com/davidemms/OrthoFinder/blob/master/README.md
Summary sketch at https://github.com/davidemms/OrthoFinder/blob/master/OrthoFinder-options.pdf

OrthoFinder is a fast, accurate and comprehensive analysis tool for comparative genomics. It finds orthologues and orthogroups infers gene trees for all orthogroups and infers a rooted species tree for the species being analysed. OrthoFinder also provides comprehensive statistics for comparative genomic analyses. OrthoFinder is simple to use and all you need to run it is a set of protein sequence files (one per species) in FASTA format (Emms, D.M. and Kelly, S., 2015).

.. class:: infomark

This galaxy tool implements the first part of the Orthofinder program, e.g. the clustering of orthogroups of genes.

If you have already ran OrthoFinder, the tool allows to re-run the analysis from the pre-computed blast-results.

-----------
Input files
-----------
    - When using "from fasta" option (e.g Orthofinder from scratch) : the input files are a set of proteomes in fasta format (on file per species). Choose this option if you have no OrthoFinder results yet.
    - When using "from blast results" option : the input files are all the following files from of a previous OrthoFinder run (these files appear only if you have chosen to keep them while launching a previous run):
        - A dataset collection / multiple datasets for the blast outputs
        - A dataset collection / multiple datasets for .fa files
        - The SpeciesIDs.txt file
        - The SequencesIDs.txt file

----------
Parameters
----------
    - Sequence search program : You can choose either blast, blast_gz, or diamond (diamond is faster)
    - Get the blast results : Check "Yes" if, while using blast as the sequence search program, you want to retrieve the blast output files
    - Inflation : the inflation parameter; modify this parameter is not recommended.

    </help>
    <citations>
        <citation type="doi">10.1186/s13059-015-0721-2</citation>
    </citations>
</tool>


text:
<!-- toc -->
## j.tools.executor

- /opt/jumpscale8/lib/JumpScale/tools/executor/ExecutorFactory.py

### Methods

#### get(*executor='localhost'*)

```
@param executor is an executor object, None or $hostname:$port or $ipaddr:$port or
    $hostname or $ipaddr

```

#### getJSAgentBased(*agentControllerClientKey, debug, checkok*)

#### getLocal(*jumpscale, debug, checkok*)

#### getSSHBased(*addr='localhost', port=22, login='root', passwd, debug, allow_agent=True, look_for_keys=True, timeout=5, usecache=True, passphrase*)

```
returns an ssh-based executor where:
allow_agent: uses the ssh-agent to connect
look_for_keys: will iterate over keys loaded on the ssh-agent and try to use them to
    authenticate
pushkey: authorizes itself on remote
pubkey: uses this particular key (path) to connect
usecache: gets cached executor if available. False to get a new one.

```

#### pushkey(*addr, passwd, keyname='', pubkey='', port=22, login='root'*)

```
@param keyname is name of key (pub)
@param pubkey is the content of the pub key

```

#### reset(*executor*)

```
reset remove the executor passed in argument from the cache.

```


text:
[![Build Status](https://travis-ci.org/GanfOfFourOrFive/reservira.svg?branch=master)](https://travis-ci.org/GanfOfFourOrFive/reservira)
[![Code Climate](https://codeclimate.com/github/GanfOfFourOrFive/reservira.png)](https://codeclimate.com/github/GanfOfFourOrFive/reservira)
[![Code Coverage](https://codeclimate.com/github/GanfOfFourOrFive/reservira/coverage.png)](https://codeclimate.com/github/GanfOfFourOrFive/reservira)
[![Dependency Status](https://gemnasium.com/GanfOfFourOrFive/reservira.svg)](https://gemnasium.com/GanfOfFourOrFive/reservira)

Esse sistema tem o fim didático e tem como objetivo servir de aprendizado através
do uso dos diversos recursos do Ruby on Rails, HTML 5, CSS 3 e Javascript. Também
tem o objetivo de apresentar as melhores práticas de desenvolvimento e trabalho em
equipe com colaboradores distribuidos, usando para isso diversas ferramentas como
Github, Travis CI, Hound CI, Gemnasium, Slack, Heroku e Code Climate.

## Como contribuir como desenvolvedor

### Baixando o projeto, implementando uma nova fixture e contribuindo no Github
O projeto usa o controle de versão [GIT-SCM](http://git-scm.com) e se caso você
ainda não conhece muito de GIT recomendamos que [assista esse tutorial completo]
(http://goo.gl/bLCO43) feito pelo [Fábio Akita](http://akitaonrails.com.br/).

- Faça um fork do projeto para a sua conta do github e clone no seu ambiente de
desenvolvimento usando o comando:

  git clone url-do-seu-clone

- Assuma a tarefa no Trello e então planeje o desenvolvimento de sua feature. O
ideal é criar um novo branch para a sua feature com o comando:

  git checkout -b nome-da-feature

- Utilize TDD/BDD para guiar o processo de design e desenvolvimento, não é uma sugestão, é sua
obrigação como desenvolvedor.
- Implementada a feature, certifique-se que todos os testes estão passando, e que
o seu código esteja limpo, caso contrário Hound CI e o Travis CI vão acabar com a sua
reputação no Github e na equipe.
- Use o comando pull do git para puxar os arquivos do projeto:

    git pull origin nome-da-feature

verifique se o Travis e Hound aprovaram sua submissão. Feito isso aguarde o code review.


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Dark Corners</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta name="description" content="WebGL game prototype">
	<meta name="author" content="Tapio Vierros">

	<link rel="shortcut icon" href="favicon.png" />
	<link href="css/bootstrap.min.css" rel="stylesheet">

	<link href="css/bootstrap-responsive.min.css" rel="stylesheet">

Dark Corners

This is a 3D first-person game prototype, which runs in the web browser thanks to WebGL.
					It's in early stages of development, so don't expect much more than walking around in a dungeon.

						Try demo!
						Try another scene!

						Oh no! Your browser or GPU doesn't seem to support WebGL.
						Unfortunately you can't play the game without it.

						<button type="button" class="close" data-dismiss="alert">×</button>
						This is an early alpha. Performance or compatibility has not
						been optimized and gameplay is mostly missing.

						<button type="button" class="close" data-dismiss="alert">×</button>
						You may be affected by ANGLE/browser bug.

						Try disabling shadows in the options and reloading the game if there are missing textures.

						<button type="button" class="close" data-dismiss="alert">×</button>
						You seem to be using Firefox. It has bad performance and reduced features.

						Check out Performance Tips or switch to Chrome.

3D environments with dynamic lighting

Enhanced immersion with physics engine

Create your own levels with a simple editor

High quality, yet freely licensed assets

Varying locations from caves to temples

						‹
						›

Requirements

Latest version of Chrome

Firefox kind of works too, but has bad performance and some missing features

Excellent dedicated GPU and drivers (both must not be blacklisted for WebGL by the browser vendors)

Fast CPU and 1GB of free RAM so that JavaScript runs well

About

This is a game prototype with a fantasy/mediaval setting. It's an experiment in
				creating a full-blown 3D browser game complete with physics and high quality assets.

Currently the engine is in a demoable state, but the actual game is missing.
				However, a different game using this engine has been completed and is featured
				below.

Features

Editor for creating and sharing more levels

High quality textures, models etc

Animated enemies

Path finding enemies

Rigid body dynamics, i.e. physics

Dynamic lighting with shadows

Post-processing effects

Troubleshooting

If you experience problems, follow these steps:

Check that your system fulfills the system requirements on the left.

Read the
						Known Issues wiki page.

Check out the
						Performance Tips wiki page if needed.

If the above didn't solve the problem, you are welcome to
						file an issue.

Editor

There is also a level editor for creating and editing levels for the game.
				For maximum productivity and minimal learning curve, the editor is 2D, but
				you can test your creation very easily with a push of a button.

Levels can be exported and then shared with friends.

Launch editor »

Contribute

This game is open source and you can freely study and modify it.
				The sources, including art assets are available at GitHub.

If you have patches, new 3d models or a kick-ass level, please make a
				pull request. In case of art, it is strongly recommended to also submit to
				Open Game Art.

Project page @ GitHub »

Derivative: Plasma Forks

Check out a small but complete scifi first-person shooter based on Dark Corners engine!

Plasma Forks »

© Tapio Vierros 2012
			 |
			Credits


text:
Originally published: 2009-03-31 16:24:51
Last updated: 2009-04-01 07:07:56
Author: oohay_email2004

This is my first successful attempt at threading in pyGTK.

Suggestions please.


text:
package org.insightech.er.editor.model.dbexport.ddl.validator.rule.column.impl;

import org.eclipse.core.resources.IMarker;
import org.insightech.er.ResourceString;
import org.insightech.er.editor.model.dbexport.ddl.validator.ValidateResult;
import org.insightech.er.editor.model.dbexport.ddl.validator.rule.column.ColumnRule;
import org.insightech.er.editor.model.diagram_contents.element.node.table.ERTable;
import org.insightech.er.editor.model.diagram_contents.element.node.table.column.NormalColumn;

public class NoColumnTypeRule extends ColumnRule {

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean validate(final ERTable table, final NormalColumn column) {
        if (column.getType() == null || column.getType().getAlias(table.getDiagram().getDatabase()) == null) {
            final ValidateResult validateResult = new ValidateResult();
            validateResult.setMessage(ResourceString.getResourceString("error.validate.no.column.type1") + table.getPhysicalName() + ResourceString.getResourceString("error.validate.no.column.type2") + column.getPhysicalName());
            validateResult.setLocation(table.getLogicalName());
            validateResult.setSeverity(IMarker.SEVERITY_WARNING);
            validateResult.setObject(table);

            addError(validateResult);
        }

        return true;
    }
}


text:
from setuptools import setup

setup(
    name='Antipodalpy',
    version=0.1,
    author='Robbert Verbruggen',
    packages=['antipodalpy'],
    url='https://github.com/rfverbruggen/antipodalpy',
    license='MIT',
    description='A python library to calculate the Antipodal point of a location on a sphere.',
    long_description=open('README.md').read(),
    platforms='Cross Platform',
    classifiers=[
        'Development Status :: 0.1 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2',
        'Topic :: Software Development'
        ]
)


text:
echo "adb" > /sys/class/android_usb/android0/functions
echo "1" > /sys/class/android_usb/f_adb/on
cp /supersu/aromafm.zip /cache/aromafm.zip


text:
import type { DropTargetMonitor } from '../../types';
import type { DropTargetHookSpec } from '../types';
import { DropTargetImpl } from './DropTargetImpl';
export declare function useDropTarget<O, R, P>(spec: DropTargetHookSpec<O, R, P>, monitor: DropTargetMonitor<O, R>): DropTargetImpl<O, R, P>;


text:
<form class="form-horizontal" name="form" novalidate ng-submit="ok()">

			{{t.LANGUAGE}} {{model.name}}

				{{t.LOCALE}}

					<select class="form-control" id="inputLocale" name="locale" ng-model="model.locale" ng-options="item.locale as (item.name + ' / ' + item.locale) for item in locales | orderBy:'name'">
						<option>..</option>
					</select>

				{{t.LANGUAGE}}

					<input type="text" class="form-control" id="inputName" placeholder="{{t.PLACEHOLDER_LANGUAGE}}" name="name" ng-model="model.name" required validation>

							<input type="checkbox" ng-model="model.is_active" ng-true-value="1" ng-false-value="0">
							{{t.ENABLED}}

				<button class="btn btn-success" type="submit">

					{{t.SAVE}}
				</button>

				<button class="btn btn-default" type="button" ng-click="cancel()">

					{{t.CANCEL}}
				</button>

</form>


text:
<?php
namespace ENC\Bundle\BackupRestoreBundle\Restore;

use ENC\Bundle\BackupRestoreBundle\Common\AbstractBackupRestore;

abstract class AbstractRestore extends AbstractBackupRestore implements RestoreInterface
{
}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/waldo_blue</item>
        <item name="colorPrimaryDark">@color/waldo_grey</item>
        <item name="colorAccent">@color/waldo_blue_dark</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="ThemeOverlay.MyNoTitleActivity" parent="AppTheme">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <!-- Dark Buttons -->
    <style name="ThemeOverlay.MyDarkButton" parent="ThemeOverlay.AppCompat.Dark">
        <item name="colorButtonNormal">@color/waldo_grey</item>
        <item name="android:textColor">@android:color/white</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="FullscreenTheme" parent="AppTheme">
        <item name="android:actionBarStyle">@style/FullscreenActionBarStyle</item>
        <item name="android:windowActionBarOverlay">true</item>
        <item name="android:windowBackground">@null</item>
        <item name="metaButtonBarStyle">?android:attr/buttonBarStyle</item>
        <item name="metaButtonBarButtonStyle">?android:attr/buttonBarButtonStyle</item>
    </style>

    <style name="FullscreenActionBarStyle" parent="Widget.AppCompat.ActionBar">
        <item name="android:background">@color/black_overlay</item>
    </style>

</resources>


text:
"""The tests for the Home Assistant HTTP component."""
# pylint: disable=protected-access
import logging
from ipaddress import ip_network
from unittest.mock import patch

import requests

from homeassistant import bootstrap, const
import homeassistant.components.http as http

from tests.common import get_test_instance_port, get_test_home_assistant

API_PASSWORD = 'test1234'
SERVER_PORT = get_test_instance_port()
HTTP_BASE = '127.0.0.1:{}'.format(SERVER_PORT)
HTTP_BASE_URL = 'http://{}'.format(HTTP_BASE)
HA_HEADERS = {
    const.HTTP_HEADER_HA_AUTH: API_PASSWORD,
    const.HTTP_HEADER_CONTENT_TYPE: const.CONTENT_TYPE_JSON,
}
# Don't add 127.0.0.1/::1 as trusted, as it may interfere with other test cases
TRUSTED_NETWORKS = ['192.0.2.0/24', '2001:DB8:ABCD::/48', '100.64.0.1',
                    'FD01:DB8::1']
TRUSTED_ADDRESSES = ['100.64.0.1', '192.0.2.100', 'FD01:DB8::1',
                     '2001:DB8:ABCD::1']
UNTRUSTED_ADDRESSES = ['198.51.100.1', '2001:DB8:FA1::1', '127.0.0.1', '::1']

CORS_ORIGINS = [HTTP_BASE_URL, HTTP_BASE]

hass = None

def _url(path=''):
    """Helper method to generate URLs."""
    return HTTP_BASE_URL + path

# pylint: disable=invalid-name
def setUpModule():
    """Initialize a Home Assistant server."""
    global hass

    hass = get_test_home_assistant()

    hass.bus.listen('test_event', lambda _: _)
    hass.states.set('test.test', 'a_state')

    bootstrap.setup_component(
        hass, http.DOMAIN, {
            http.DOMAIN: {
                http.CONF_API_PASSWORD: API_PASSWORD,
                http.CONF_SERVER_PORT: SERVER_PORT,
                http.CONF_CORS_ORIGINS: CORS_ORIGINS,
            }
        }
    )

    bootstrap.setup_component(hass, 'api')

    hass.http.trusted_networks = [
        ip_network(trusted_network)
        for trusted_network in TRUSTED_NETWORKS]

    hass.start()

# pylint: disable=invalid-name
def tearDownModule():
    """Stop the Home Assistant server."""
    hass.stop()

class TestHttp:
    """Test HTTP component."""

    def test_access_denied_without_password(self):
        """Test access without password."""
        req = requests.get(_url(const.URL_API))

        assert req.status_code == 401

    def test_access_denied_with_wrong_password_in_header(self):
        """Test access with wrong password."""
        req = requests.get(
            _url(const.URL_API),
            headers={const.HTTP_HEADER_HA_AUTH: 'wrongpassword'})

        assert req.status_code == 401

    def test_access_denied_with_x_forwarded_for(self, caplog):
        """Test access denied through the X-Forwarded-For http header."""
        hass.http.use_x_forwarded_for = True
        for remote_addr in UNTRUSTED_ADDRESSES:
            req = requests.get(_url(const.URL_API), headers={
                const.HTTP_HEADER_X_FORWARDED_FOR: remote_addr})

            assert req.status_code == 401, \
                "{} shouldn't be trusted".format(remote_addr)

    def test_access_denied_with_untrusted_ip(self, caplog):
        """Test access with an untrusted ip address."""
        for remote_addr in UNTRUSTED_ADDRESSES:
            with patch('homeassistant.components.http.'
                       'HomeAssistantWSGI.get_real_ip',
                       return_value=remote_addr):
                req = requests.get(
                    _url(const.URL_API), params={'api_password': ''})

                assert req.status_code == 401, \
                    "{} shouldn't be trusted".format(remote_addr)

    def test_access_with_password_in_header(self, caplog):
        """Test access with password in URL."""
        # Hide logging from requests package that we use to test logging
        caplog.set_level(
            logging.WARNING, logger='requests.packages.urllib3.connectionpool')

        req = requests.get(
            _url(const.URL_API),
            headers={const.HTTP_HEADER_HA_AUTH: API_PASSWORD})

        assert req.status_code == 200

        logs = caplog.text

        # assert const.URL_API in logs
        assert API_PASSWORD not in logs

    def test_access_denied_with_wrong_password_in_url(self):
        """Test access with wrong password."""
        req = requests.get(
            _url(const.URL_API), params={'api_password': 'wrongpassword'})

        assert req.status_code == 401

    def test_access_with_password_in_url(self, caplog):
        """Test access with password in URL."""
        # Hide logging from requests package that we use to test logging
        caplog.set_level(
            logging.WARNING, logger='requests.packages.urllib3.connectionpool')

        req = requests.get(
            _url(const.URL_API), params={'api_password': API_PASSWORD})

        assert req.status_code == 200

        logs = caplog.text

        # assert const.URL_API in logs
        assert API_PASSWORD not in logs

    def test_access_granted_with_x_forwarded_for(self, caplog):
        """Test access denied through the X-Forwarded-For http header."""
        hass.http.use_x_forwarded_for = True
        for remote_addr in TRUSTED_ADDRESSES:
            req = requests.get(_url(const.URL_API), headers={
                const.HTTP_HEADER_X_FORWARDED_FOR: remote_addr})

            assert req.status_code == 200, \
                "{} should be trusted".format(remote_addr)

    def test_access_granted_with_trusted_ip(self, caplog):
        """Test access with trusted addresses."""
        for remote_addr in TRUSTED_ADDRESSES:
            with patch('homeassistant.components.http.'
                       'HomeAssistantWSGI.get_real_ip',
                       return_value=remote_addr):
                req = requests.get(
                    _url(const.URL_API), params={'api_password': ''})

                assert req.status_code == 200, \
                    '{} should be trusted'.format(remote_addr)

    def test_cors_allowed_with_password_in_url(self):
        """Test cross origin resource sharing with password in url."""
        req = requests.get(_url(const.URL_API),
                           params={'api_password': API_PASSWORD},
                           headers={const.HTTP_HEADER_ORIGIN: HTTP_BASE_URL})

        allow_origin = const.HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN

        assert req.status_code == 200
        assert req.headers.get(allow_origin) == HTTP_BASE_URL

    def test_cors_allowed_with_password_in_header(self):
        """Test cross origin resource sharing with password in header."""
        headers = {
            const.HTTP_HEADER_HA_AUTH: API_PASSWORD,
            const.HTTP_HEADER_ORIGIN: HTTP_BASE_URL
        }
        req = requests.get(_url(const.URL_API), headers=headers)

        allow_origin = const.HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN

        assert req.status_code == 200
        assert req.headers.get(allow_origin) == HTTP_BASE_URL

    def test_cors_denied_without_origin_header(self):
        """Test cross origin resource sharing with password in header."""
        headers = {
            const.HTTP_HEADER_HA_AUTH: API_PASSWORD
        }
        req = requests.get(_url(const.URL_API), headers=headers)

        allow_origin = const.HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN
        allow_headers = const.HTTP_HEADER_ACCESS_CONTROL_ALLOW_HEADERS

        assert req.status_code == 200
        assert allow_origin not in req.headers
        assert allow_headers not in req.headers

    def test_cors_preflight_allowed(self):
        """Test cross origin resource sharing preflight (OPTIONS) request."""
        headers = {
            const.HTTP_HEADER_ORIGIN: HTTP_BASE_URL,
            'Access-Control-Request-Method': 'GET',
            'Access-Control-Request-Headers': 'x-ha-access'
        }
        req = requests.options(_url(const.URL_API), headers=headers)

        allow_origin = const.HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN
        allow_headers = const.HTTP_HEADER_ACCESS_CONTROL_ALLOW_HEADERS

        assert req.status_code == 200
        assert req.headers.get(allow_origin) == HTTP_BASE_URL
        assert req.headers.get(allow_headers) == \
            const.HTTP_HEADER_HA_AUTH.upper()


text:
<?php
namespace Elastica\Test\Filter;

use Elastica\Document;
use Elastica\Filter\Ids;
use Elastica\Filter\Type;
use Elastica\Query;
use Elastica\Test\Base as BaseTest;

class IdsTest extends BaseTest
{
    protected function _getIndexForTest()
    {
        $index = $this->_createIndex();

        // Add documents to first type
        $docs = array();
        for ($i = 1; $i < 100; $i++) {
            $docs[] = new Document($i, array('name' => 'ruflin'));
        }
        $index->getType('helloworld1')->addDocuments($docs);

        // Add documents to second type
        $docs = array();
        for ($i = 1; $i < 100; $i++) {
            $docs[] = new Document($i, array('name' => 'ruflin'));
        }
        // This is a special id that will only be in the second type
        $docs[] = new Document(101, array('name' => 'ruflin'));
        $index->getType('helloworld2')->addDocuments($docs);

        $index->optimize();
        $index->refresh();

        return $index;
    }

    protected function _getTypeForTest()
    {
        return $this->_getIndexForTest()->getType('helloworld1');
    }

    /**
     * @group functional
     */
    public function testSetIdsSearchSingle()
    {
        $filter = new Ids();
        $filter->setIds('1');

        $query = Query::create($filter);
        $resultSet = $this->_getTypeForTest()->search($query);

        $this->assertEquals(1, $resultSet->count());
    }

    /**
     * @group functional
     */
    public function testSetIdsSearchArray()
    {
        $filter = new Ids();
        $filter->setIds(array(1, 7, 13));

        $query = Query::create($filter);
        $resultSet = $this->_getTypeForTest()->search($query);

        $this->assertEquals(3, $resultSet->count());
    }

    /**
     * @group functional
     */
    public function testAddIdsSearchSingle()
    {
        $filter = new Ids();
        $filter->addId('39');

        $query = Query::create($filter);
        $resultSet = $this->_getTypeForTest()->search($query);

        $this->assertEquals(1, $resultSet->count());
    }

    /**
     * @group functional
     */
    public function testAddIdsSearchSingleNotInType()
    {
        $filter = new Ids();
        $filter->addId('39');

        // Add an ID that is not in the index
        $filter->addId(104);

        $query = Query::create($filter);
        $resultSet = $this->_getTypeForTest()->search($query);

        $this->assertEquals(1, $resultSet->count());
    }

    /**
     * @group functional
     */
    public function testComboIdsSearchArray()
    {
        $filter = new Ids();
        $filter->setIds(array(1, 7, 13));
        $filter->addId('39');

        $query = Query::create($filter);
        $resultSet = $this->_getTypeForTest()->search($query);

        $this->assertEquals(4, $resultSet->count());
    }

    /**
     * @group functional
     */
    public function testSetTypeSingleSearchSingle()
    {
        $filter = new Ids();
        $filter->setIds('1');
        $filter->setType('helloworld1');

        $query = Query::create($filter);
        $resultSet = $this->_getIndexForTest()->search($query);

        $this->assertEquals(1, $resultSet->count());
    }

    /**
     * @group functional
     */
    public function testSetTypeSingleSearchArray()
    {
        $filter = new Ids();
        $filter->setIds(array('1', '2'));
        $filter->setType('helloworld1');

        $query = Query::create($filter);
        $resultSet = $this->_getIndexForTest()->search($query);

        $this->assertEquals(2, $resultSet->count());
    }

    /**
     * @group functional
     */
    public function testSetTypeSingleSearchSingleDocInOtherType()
    {
        $filter = new Ids();

        // Doc 4 is in the second type...
        $filter->setIds('101');
        $filter->setType('helloworld1');

        $query = Query::create($filter);
        $resultSet = $this->_getTypeForTest()->search($query);

        // ...therefore 0 results should be returned
        $this->assertEquals(0, $resultSet->count());
    }

    /**
     * @group functional
     */
    public function testSetTypeSingleSearchArrayDocInOtherType()
    {
        $filter = new Ids();

        // Doc 4 is in the second type...
        $filter->setIds(array('1', '101'));
        $filter->setType('helloworld1');

        $query = Query::create($filter);
        $resultSet = $this->_getTypeForTest()->search($query);

        // ...therefore only 1 result should be returned
        $this->assertEquals(1, $resultSet->count());
    }

    /**
     * @group functional
     */
    public function testSetTypeArraySearchArray()
    {
        $filter = new Ids();
        $filter->setIds(array('1', '4'));
        $filter->setType(array('helloworld1', 'helloworld2'));

        $query = Query::create($filter);
        $resultSet = $this->_getIndexForTest()->search($query);

        $this->assertEquals(4, $resultSet->count());
    }

    /**
     * @group functional
     */
    public function testSetTypeArraySearchSingle()
    {
        $filter = new Ids();
        $filter->setIds('4');
        $filter->setType(array('helloworld1', 'helloworld2'));

        $query = Query::create($filter);
        $resultSet = $this->_getIndexForTest()->search($query);

        $this->assertEquals(2, $resultSet->count());
    }

    /**
     * @group unit
     */
    public function testFilterTypeAndTypeCollision()
    {
        // This test ensures that Elastica\Type and Elastica\Filter\Type
        // do not collide when used together, which at one point
        // happened because of a use statement in Elastica\Filter\Ids
        // Test goal is to make sure a Fatal Error is not triggered
        $filterType = new Type();
        $filter = new Ids();
    }

    /**
     * @group unit
     */
    public function testAddType()
    {
        $type = $this->_getClient()->getIndex('indexname')->getType('typename');

        $filter = new Ids();

        $filter->addType('foo');
        $this->assertEquals(array('foo'), $filter->getParam('type'));

        $filter->addType($type);
        $this->assertEquals(array('foo', $type->getName()), $filter->getParam('type'));

        $returnValue = $filter->addType('bar');
        $this->assertInstanceOf('Elastica\Filter\Ids', $returnValue);
    }
}


text: get_number_from_string = lambda string: int(''.join(filter(lambda s: s.isdigit(), string)))