text:
* fix some weird behavior with ruby 1.8.x (not noticable)
* refactor tests

## v1.2.2

* fix preview for carrierwave when using versions (will now preview versions correctly)

## v1.2.1

* fix regression for ruby 1.8.x

## v1.2

* better (lazy) loading of carrierwave

## v1.1.6

* better handling of save options like :perform_validation for associations and create moderations
* better handling of carrierwave fields, especially when previewing

## v1.1.5

* fix bug where #preview would remove carrierwave temporary files
* fix #preview for carrierwave uploads, now gives a frozen uploader pointing to the temporary file

## v1.1.4

* fix issue #13 (create moderation preview bug, regression from v1.1.1 upwards)
* fix bug that happened when you create a new column with a moderated attribute assigned
* not using attr_accessible anywhere anymore in preparation for Rails 4

## v1.1.3

* more consistent behavior of without_moderation

## v1.1.2

* added Moderation class method without_moderation to disable moderations globally for all models

## v1.1.1

* accept and accept! now accept hash parameters that will be passed on to model#save

## v1.1

* accept now returns false if validations don't pass, otherwise returns true
* accept! added (raises exception if validations don't pass)

## v1.0.1

* Fix issue #12

## v1.0.rc11

* Moderation#destroy now calls Moderation#discard automatically.

## v1.0.rc10

* Use get\_moderation\_attributes when using has\_moderated to moderate attributes on update (previously only used in create moderations).

## v1.0.rc9

* Updated preview and live\_preview
* Updated README

## v1.0.rc6

* Make tests pass on 1.8.x and rubinius.

## v1.0.rc5

* Support moderation.preview for associations

## v1.0.rc4

* Refactoring
* Bug fixes
* moderation.preview feature
* changed moderations database table schema

## v0.0.34

* Now moderates deleting associations when using has\_moderated\_association


text:
const mqtt = require('mqtt');

var mqtt_builder = function(config, app) {
    var client = mqtt.connect(config.host, config.options);

    app.on('exit', function (code) {
        client.end();
    });

    client.on('connect', function(connack) {
        app.logger.info("MQTT - connect", connack);
    });

    client.on('reconnect', function() {
        app.logger.debug("MQTT - reconnect");
    });

    client.on('close', function() {
        app.logger.info("MQTT - close");
    });

    client.on('offline', function() {
        app.logger.info("MQTT - offline");
    });

    client.on('error', function(error) {
        app.logger.error("MQTT - error: " + error);
        app.exit(1, error);
    });

    client.on('message', function(topic, message, packet) {
        app.logger.debug("MQTT - message: ", {topic: topic, message: message, packet: packet});
    });

    return client;
};

module.exports = mqtt_builder;

redpajama_set_name: RedPajamaGithub


text:
require 'tr4n5l4te/version'

require 'midwire_common/yaml_setting'
require 'midwire_common/hash'

module Tr4n5l4te
  class << self
    attr_accessor :configuration

    def root
      Pathname.new(File.dirname(__FILE__)).parent
    end

    def string_id
      'tr4n5l4te'
    end

    def default_config_directory
      ".#{string_id}"
    end

    def default_cookie_filename
      'cookies.yml'
    end

    def home_directory
      ENV.fetch('HOME')
    end

    # If you don't have a HOME directory defined, you are on an OS that is
    # retarded, and this call will fail.
    def cookie_file
      dir = File.join(home_directory, default_config_directory)
      module_string = string_id.upcase
      file = ENV.fetch(
        "#{module_string}_COOKIES",
        File.join(dir, default_cookie_filename)
      )
      FileUtils.mkdir_p(dir)
      FileUtils.touch(file)
      file
    end

    def configure
      self.configuration ||= Configuration.new
      yield(configuration)
    end
  end

  autoload :Agent,          'tr4n5l4te/agent'
  autoload :Configuration,  'tr4n5l4te/configuration'
  autoload :Language,       'tr4n5l4te/language'
  autoload :Runner,         'tr4n5l4te/runner'
  autoload :Translator,     'tr4n5l4te/translator'
end

Tr4n5l4te.configure {}


text:
package org.apache.camel.component.vertx.kafka;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import io.vertx.kafka.client.producer.RecordMetadata;
import org.apache.camel.Endpoint;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.header.Headers;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class VertxKafkaProducerFullTest extends BaseEmbeddedKafkaTest {

    private static final String TOPIC_STRINGS = "test";
    private static final String TOPIC_INTERCEPTED = "test";
    private static final String TOPIC_STRINGS_IN_HEADER = "testHeader";
    private static final String TOPIC_BYTES = "testBytes";
    private static final String TOPIC_BYTES_IN_HEADER = "testBytesHeader";
    private static final String GROUP_BYTES = "groupStrings";
    private static final String TOPIC_PROPAGATED_HEADERS = "testPropagatedHeaders";
    private static final String TOPIC_NO_RECORD_SPECIFIC_HEADERS = "noRecordSpecificHeaders";

    private static KafkaConsumer<String, String> stringsConsumerConn;
    private static KafkaConsumer<byte[], byte[]> bytesConsumerConn;

    @EndpointInject("vertx-kafka:" + TOPIC_STRINGS + "?acks=-1")
    private Endpoint toStrings;

    @EndpointInject("vertx-kafka:" + TOPIC_STRINGS + "?acks=-1&partitionId=0")
    private Endpoint toStrings2;

    @EndpointInject("mock:kafkaAck")
    private MockEndpoint mockEndpoint;

    @EndpointInject("vertx-kafka:" + TOPIC_BYTES + "?acks=-1"
                    + "&valueSerializer=org.apache.kafka.common.serialization.ByteArraySerializer&"
                    + "keySerializer=org.apache.kafka.common.serialization.ByteArraySerializer")
    private Endpoint toBytes;

    @EndpointInject("vertx-kafka:" + TOPIC_PROPAGATED_HEADERS + "?acks=-1")
    private Endpoint toPropagatedHeaders;

    @EndpointInject("vertx-kafka:" + TOPIC_NO_RECORD_SPECIFIC_HEADERS + "?acks=-1")
    private Endpoint toNoRecordSpecificHeaders;

    @Produce("direct:startStrings")
    private ProducerTemplate stringsTemplate;

    @Produce("direct:startStrings2")
    private ProducerTemplate stringsTemplate2;

    @Produce("direct:startBytes")
    private ProducerTemplate bytesTemplate;

    @Produce("direct:startTraced")
    private ProducerTemplate interceptedTemplate;

    @Produce("direct:propagatedHeaders")
    private ProducerTemplate propagatedHeadersTemplate;

    @Produce("direct:noRecordSpecificHeaders")
    private ProducerTemplate noRecordSpecificHeadersTemplate;

    @BeforeAll
    public static void before() {
        stringsConsumerConn = createStringKafkaConsumer("DemoConsumer");
        bytesConsumerConn = createByteKafkaConsumer(GROUP_BYTES);
    }

    @AfterAll
    public static void after() {
        // clean all test topics
        final List<String> topics = new ArrayList<>();
        topics.add(TOPIC_BYTES);
        topics.add(TOPIC_INTERCEPTED);
        topics.add(TOPIC_PROPAGATED_HEADERS);
        topics.add(TOPIC_STRINGS);
        topics.add(TOPIC_NO_RECORD_SPECIFIC_HEADERS);

        kafkaAdminClient.deleteTopics(topics);
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:startStrings").to(toStrings).to(mockEndpoint);

                from("direct:startStrings2").to(toStrings2).to(mockEndpoint);

                from("direct:startBytes").to(toBytes).to(mockEndpoint);

                from("direct:propagatedHeaders").to(toPropagatedHeaders).to(mockEndpoint);

                from("direct:noRecordSpecificHeaders").to(toNoRecordSpecificHeaders).to(mockEndpoint);
            }
        };
    }

    @Test
    public void producedStringMessageIsReceivedByKafka() throws InterruptedException, IOException {
        int messageInTopic = 10;
        int messageInOtherTopic = 5;

        CountDownLatch messagesLatch = new CountDownLatch(messageInTopic + messageInOtherTopic);

        sendMessagesInRoute(messageInTopic, stringsTemplate, "IT test message", VertxKafkaConstants.PARTITION_ID, "0");
        sendMessagesInRoute(messageInOtherTopic, stringsTemplate, "IT test message in other topic",
                VertxKafkaConstants.PARTITION_ID, "0", VertxKafkaConstants.TOPIC,
                TOPIC_STRINGS_IN_HEADER);

        createKafkaMessageConsumer(stringsConsumerConn, TOPIC_STRINGS, TOPIC_STRINGS_IN_HEADER, messagesLatch);

        boolean allMessagesReceived = messagesLatch.await(200, TimeUnit.MILLISECONDS);

        assertTrue(allMessagesReceived,
                "Not all messages were published to the kafka topics. Not received: " + messagesLatch.getCount());

        List<Exchange> exchangeList = mockEndpoint.getExchanges();
        assertEquals(15, exchangeList.size(), "Fifteen Exchanges are expected");
        for (Exchange exchange : exchangeList) {
            List<RecordMetadata> recordMetaData1
                    = getRecordMetadata(exchange);
            assertEquals(1, recordMetaData1.size(), "One RecordMetadata is expected.");
            assertTrue(recordMetaData1.get(0).getOffset() >= 0, "Offset is positive");
            assertTrue(recordMetaData1.get(0).getTopic().startsWith("test"), "Topic Name start with 'test'");
        }
    }

    @Test
    public void producedString2MessageIsReceivedByKafka() throws InterruptedException, IOException {
        int messageInTopic = 10;
        int messageInOtherTopic = 5;

        CountDownLatch messagesLatch = new CountDownLatch(messageInTopic + messageInOtherTopic);

        sendMessagesInRoute(messageInTopic, stringsTemplate2, "IT test message", (String[]) null);
        sendMessagesInRoute(messageInOtherTopic, stringsTemplate2, "IT test message in other topic",
                VertxKafkaConstants.PARTITION_ID, "0", VertxKafkaConstants.TOPIC,
                TOPIC_STRINGS_IN_HEADER);

        createKafkaMessageConsumer(stringsConsumerConn, TOPIC_STRINGS, TOPIC_STRINGS_IN_HEADER, messagesLatch);

        boolean allMessagesReceived = messagesLatch.await(200, TimeUnit.MILLISECONDS);

        assertTrue(allMessagesReceived,
                "Not all messages were published to the kafka topics. Not received: " + messagesLatch.getCount());

        List<Exchange> exchangeList = mockEndpoint.getExchanges();
        assertEquals(15, exchangeList.size(), "Fifteen Exchanges are expected");
        for (Exchange exchange : exchangeList) {
            List<RecordMetadata> recordMetaData1
                    = getRecordMetadata(exchange);
            assertEquals(1, recordMetaData1.size(), "One RecordMetadata is expected.");
            assertTrue(recordMetaData1.get(0).getOffset() >= 0, "Offset is positive");
            assertTrue(recordMetaData1.get(0).getTopic().startsWith("test"), "Topic Name start with 'test'");
        }
    }

    @Test
    public void producedStringCollectionMessageIsReceivedByKafka() throws InterruptedException, IOException {
        int messageInTopic = 10;
        int messageInOtherTopic = 5;

        CountDownLatch messagesLatch = new CountDownLatch(messageInTopic + messageInOtherTopic);

        List<String> msgs = new ArrayList<>();
        for (int x = 0; x < messageInTopic; x++) {
            msgs.add("Message " + x);
        }

        sendMessagesInRoute(1, stringsTemplate, msgs, VertxKafkaConstants.PARTITION_ID, "0");
        msgs = new ArrayList<>();
        for (int x = 0; x < messageInOtherTopic; x++) {
            msgs.add("Other Message " + x);
        }
        sendMessagesInRoute(1, stringsTemplate, msgs, VertxKafkaConstants.PARTITION_ID, "0", VertxKafkaConstants.TOPIC,
                TOPIC_STRINGS_IN_HEADER);

        createKafkaMessageConsumer(stringsConsumerConn, TOPIC_STRINGS, TOPIC_STRINGS_IN_HEADER, messagesLatch);

        boolean allMessagesReceived = messagesLatch.await(200, TimeUnit.MILLISECONDS);

        assertTrue(allMessagesReceived,
                "Not all messages were published to the kafka topics. Not received: " + messagesLatch.getCount());
        List<Exchange> exchangeList = mockEndpoint.getExchanges();
        assertEquals(2, exchangeList.size(), "Two Exchanges are expected");
        Exchange e1 = exchangeList.get(0);
        List<RecordMetadata> recordMetaData1 = getRecordMetadata(e1);
        assertEquals(10, recordMetaData1.size(), "Ten RecordMetadata is expected.");
        for (RecordMetadata recordMeta : recordMetaData1) {
            assertTrue(recordMeta.getOffset() >= 0, "Offset is positive");
            assertTrue(recordMeta.getTopic().startsWith("test"), "Topic Name start with 'test'");
        }
        Exchange e2 = exchangeList.get(1);
        List<RecordMetadata> recordMetaData2 = getRecordMetadata(e2);
        assertEquals(5, recordMetaData2.size(), "Five RecordMetadata is expected.");
        for (RecordMetadata recordMeta : recordMetaData2) {
            assertTrue(recordMeta.getOffset() >= 0, "Offset is positive");
            assertTrue(recordMeta.getTopic().startsWith("test"), "Topic Name start with 'test'");
        }
    }

    @Test
    public void producedBytesMessageIsReceivedByKafka() throws InterruptedException, IOException {
        int messageInTopic = 10;
        int messageInOtherTopic = 5;

        CountDownLatch messagesLatch = new CountDownLatch(messageInTopic + messageInOtherTopic);

        Map<String, Object> inTopicHeaders = new HashMap<>();
        inTopicHeaders.put(VertxKafkaConstants.PARTITION_ID, "0".getBytes());
        sendMessagesInRoute(messageInTopic, bytesTemplate, "IT test message".getBytes(), inTopicHeaders);

        Map<String, Object> otherTopicHeaders = new HashMap<>();
        otherTopicHeaders.put(VertxKafkaConstants.PARTITION_ID, "0".getBytes());
        otherTopicHeaders.put(VertxKafkaConstants.TOPIC, TOPIC_BYTES_IN_HEADER);
        sendMessagesInRoute(messageInOtherTopic, bytesTemplate, "IT test message in other topic".getBytes(), otherTopicHeaders);

        createKafkaBytesMessageConsumer(bytesConsumerConn, TOPIC_BYTES, TOPIC_BYTES_IN_HEADER, messagesLatch);

        boolean allMessagesReceived = messagesLatch.await(200, TimeUnit.MILLISECONDS);

        assertTrue(allMessagesReceived,
                "Not all messages were published to the kafka topics. Not received: " + messagesLatch.getCount());

        List<Exchange> exchangeList = mockEndpoint.getExchanges();
        assertEquals(15, exchangeList.size(), "Fifteen Exchanges are expected");
        for (Exchange exchange : exchangeList) {
            List<RecordMetadata> recordMetaData1
                    = getRecordMetadata(exchange);
            assertEquals(1, recordMetaData1.size(), "One RecordMetadata is expected.");
            assertTrue(recordMetaData1.get(0).getOffset() >= 0, "Offset is positive");
            assertTrue(recordMetaData1.get(0).getTopic().startsWith("test"), "Topic Name start with 'test'");
        }
    }

    @Test
    public void propagatedHeaderIsReceivedByKafka() throws Exception {
        String propagatedStringHeaderKey = "PROPAGATED_STRING_HEADER";
        String propagatedStringHeaderValue = "propagated string header value";

        String propagatedIntegerHeaderKey = "PROPAGATED_INTEGER_HEADER";
        Integer propagatedIntegerHeaderValue = 54545;

        String propagatedLongHeaderKey = "PROPAGATED_LONG_HEADER";
        Long propagatedLongHeaderValue = 5454545454545L;

        String propagatedDoubleHeaderKey = "PROPAGATED_DOUBLE_HEADER";
        Double propagatedDoubleHeaderValue = 43434.545D;

        String propagatedBytesHeaderKey = "PROPAGATED_BYTES_HEADER";
        byte[] propagatedBytesHeaderValue = new byte[] { 121, 34, 34, 54, 5, 3, 54, -34 };

        String propagatedBooleanHeaderKey = "PROPAGATED_BOOLEAN_HEADER";
        Boolean propagatedBooleanHeaderValue = Boolean.TRUE;

        Map<String, Object> camelHeaders = new HashMap<>();
        camelHeaders.put(propagatedStringHeaderKey, propagatedStringHeaderValue);
        camelHeaders.put(propagatedIntegerHeaderKey, propagatedIntegerHeaderValue);
        camelHeaders.put(propagatedLongHeaderKey, propagatedLongHeaderValue);
        camelHeaders.put(propagatedDoubleHeaderKey, propagatedDoubleHeaderValue);
        camelHeaders.put(propagatedBytesHeaderKey, propagatedBytesHeaderValue);
        camelHeaders.put(propagatedBooleanHeaderKey, propagatedBooleanHeaderValue);

        camelHeaders.put("CustomObjectHeader", new Object());
        camelHeaders.put("CustomNullObjectHeader", null);
        camelHeaders.put("CamelFilteredHeader", "CamelFilteredHeader value");

        CountDownLatch messagesLatch = new CountDownLatch(1);
        propagatedHeadersTemplate.sendBodyAndHeaders("Some test message", camelHeaders);

        List<ConsumerRecord<String, String>> records = pollForRecords(createStringKafkaConsumer("propagatedHeaderConsumer"),
                TOPIC_PROPAGATED_HEADERS, messagesLatch);
        boolean allMessagesReceived = messagesLatch.await(10_000, TimeUnit.MILLISECONDS);

        assertTrue(allMessagesReceived,
                "Not all messages were published to the kafka topics. Not received: " + messagesLatch.getCount());

        ConsumerRecord<String, String> record = records.get(0);
        Headers headers = record.headers();
        assertNotNull(headers, "Kafka Headers should not be null.");
        // we have 6 headers
        assertEquals(6, headers.toArray().length, "6 propagated header is expected.");
        assertEquals(propagatedStringHeaderValue, new String(getHeaderValue(propagatedStringHeaderKey, headers)),
                "Propagated string value received");
        assertEquals(propagatedIntegerHeaderValue,
                Integer.valueOf(ByteBuffer.wrap(getHeaderValue(propagatedIntegerHeaderKey, headers)).getInt()),
                "Propagated integer value received");
        assertEquals(propagatedLongHeaderValue,
                Long.valueOf(ByteBuffer.wrap(getHeaderValue(propagatedLongHeaderKey, headers)).getLong()),
                "Propagated long value received");
        assertEquals(propagatedDoubleHeaderValue,
                Double.valueOf(ByteBuffer.wrap(getHeaderValue(propagatedDoubleHeaderKey, headers)).getDouble()),
                "Propagated double value received");
        assertArrayEquals(propagatedBytesHeaderValue, getHeaderValue(propagatedBytesHeaderKey, headers),
                "Propagated byte array value received");
        assertEquals(propagatedBooleanHeaderValue,
                Boolean.valueOf(new String(getHeaderValue(propagatedBooleanHeaderKey, headers))),
                "Propagated boolean value received");
    }

    @Test
    public void recordSpecificHeaderIsNotReceivedByKafka() throws Exception {
        String propagatedStringHeaderKey = VertxKafkaConstants.TIMESTAMP;
        String propagatedStringHeaderValue = "dummy timestamp";

        Map<String, Object> camelHeaders = new HashMap<>();
        camelHeaders.put(propagatedStringHeaderKey, propagatedStringHeaderValue);

        CountDownLatch messagesLatch = new CountDownLatch(1);
        noRecordSpecificHeadersTemplate.sendBodyAndHeaders("Some test message", camelHeaders);

        List<ConsumerRecord<String, String>> records = pollForRecords(
                createStringKafkaConsumer("noRecordSpecificHeadersConsumer"), TOPIC_NO_RECORD_SPECIFIC_HEADERS, messagesLatch);
        boolean allMessagesReceived = messagesLatch.await(10_000, TimeUnit.MILLISECONDS);

        assertTrue(allMessagesReceived,
                "Not all messages were published to the kafka topics. Not received: " + messagesLatch.getCount());

        ConsumerRecord<String, String> record = records.get(0);
        Headers headers = record.headers();
        assertNotNull(headers, "Kafka Headers should not be null.");
        // we have 0 headers
        assertEquals(0, headers.toArray().length, "0 propagated headers are expected");
    }

    private byte[] getHeaderValue(String headerKey, Headers headers) {
        return VertxKafkaTestUtils.getHeaderValue(headerKey, headers);
    }

    @SuppressWarnings("unchecked")
    private List<RecordMetadata> getRecordMetadata(final Exchange exchange) {
        return (List<RecordMetadata>) (exchange.getIn().getHeader(VertxKafkaConstants.RECORD_METADATA));
    }

    private static KafkaConsumer<String, String> createStringKafkaConsumer(final String groupId) {
        Properties stringsProps = new Properties();

        stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
                service.getBootstrapServers());
        stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.GROUP_ID_CONFIG, groupId);
        stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
        stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
        stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "30000");
        stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringDeserializer");
        stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringDeserializer");
        stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

        return new KafkaConsumer<>(stringsProps);
    }

    private static KafkaConsumer<byte[], byte[]> createByteKafkaConsumer(final String groupId) {
        Properties stringsProps = new Properties();

        stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
                service.getBootstrapServers());
        stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.GROUP_ID_CONFIG, groupId);
        stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
        stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
        stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "30000");
        stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.ByteArrayDeserializer");
        stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.ByteArrayDeserializer");
        stringsProps.put(org.apache.kafka.clients.consumer.ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

        return new KafkaConsumer<>(stringsProps);
    }

    private List<ConsumerRecord<String, String>> pollForRecords(
            KafkaConsumer<String, String> consumerConn, String topic, CountDownLatch messagesLatch) {

        List<ConsumerRecord<String, String>> consumedRecords = new ArrayList<>();
        consumerConn.subscribe(Collections.singletonList(topic));

        new Thread(() -> {
            while (messagesLatch.getCount() != 0) {
                for (ConsumerRecord<String, String> record : consumerConn.poll(Duration.ofMillis(100))) {
                    consumedRecords.add(record);
                    messagesLatch.countDown();
                }
            }
        }).start();

        return consumedRecords;
    }

    private void createKafkaMessageConsumer(
            KafkaConsumer<String, String> consumerConn, String topic, String topicInHeader, CountDownLatch messagesLatch) {

        consumerConn.subscribe(Arrays.asList(topic, topicInHeader));
        boolean run = true;

        while (run) {
            ConsumerRecords<String, String> records = consumerConn.poll(Duration.ofMillis(100));
            for (int i = 0; i < records.count(); i++) {
                messagesLatch.countDown();
                if (messagesLatch.getCount() == 0) {
                    run = false;
                }
            }
        }

    }

    private void createKafkaBytesMessageConsumer(
            KafkaConsumer<byte[], byte[]> consumerConn, String topic, String topicInHeader, CountDownLatch messagesLatch) {

        consumerConn.subscribe(Arrays.asList(topic, topicInHeader));
        boolean run = true;

        while (run) {
            ConsumerRecords<byte[], byte[]> records = consumerConn.poll(Duration.ofMillis(100));
            for (int i = 0; i < records.count(); i++) {
                messagesLatch.countDown();
                if (messagesLatch.getCount() == 0) {
                    run = false;
                }
            }
        }

    }

    private void sendMessagesInRoute(int messages, ProducerTemplate template, Object bodyOther, String... headersWithValue) {
        Map<String, Object> headerMap = new HashMap<>();
        if (headersWithValue != null) {
            for (int i = 0; i < headersWithValue.length; i = i + 2) {
                headerMap.put(headersWithValue[i], headersWithValue[i + 1]);
            }
        }
        sendMessagesInRoute(messages, template, bodyOther, headerMap);
    }

    private void sendMessagesInRoute(int messages, ProducerTemplate template, Object bodyOther, Map<String, Object> headerMap) {
        for (int k = 0; k < messages; k++) {
            template.sendBodyAndHeaders(bodyOther, headerMap);
        }
    }
}


text:
#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
#endregion

//This namespace holds indicators in this folder and is required. Do not change it.
namespace HaiFeng
{
	/// <summary>
	/// The Forecast Oscillator (FOSC) is an extension of the linear regression based indicators
	/// made popular by Tushar Chande. The Forecast Oscillator plots the percentage difference
	/// between the forecast price (generated by an x-period linear regression line) and the actual
	/// price. The oscillator is above zero when the forecast price is greater than the actual price.
	/// Conversely, it's less than zero if its below. In the rare case when the forecast price and the
	///  actual price are the same, the oscillator would plot zero. Actual prices that are persistently
	///  below the forecast price suggest lower prices ahead.  Likewise, actual prices that are persistently
	///  above the forecast price suggest higher prices ahead. Short-term traders should use shorter time
	///  periods and perhaps more relaxed standards for the required length of time above or below the
	///  forecast price. Long-term traders should use longer time periods and perhaps stricter standards
	///  for the required length of time above or below the forecast price. Chande also suggests plotting
	///  a three-day moving average trigger line of the Forecast Oscillator to generate early warnings of
	/// changes in trend. When the oscillator crosses below the trigger line, lower prices are suggested.
	/// When the oscillator crosses above the trigger line, higher prices are suggested.
	/// </summary>
	public class FOSC : Indicator
	{
		private TSF tsf;

		protected override void Init()
		{
			tsf = TSF(Input, 0, Period);
		}

		protected override void OnBarUpdate()
		{
			double input0 = Input[0];
			Value[0] = 100 * ((input0 - tsf[0]) / input0);
		}

		#region Properties
		[Range(1, int.MaxValue)]
		[Parameter("Period")]
		public int Period { get; set; }
		#endregion
	}

	#region generated code. Neither change nor remove.

	public partial class Indicator
	{
		private FOSC[] cacheFOSC;

		public FOSC FOSC(DataSeries input, int period)
		{
			if (cacheFOSC != null)
				for (int idx = 0; idx < cacheFOSC.Length; idx++)
					if (cacheFOSC[idx] != null && cacheFOSC[idx].Period == period && cacheFOSC[idx].EqualsInput(input))
						return cacheFOSC[idx];
			return CacheIndicator<FOSC>(new FOSC() { Period = period, Input = input }, ref cacheFOSC);
		}
	}

	public partial class Strategy
	{
		public FOSC FOSC(DataSeries input, int period)
		{
			return Indicator.FOSC(input, period);
		}
	}
}

#endregion


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ann. R. bot. Gdns Peradeniya 5(4): 250 (1912)

#### Original name
Uredo microglossae Petch

### Remarks
null


text:
PROJECT_ID=YOUR_PROJECT_ID
PROJECT_NUMBER=YOUR_PROJECT_NUMBER

# The name of the session, can be an arbitrary string.
# This also serves as the prefix for instance names. For example, the root instance will be named $SESSION-root.
SESSION="fuzzilli"

# The path to the JavaScript engine binary in the container
BINARY=./v8/d8
# Common arguments to pass to every Fuzzilli instance. See ./Fuzzilli --help
FUZZILLI_ARGS="--profile=v8"
# Arguments for the root instance. See ./Fuzzilli --help
FUZZILLI_ROOT_ARGS="--exportStatistics"
FUZZILLI_WORKER_ARGS=""

# Region and zone where compute instances are created. See https://cloud.google.com/compute/docs/regions-zones
REGION=us-east1
ZONE=$REGION-b

# By default, the default service account: https://cloud.google.com/iam/docs/service-accounts#default
SERVICE_ACCOUNT=$PROJECT_NUMBER-compute@developer.gserviceaccount.com

# The docker container and OS image to use.
CONTAINER_NAME=fuzzilli
CONTAINER_IMAGE=gcr.io/$PROJECT_ID/$CONTAINER_NAME:latest
# By default, use the latest stable OS image
OS_IMAGE=$(gcloud compute --project=$PROJECT_ID images list --filter="family=cos-stable" --format="value(NAME)")

# Total number of Fuzzilli worker instances. Adjust this as desired.
NUM_WORKERS=128

# How many workers to run per machine, using --jobs=N.
# NUM_WORKERS / NUM_WORKERS_PER_MACHINE worker machines will be started.
# This number should roughly equal the number of cores on the worker machines.
NUM_WORKERS_PER_MACHINE=8

# How many worker machines a single master instance can handle at most.
# This will determine the depth of the instace hierarchy.
MAX_WORKERS_PER_MASTER=32

# 2 cores, 8 GB
ROOT_MACHINE_TYPE=e2-standard-2
# 2 cores, 4GB
MASTER_MACHINE_TYPE=e2-medium
# 8 cores, 8 GB
WORKER_MACHINE_TYPE=e2-highcpu-8

# Worker instance type, can be "permanent" or "preemtible". Preemptible instances are (much) cheaper but live at most 24
# hours and may be shut down at any time. Typically it only makes sense to use preemtible instances when the corpora
# between workers and masters are synchronized as 24h is otherwise not long enough for a decent fuzzing run.
WORKER_INSTANCE_TYPE=preemtible


text:
package org.dcache.nfs.v4.xdr;
import org.dcache.xdr.*;
import java.io.IOException;

public class notify_remove4 implements XdrAble {
    public notify_entry4 nrm_old_entry;
    public nfs_cookie4 nrm_old_entry_cookie;

    public notify_remove4() {
    }

    public notify_remove4(XdrDecodingStream xdr)
           throws OncRpcException, IOException {
        xdrDecode(xdr);
    }

    public void xdrEncode(XdrEncodingStream xdr)
           throws OncRpcException, IOException {
        nrm_old_entry.xdrEncode(xdr);
        nrm_old_entry_cookie.xdrEncode(xdr);
    }

    public void xdrDecode(XdrDecodingStream xdr)
           throws OncRpcException, IOException {
        nrm_old_entry = new notify_entry4(xdr);
        nrm_old_entry_cookie = new nfs_cookie4(xdr);
    }

}
// End of notify_remove4.java


text:
layout: default
hl: en
permalink: /en/sponsoring.html
---
{% include navigation_fixed.html %}

{% include sponsors.html %}


text:
<archimate:Grouping
    xmlns:archimate="http://www.archimatetool.com/archimate"
    name="Embracing advances in the JavaScript language"
    id="c6b95803-15f6-4e43-a250-76cc0789afe2"/>


text:
package org.blade.personal.engine;

import org.blade.personal.mode.ModelDefined;

/**
 * 代码引擎
 * @author Thinkpad
 *
 */
public interface CodeEngine {

	/**
	 * 生成
	 * @return
	 */
	public String generate(ModelDefined modeDefined);
}


text:
package com.streamsets.pipeline.stage.destination.mapreduce.jobtype.avroparquet;

public class AvroParquetConstants {

  /**
   * Full path to input avro file that needs to be converted.
   */
  public final static String INPUT_FILE = AvroParquetConstants.class.getCanonicalName() + ".input";

  /**
   * Directory into which the converted parquet file should be stored.
   */
  public final static String OUTPUT_DIR = AvroParquetConstants.class.getCanonicalName() + ".output";

  /**
   * Whether or not to keep input file after the conversion is done.
   */
  public final static String KEEP_INPUT_FILE = AvroParquetConstants.class.getCanonicalName() + ".keep_input_file";

  /**
   * Name of the compression codec that should be passed down to Parquet writer.
   */
  public final static String COMPRESSION_CODEC_NAME = AvroParquetConstants.class.getCanonicalName() + ".compression_codec";

  /**
   * Row group size that will be passed down to Parquet writer.
   */
  public final static String ROW_GROUP_SIZE = AvroParquetConstants.class.getCanonicalName() + ".row_group_size";

  /**
   * Page size that will be passed down to Parquet writer.
   */
  public final static String PAGE_SIZE = AvroParquetConstants.class.getCanonicalName() + ".page_size";

  /**
   * Dictionary page size that will be passed down to Parquet writer.
   */
  public final static String DICTIONARY_PAGE_SIZE = AvroParquetConstants.class.getCanonicalName() + ".dictionary_page_size";

  /**
   * Max padding size that will be passed down to Parquet writer.
   */
  public final static String MAX_PADDING_SIZE = AvroParquetConstants.class.getCanonicalName() + ".max_padding_size";
}


text:
package org.cardiacatlas.xpacs.web.rest;

import org.cardiacatlas.xpacs.XpacswebApp;

import org.cardiacatlas.xpacs.domain.PatientInfo;
import org.cardiacatlas.xpacs.repository.PatientInfoRepository;
import org.cardiacatlas.xpacs.web.rest.errors.ExceptionTranslator;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import org.cardiacatlas.xpacs.domain.enumeration.GenderType;
/**
 * Test class for the PatientInfoResource REST controller.
 *
 * @see PatientInfoResource
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = XpacswebApp.class)
public class PatientInfoResourceIntTest {

    private static final String DEFAULT_PATIENT_ID = "AAAAAAAAAA";
    private static final String UPDATED_PATIENT_ID = "BBBBBBBBBB";

    private static final String DEFAULT_COHORT = "AAAAAAAAAA";
    private static final String UPDATED_COHORT = "BBBBBBBBBB";

    private static final String DEFAULT_ETHNICITY = "AAAAAAAAAA";
    private static final String UPDATED_ETHNICITY = "BBBBBBBBBB";

    private static final GenderType DEFAULT_GENDER = GenderType.male;
    private static final GenderType UPDATED_GENDER = GenderType.female;

    private static final String DEFAULT_PRIMARY_DIAGNOSIS = "AAAAAAAAAA";
    private static final String UPDATED_PRIMARY_DIAGNOSIS = "BBBBBBBBBB";

    @Autowired
    private PatientInfoRepository patientInfoRepository;

    @Autowired
    private MappingJackson2HttpMessageConverter jacksonMessageConverter;

    @Autowired
    private PageableHandlerMethodArgumentResolver pageableArgumentResolver;

    @Autowired
    private ExceptionTranslator exceptionTranslator;

    @Autowired
    private EntityManager em;

    private MockMvc restPatientInfoMockMvc;

    private PatientInfo patientInfo;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        PatientInfoResource patientInfoResource = new PatientInfoResource(patientInfoRepository);
        this.restPatientInfoMockMvc = MockMvcBuilders.standaloneSetup(patientInfoResource)
            .setCustomArgumentResolvers(pageableArgumentResolver)
            .setControllerAdvice(exceptionTranslator)
            .setMessageConverters(jacksonMessageConverter).build();
    }

    /**
     * Create an entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static PatientInfo createEntity(EntityManager em) {
        PatientInfo patientInfo = new PatientInfo()
            .patientId(DEFAULT_PATIENT_ID)
            .cohort(DEFAULT_COHORT)
            .ethnicity(DEFAULT_ETHNICITY)
            .gender(DEFAULT_GENDER)
            .primaryDiagnosis(DEFAULT_PRIMARY_DIAGNOSIS);
        return patientInfo;
    }

    @Before
    public void initTest() {
        patientInfo = createEntity(em);
    }

    @Test
    @Transactional
    public void createPatientInfo() throws Exception {
        int databaseSizeBeforeCreate = patientInfoRepository.findAll().size();

        // Create the PatientInfo
        restPatientInfoMockMvc.perform(post("/api/patient-infos")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(patientInfo)))
            .andExpect(status().isCreated());

        // Validate the PatientInfo in the database
        List<PatientInfo> patientInfoList = patientInfoRepository.findAll();
        assertThat(patientInfoList).hasSize(databaseSizeBeforeCreate + 1);
        PatientInfo testPatientInfo = patientInfoList.get(patientInfoList.size() - 1);
        assertThat(testPatientInfo.getPatientId()).isEqualTo(DEFAULT_PATIENT_ID);
        assertThat(testPatientInfo.getCohort()).isEqualTo(DEFAULT_COHORT);
        assertThat(testPatientInfo.getEthnicity()).isEqualTo(DEFAULT_ETHNICITY);
        assertThat(testPatientInfo.getGender()).isEqualTo(DEFAULT_GENDER);
        assertThat(testPatientInfo.getPrimaryDiagnosis()).isEqualTo(DEFAULT_PRIMARY_DIAGNOSIS);

    }

    @Test
    @Transactional
    public void createPatientInfoWithExistingId() throws Exception {
        int databaseSizeBeforeCreate = patientInfoRepository.findAll().size();

        // Create the PatientInfo with an existing ID
        patientInfo.setId(1L);

        // An entity with an existing ID cannot be created, so this API call must fail
        restPatientInfoMockMvc.perform(post("/api/patient-infos")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(patientInfo)))
            .andExpect(status().isBadRequest());

        // Validate the Alice in the database
        List<PatientInfo> patientInfoList = patientInfoRepository.findAll();
        assertThat(patientInfoList).hasSize(databaseSizeBeforeCreate);
    }

    @Test
    @Transactional
    public void createPatientInfoWithExistingPatientId() throws Exception {
    	// InitalizeDatabase
    	patientInfoRepository.saveAndFlush(patientInfo);
    	List<PatientInfo> patientInfoListBeforeCreate = patientInfoRepository.findAll();

        PatientInfo newPatientInfo = new PatientInfo()
                .patientId(DEFAULT_PATIENT_ID)         // this should already be there
                .cohort(DEFAULT_COHORT)
                .ethnicity(DEFAULT_ETHNICITY)
                .gender(DEFAULT_GENDER)
                .primaryDiagnosis(DEFAULT_PRIMARY_DIAGNOSIS);

        // Create the User
        restPatientInfoMockMvc.perform(post("/api/patient-infos")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(newPatientInfo)))
        	.andExpect(status().isBadRequest());

        // Validate that the newPatientInfo is not inserted
        assertThat(patientInfoRepository.findAll()).isEqualTo(patientInfoListBeforeCreate);
    }

    @Test
    @Transactional
    public void checkPatientIdIsRequired() throws Exception {
        int databaseSizeBeforeTest = patientInfoRepository.findAll().size();
        // set the field null
        patientInfo.setPatientId(null);

        // Create the PatientInfo, which fails.

        restPatientInfoMockMvc.perform(post("/api/patient-infos")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(patientInfo)))
            .andExpect(status().isBadRequest());

        List<PatientInfo> patientInfoList = patientInfoRepository.findAll();
        assertThat(patientInfoList).hasSize(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    public void checkGenderIsRequired() throws Exception {
        int databaseSizeBeforeTest = patientInfoRepository.findAll().size();
        // set the field null
        patientInfo.setGender(null);

        // Create the PatientInfo, which fails.

        restPatientInfoMockMvc.perform(post("/api/patient-infos")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(patientInfo)))
            .andExpect(status().isBadRequest());

        List<PatientInfo> patientInfoList = patientInfoRepository.findAll();
        assertThat(patientInfoList).hasSize(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    public void getAllPatientInfos() throws Exception {
        // Initialize the database
        patientInfoRepository.saveAndFlush(patientInfo);

        // Get all the patientInfoList
        restPatientInfoMockMvc.perform(get("/api/patient-infos?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(patientInfo.getId().intValue())))
            .andExpect(jsonPath("$.[*].patientId").value(hasItem(DEFAULT_PATIENT_ID.toString())))
            .andExpect(jsonPath("$.[*].cohort").value(hasItem(DEFAULT_COHORT.toString())))
            .andExpect(jsonPath("$.[*].ethnicity").value(hasItem(DEFAULT_ETHNICITY.toString())))
            .andExpect(jsonPath("$.[*].gender").value(hasItem(DEFAULT_GENDER.toString())))
            .andExpect(jsonPath("$.[*].primaryDiagnosis").value(hasItem(DEFAULT_PRIMARY_DIAGNOSIS.toString())));
    }

    @Test
    @Transactional
    public void getPatientInfo() throws Exception {
        // Initialize the database
        patientInfoRepository.saveAndFlush(patientInfo);

        // Get the patientInfo
        restPatientInfoMockMvc.perform(get("/api/patient-infos/{id}", patientInfo.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.id").value(patientInfo.getId().intValue()))
            .andExpect(jsonPath("$.patientId").value(DEFAULT_PATIENT_ID.toString()))
            .andExpect(jsonPath("$.cohort").value(DEFAULT_COHORT.toString()))
            .andExpect(jsonPath("$.ethnicity").value(DEFAULT_ETHNICITY.toString()))
            .andExpect(jsonPath("$.gender").value(DEFAULT_GENDER.toString()))
            .andExpect(jsonPath("$.primaryDiagnosis").value(DEFAULT_PRIMARY_DIAGNOSIS.toString()));
    }

    @Test
    @Transactional
    public void getNonExistingPatientInfo() throws Exception {
        // Get the patientInfo
        restPatientInfoMockMvc.perform(get("/api/patient-infos/{id}", Long.MAX_VALUE))
            .andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    public void updatePatientInfo() throws Exception {
        // Initialize the database
        patientInfoRepository.saveAndFlush(patientInfo);
        int databaseSizeBeforeUpdate = patientInfoRepository.findAll().size();

        // Update the patientInfo
        PatientInfo updatedPatientInfo = patientInfoRepository.findOne(patientInfo.getId());
        updatedPatientInfo
            .patientId(UPDATED_PATIENT_ID)
            .cohort(UPDATED_COHORT)
            .ethnicity(UPDATED_ETHNICITY)
            .gender(UPDATED_GENDER)
            .primaryDiagnosis(UPDATED_PRIMARY_DIAGNOSIS);

        restPatientInfoMockMvc.perform(put("/api/patient-infos")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(updatedPatientInfo)))
            .andExpect(status().isOk());

        // Validate the PatientInfo in the database
        List<PatientInfo> patientInfoList = patientInfoRepository.findAll();
        assertThat(patientInfoList).hasSize(databaseSizeBeforeUpdate);
        PatientInfo testPatientInfo = patientInfoList.get(patientInfoList.size() - 1);
        assertThat(testPatientInfo.getPatientId()).isEqualTo(UPDATED_PATIENT_ID);
        assertThat(testPatientInfo.getCohort()).isEqualTo(UPDATED_COHORT);
        assertThat(testPatientInfo.getEthnicity()).isEqualTo(UPDATED_ETHNICITY);
        assertThat(testPatientInfo.getGender()).isEqualTo(UPDATED_GENDER);
        assertThat(testPatientInfo.getPrimaryDiagnosis()).isEqualTo(UPDATED_PRIMARY_DIAGNOSIS);
    }

    @Test
    @Transactional
    public void updateNonExistingPatientInfo() throws Exception {
        int databaseSizeBeforeUpdate = patientInfoRepository.findAll().size();

        // Create the PatientInfo

        // If the entity doesn't have an ID, it will be created instead of just being updated
        restPatientInfoMockMvc.perform(put("/api/patient-infos")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(patientInfo)))
            .andExpect(status().isCreated());

        // Validate the PatientInfo in the database
        List<PatientInfo> patientInfoList = patientInfoRepository.findAll();
        assertThat(patientInfoList).hasSize(databaseSizeBeforeUpdate + 1);
    }

    @Test
    @Transactional
    public void deletePatientInfo() throws Exception {
        // Initialize the database
        patientInfoRepository.saveAndFlush(patientInfo);
        int databaseSizeBeforeDelete = patientInfoRepository.findAll().size();

        // Get the patientInfo
        restPatientInfoMockMvc.perform(delete("/api/patient-infos/{id}", patientInfo.getId())
            .accept(TestUtil.APPLICATION_JSON_UTF8))
            .andExpect(status().isOk());

        // Validate the database is empty
        List<PatientInfo> patientInfoList = patientInfoRepository.findAll();
        assertThat(patientInfoList).hasSize(databaseSizeBeforeDelete - 1);
    }

    @Test
    @Transactional
    public void equalsVerifier() throws Exception {
        TestUtil.equalsVerifier(PatientInfo.class);
        PatientInfo patientInfo1 = new PatientInfo();
        patientInfo1.setId(1L);
        PatientInfo patientInfo2 = new PatientInfo();
        patientInfo2.setId(patientInfo1.getId());
        assertThat(patientInfo1).isEqualTo(patientInfo2);
        patientInfo2.setId(2L);
        assertThat(patientInfo1).isNotEqualTo(patientInfo2);
        patientInfo1.setId(null);
        assertThat(patientInfo1).isNotEqualTo(patientInfo2);
    }
}


text:
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.WindowsAzure.MobileServices.TestFramework;

namespace Microsoft.WindowsAzure.Mobile.Android.Test
{
    sealed class TestListener
        : ITestReporter, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public string Status
        {
            get { return this.status; }
            private set
            {
                if (this.status == value)
                    return;

                this.status = value;
                OnPropertyChanged();
            }
        }

        public int Progress
        {
            get { return this.progress; }
            private set
            {
                if (this.progress == value)
                    return;

                this.progress = value;
                OnPropertyChanged();
            }
        }

        public IEnumerable<GroupDescription> Groups
        {
            get { return this.groups; }
        }

        void ITestReporter.StartRun (TestHarness harness)
        {
            Progress = 0;
            this.groups.Clear();
        }

        void ITestReporter.Progress (TestHarness harness)
        {
            float value = harness.Progress;
            int count = harness.Count;
            if (count > 0)
                value = value / count;

            this.Progress = (int)(value * 10000);
        }

        void ITestReporter.EndRun (TestHarness harness)
        {
        }

        void ITestReporter.StartGroup (TestGroup group)
        {
            this.currentGroup = new GroupDescription (group);
            this.groups.Add (this.currentGroup);
        }

        void ITestReporter.EndGroup (TestGroup group)
        {
        }

        void ITestReporter.StartTest (TestMethod test)
        {
            this.logBuilder = new StringBuilder();
        }

        void ITestReporter.EndTest (TestMethod test)
        {
            var description = new TestDescription (test, this.logBuilder.ToString());
            this.currentGroup.Tests.Add (description);
        }

        void ITestReporter.Log (string message)
        {
            this.logBuilder.AppendLine (message);
        }

        void ITestReporter.Error (string errorDetails)
        {
            this.logBuilder.AppendLine (errorDetails);
        }

        void ITestReporter.Status (string newStatus)
        {
            Status = newStatus;
        }

        private GroupDescription currentGroup;
        private readonly ObservableCollection<GroupDescription> groups = new ObservableCollection<GroupDescription>();

        private StringBuilder logBuilder;
        private string status;
        private int progress;

        private void OnPropertyChanged ([CallerMemberName] string propertyName = null)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
                handler (this, new PropertyChangedEventArgs (propertyName));
        }
    }
}


text:
/* tfwxo * 1/18/2016 * 9:56 PM */
using System;
using System.IO;
namespace on.iff
{
	public class WZSTR
	{
		public uint Tag {
			get;
			set;
		}

		public ZSTR Value {
			get;
			set;
		}

		// public void Read(BinaryReader writer) {}
		public void Write(BinaryWriter writer)
		{
			writer.WriteE(Tag);
			Value.Write(writer);
		}
	}
}


text:
define(['grasshopperModel', 'masseuse'], function (Model, masseuse) {
    'use strict';

    var ComputedProperty = masseuse.ComputedProperty;

    return Model.extend({
        defaults : {
            label : new ComputedProperty(['fields'], function() {
                if(this.get('meta.labelfield')) {
                    return this.get('fields.'+ [this.get('meta.labelfield')]);
                }
            })
        }
    });

});


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var common_1 = require("@angular/common");
var forms_1 = require("@angular/forms");
var forms_component_1 = require("./forms.component");
var theme_module_1 = require("../../theme/theme.module");
var forms_routing_module_1 = require("./forms-routing.module");
var standardFields_component_1 = require("./standardFields/standardFields.component");
var validationStates_component_1 = require("./validationStates/validationStates.component");
var inputGroups_component_1 = require("./inputGroups/inputGroups.component");
var ratingInputs_component_1 = require("./ratingInputs/ratingInputs.component");
var selectInputs_component_1 = require("./selectInputs/selectInputs.component");
var checkBoxesAndRadios_component_1 = require("./checkBoxesAndRadios/checkBoxesAndRadios.component");
var pictureUploader_component_1 = require("./pictureUploader/pictureUploader.component");
var ckeditor_component_1 = require("./ckeditor/ckeditor.component");
var layoutBascicForm_component_1 = require("./layoutBasicForm/layoutBascicForm.component");
var layoutBlockForm_component_1 = require("./layoutBlockForm/layoutBlockForm.component");
var layoutHorizontalForm_component_1 = require("./layoutHorizontalForm/layoutHorizontalForm.component");
var layoutInlineForm_component_1 = require("./layoutInlineForm/layoutInlineForm.component");
var layoutWithoutLabelsForm_component_1 = require("./layoutWithoutLabelsForm/layoutWithoutLabelsForm.component");
var ng2_bootstrap_1 = require("ng2-bootstrap/ng2-bootstrap");
//third part component
var ngx_uploader_1 = require("ngx-uploader");
var ng2_ckeditor_1 = require("ng2-ckeditor");
var FormscModule = (function () {
    function FormscModule() {
    }
    return FormscModule;
}());
FormscModule = __decorate([
    core_1.NgModule({
        imports: [
            forms_routing_module_1.FormsRoutingModule,
            common_1.CommonModule,
            forms_1.FormsModule,
            theme_module_1.ThemeModule,
            ng2_bootstrap_1.AlertModule.forRoot(),
            ng2_bootstrap_1.RatingModule.forRoot(),
            ngx_uploader_1.NgUploaderModule,
            ng2_ckeditor_1.CKEditorModule
        ],
        declarations: [
            forms_component_1.FormsComponent,
            validationStates_component_1.ValidationStatesComponent,
            standardFields_component_1.StandardFieldsComponent,
            inputGroups_component_1.InputGroupsComponent,
            ratingInputs_component_1.RatingInputsComponentt,
            selectInputs_component_1.SelectInputsComponent,
            checkBoxesAndRadios_component_1.CheckBoxesAndRadiosComponent,
            ckeditor_component_1.CkeditorComponent,
            layoutBascicForm_component_1.LayoutBasciFormComponent,
            layoutBlockForm_component_1.LayoutBlockFormComponent,
            layoutHorizontalForm_component_1.LayoutHorizontalForm,
            layoutInlineForm_component_1.LayoutInlineFormComponent,
            layoutWithoutLabelsForm_component_1.LayoutWithoutLabelsFormComponent,
            pictureUploader_component_1.PictureUploaderComponent
        ]
    })
], FormscModule);
exports.FormscModule = FormscModule;
//# sourceMappingURL=E:/Sonicwall/project/Sonicwall_demo/Sonicwall_demo/typescript-angular2-client/app/admin/pages/forms/forms.module.js.map


text:
import StrayRepository from "../../../seasoned/strayRepository.js";

const strayRepository = new StrayRepository();

function readStraysController(req, res) {
  const { verified, page } = req.query;
  strayRepository
    .readAll(verified, page)
    .then(strays => {
      res.send(strays);
    })
    .catch(error => {
      res.status(500).send({ success: false, message: error.message });
    });
}

export default readStraysController;


text:
package io.datakernel.common;

import io.datakernel.common.collection.IntrusiveLinkedList;
import io.datakernel.common.collection.IntrusiveLinkedList.Node;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

@SuppressWarnings("ConstantConditions")
public class IntrusiveLinkedListTest {
	private IntrusiveLinkedList<String> list;

	@Before
	public void before() {
		list = new IntrusiveLinkedList<>();
	}

	@Test
	public void testAdd() {
		assertTrue(list.isEmpty());
		assertEquals(0, list.size());
		assertNull(list.getFirstNode());
		assertNull(list.getLastNode());

		list.addFirstValue("2");
		assertEquals("2", list.getFirstNode().getValue());
		assertEquals("2", list.getLastNode().getValue());

		list.addFirstValue("1");
		assertEquals("1", list.getFirstNode().getValue());
		assertEquals("2", list.getLastNode().getValue());

		list.addLastValue("3");
		assertEquals("3", list.getLastNode().getValue());

		list.addLastValue("4");
		assertEquals("4", list.getLastNode().getValue());

		assertFalse(list.isEmpty());
		assertEquals(4, list.size());
		assertList("1", "2", "3", "4");

		list.clear();
		list.addLastValue("2");
		assertList("2");
	}

	@Test
	public void testRemove() {
		assertNull(list.removeFirstNode());
		assertNull(list.removeLastNode());

		list.addLastValue("1");
		Node<String> node = list.addLastValue("2");
		list.addLastValue("3");
		list.addLastValue("4");

		list.removeNode(node);
		assertList("1", "3", "4");

		assertNotNull(list.removeFirstNode());
		assertList("3", "4");

		assertNotNull(list.removeLastNode());
		assertList("3");

		list.clear();
		assertTrue(list.isEmpty());

		list.addLastValue("new");
		assertList("new");
	}

	@Test
	public void testMoveToFirst() {
		list.addLastValue("1");
		Node<String> el1 = list.addLastValue("2");
		list.addLastValue("3");
		Node<String> el2 = list.addLastValue("4");
		assertEquals("1", list.getFirstNode().getValue());
		assertEquals("4", list.getLastNode().getValue());

		list.moveNodeToFirst(el1);
		assertEquals("2", list.getFirstNode().getValue());
		assertEquals("4", list.getLastNode().getValue());
		assertList("2", "1", "3", "4");

		list.moveNodeToFirst(el1);
		assertEquals("2", list.getFirstNode().getValue());
		assertEquals("4", list.getLastNode().getValue());
		assertList("2", "1", "3", "4");

		list.moveNodeToFirst(el2);
		assertEquals("4", list.getFirstNode().getValue());
		assertEquals("3", list.getLastNode().getValue());
		assertList("4", "2", "1", "3");
	}

	@Test
	public void testMoveToLast() {
		list.addLastValue("1");
		Node<String> el1 = list.addLastValue("2");
		list.addLastValue("3");
		Node<String> el2 = list.addLastValue("4");

		assertEquals("1", list.getFirstNode().getValue());
		assertEquals("4", list.getLastNode().getValue());

		list.moveNodeToLast(el1);
		assertEquals("1", list.getFirstNode().getValue());
		assertEquals("2", list.getLastNode().getValue());
		assertList("1", "3", "4", "2");

		list.moveNodeToLast(el1);
		assertEquals("1", list.getFirstNode().getValue());
		assertEquals("2", list.getLastNode().getValue());
		assertList("1", "3", "4", "2");

		list.moveNodeToLast(el2);
		assertEquals("1", list.getFirstNode().getValue());
		assertEquals("4", list.getLastNode().getValue());
		assertList("1", "3", "2", "4");
	}

	private void assertList(String... expected) {
		Node<String> node = list.getFirstNode();
		for (String e : expected) {
			assertNotNull(node);
			assertEquals(e, node.getValue());
			node = node.getNext();
		}
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AzureBot
{
    public class VirtualMachine : Resource
    {
        public string Address { get; set; }

        public bool Start()
        {
            return true;
        }

        public bool Stop()
        {
            return true;
        }
    }
}


text:
---
layout: post
title: Testing Services with Http in Angular
imageUrl: /images/banner/testing-services-with-http-in-angular-2.jpg
date: 2016-11-28T00:00:00.000Z
update_date: 2017-02-28T00:00:00.000Z
summary: >-
  Want to learn how to test services in Angular that have an Http dependency?
  Read more here!
categories:
  - angular
tags:
  - angular2
  - services
  - http
  - testing
author: pascal_precht
related_posts:
  - Testing Angular Directives with Custom Matchers
  - RxJS Master Class and courseware updates
  - Advanced caching with RxJS
  - Custom Overlays with Angular's CDK - Part 2
  - Custom Overlays with Angular's CDK
  - Easy Dialogs with Angular Material
related_videos:
  - '175255006'
  - '193524896'
  - '189792758'
  - '189785428'
  - '175218351'
  - '189618526'

---

Testing is important. That's why Angular comes with a testing story out-of-the-box. Due to its dependency injection system, it's fairly easy to mock dependencies, swap out Angular modules, or even create so called "shallow" tests, which enable us to test Angular components, without actually depending on their views (DOM). In this article we're going to take a look at how to unit test a service that performs http calls, since there's a little bit more knowledge required to make this work.

### TABLE OF CONTENTS
{:.no_toc}
* TOC
{:toc}

## The Service we want to test

Let's start off by taking a look at the service want to test. Sure, sometimes we actually want to do test-driven development, where we **first** create the test and **then** implement the actual service. However, from a learning point of view, it's probably easier to grasp testing concepts when we first explore the APIs we want to test.

At thoughtram, we're currently recording screencasts and video tutorials, to provide additional content to our blog readers. In order to make all these videos more explorable, we're also building a little application that lets users browse and watch them. The video data is hosted on Vimeo, so we've created a service that fetches the data from their API.

Here's what our `VideoService` roughly looks like:

{% highlight js %}
{% raw %}
import { Injectable, Inject } from '@angular/core';
import { VIMEO_API_URL } from '../config';

import 'rxjs/add/operator/map';

@Injectable()
export class VideoService {

  constructor(private http: Http, @Inject(VIMEO_API_URL) private apiUrl) {}

  getVideos() {
    return this.http.get(`${this.apiUrl}/videos`)
                    .map(res => res.json().data);
  }
}
{% endraw %}
{% endhighlight %}

`getVideos()` returns an `Observable<Array<Video>>`. This is just an excerpt of the actual service we use in production. In reality, we cache the responses so we don't peform an http request every single time we call this method.

> **Special Tip**: If the `@Inject()` decorator is new to you, make sure to checkout this [article](/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html)

To use this service in our application, we first need to create a provider for it on our application module, later we will use it in our tests:

{% highlight js %}
{% raw %}
@NgModule({
  imports: [HttpModule]
  providers: [VideoService]
  ...
})
export class AppModule {}
{% endraw %}
{% endhighlight %}

Since the API returns an Observable, we need to subscribe to it to actually perform the http request. That's why the call side of the method looks something like this:

{% highlight js %}
{% raw %}
@Component()
export class VideoDashboard {

  private videos = [];

  constructor(private videoService: VideoService) {}

  ngOnInit() {
    this.videoService.getVideos()
        .subscribe(videos => this.videos = videos);
  }
}
{% endraw %}
{% endhighlight %}

Notice how we're passing a callback function to access the video data that is emitted by the Observable. We need to keep that in mind when testing these methods, because we can't call them synchronously. To get an introduction to Observables in conjunction with Angular, make sure to read [this article](/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html).

Alright, now that we know what the service we want to test looks like, let's take a look at writing the tests.

## Configuring a testing module

Before we can start writing test specs for our service APIs, we need to configure a testing module. This is needed because in our tests, we want to make sure that we aren't performing actual http requests and use a `MockBackend` instead. Our goal is to isolate the test scenario as much as we can without touching any other **real** dependencies. Since NgModules configure injectors, a testing module allows us to do exactly that.

When testing services or components that don't have any dependencies, we can just go ahead an instantiate them manually, using their constructors like this:

{% highlight js %}
{% raw %}
it('should do something', () => {
  let service = new VimeoService();

  expect(service.foo).toEqual('bar');
});
{% endraw %}
{% endhighlight %}

> **Special Tip**: When testing components and services that don't have any dependencies, we don't necessarily need to create a testing module.

To configure a testing module, we use Angular's `TestBed`. `TestBed` is Angular's primary API to configure and initialize environments for unit testing and provides methods for creating components and services in unit tests. We can create a module that overrides the actual dependencies with testing dependencies, using `TestBed.configureTestingModule()`.

{% highlight js %}
{% raw %}
import { TestBed } from '@angular/core/testing';

describe('VideoService', () => {

  beforeEach(() => {

    TestBed.configureTestingModule({
      ...
    });

  });
});
{% endraw %}
{% endhighlight %}

This will create an NgModule for every test spec, as we're running this code as part of a `beforeEach()` block. This is a [Jasmine](https://jasmine.github.io/) API. If you aren't familiar with Jasmine, we highly recommend reading their documentation.

Okay, but what does a configuration for such a testing module look like? Well, it's an NgModule, so it has pretty much the same API. Let's start with adding an `import` for `HttpModule` and a provider for `VideoService` like this:

{% highlight js %}
{% raw %}
import { HttpModule } from '@angular/http';
import { VideoService } from './video.service';
import { VIMEO_API_URL } from '../config';
...
TestBed.configureTestingModule({
  imports: [HttpModule],
  providers: [
    { provide: VIMEO_API_URL, useValue: 'http://example.com' },
    VideoService
  ]
});
...
{% endraw %}
{% endhighlight %}

This configures an injector for our tests that knows how to create our `VideoService`, as well as the `Http` service. However, what we actually want is an `Http` service that doesn't really perform http requests. How do we do that? It turns out that the `Http` service uses a `ConnectionBackend` to perform requests. If we find a way to swap that one out with a different backend, we get what we want.

To give a better picture, here's what the constructor of Angular's `Http` service looks like:

{% highlight js %}
{% raw %}
@Injectable()
export class Http {

  constructor(
    protected _backend: ConnectionBackend,
    protected _defaultOptions: RequestOptions
  ) {}

  ...
}
{% endraw %}
{% endhighlight %}

By adding an `HttpModule` to our testing module, providers for `Http`, `ConnectionBackend` and `RequestOptions` are already configured. However, using an NgModule's `providers` property, we can **override** providers that have been introduced by other imported NgModules! This is where Angular's dependency injection really shines!

### Overriding the Http Backend

In practice, this means we need to create a new provider for `Http`, which instantiates the class with a different `ConnectionBackend`. Angular's http module comes with a testing class `MockBackend`. **That** one not only ensures that no real http requests are performed, it also provides APIs to subscribe to opened connections and send mock responses.

{% highlight js %}
{% raw %}
import { HttpModule, Http, BaseRequestOptions, XHRBackend } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
...
TestBed.configureTestingModule({
  ...
  providers: [
    ...
    { provide: XHRBackend, useClass: MockBackend }
  ]
});
...
{% endraw %}
{% endhighlight %}

Wow, that was easy! We simply tell our injector to inject an instance of `MockBackend` whenever someone asks for an `XHRBackend`, which is what Angular's Http module does behind the scenes.

Awesome! We've created a testing module that uses an `Http` service with a `MockBackend`. Now let's take a look at how to actually test our service.

## Testing the service

When writing unit tests with Jasmine, every test spec is written as an `it()` block, where an assertion is made and then checked if that assertion is true or not. We won't go into too much detail here, since there's a lot of documentation for Jasmine out there. We want to test if our `VideoService` returns an `Observable<Array<Video>>`, so let's start with the following `it()` statement:

{% highlight js %}
{% raw %}
describe('VideoService', () => {
  ...
  describe('getVideos()', () => {

    it('should return an Observable<Array<Video>>', () => {
      // test goes here
    });
  });
});
{% endraw %}
{% endhighlight %}

We've also added another nested `describe()` block so we can group all tests that are related to that particular method we test. Okay, next we need to get an instance of our `VideoService`. Since we've created a testing module that comes with all providers for our services, we can use dependency injection to inject instances accordingly.

### Injecting Services

Angular's testing module comes with a helper function `inject()`, which injects service dependencies. This turns out to be super handy as we don't have to take care of getting access to the injector ourselves. `inject()` takes a list of provider tokens and a function with the test code, and it **returns** a function in which the test code is executed. That's why we can pass it straight to our spec and remove the anonymous function we've introduced in the first place:

{% highlight js %}
{% raw %}
import { TestBed, inject } from '@angular/core/testing';
...
it('should return an Observable<Array<Video>>',
  inject([/* provider tokens */], (/* dependencies */) => {
  // test goes here
}));
{% endraw %}
{% endhighlight %}

Cool, now we have all the tools we need to inject our services and write a test. Let's go ahead an do exactly that. Once we have our service injected, we can call `getVideos()` and subscribe to the Observable it returns, to then test if the emitted value is the one we expect.

{% highlight js %}
{% raw %}
it('should return an Observable<Array<Video>>',
  inject([VideoService], (videoService) => {

    videoService.getVideos().subscribe((videos) => {
      expect(videos.length).toBe(4);
      expect(videos[0].name).toEqual('Video 0');
      expect(videos[1].name).toEqual('Video 1');
      expect(videos[2].name).toEqual('Video 2');
      expect(videos[3].name).toEqual('Video 3');
    });
}));
{% endraw %}
{% endhighlight %}

**This test is not finished yet.** Right now we're having a test that expects some certain data that is going to be emitted by `getVideos()`, however, remember we've swapped out the `Http` backend so there's no actual http request performed? Right, if there's no request performed, this Observable won't emit anything. We need a way to fake a response that is emitted when we subscribe to our Observable.

### Mocking http responses

As mentioned earlier, `MockBackend` provides APIs to not only subscribe to http connections, it also enables us to send mock responses. What we want is, when the underlying `Http` service creates a connection (performs a request), send a fake http response with the data we're asserting in our `getVideos()` subscription.

We can subscribe to all opened http connections via `MockBackend.connections`, and get access to a `MockConnection` like this:

{% highlight js %}
{% raw %}
it('should return an Observable<Array<Video>>',
  inject([VideoService, XHRBackend], (videoService, mockBackend) => {
    mockBackend.connections.subscribe((connection) => {
      // This is called every time someone subscribes to
      // an http call.
      //
      // Here we want to fake the http response.
    });

    ...
}));
{% endraw %}
{% endhighlight %}

The next thing we need to do, is to make the connection send a response. We use `MockConnection.mockRespond()` for that, which takes an instance of Angular's `Response` class. In order to define what the response looks like, we need to create `ResponseOptions` and define the response body we want to send (which is a string):

{% highlight js %}
{% raw %}
...
const mockResponse = {
  data: [
    { id: 0, name: 'Video 0' },
    { id: 1, name: 'Video 1' },
    { id: 2, name: 'Video 2' },
    { id: 3, name: 'Video 3' },
  ]
};

mockBackend.connections.subscribe((connection) => {
  connection.mockRespond(new Response(new ResponseOptions({
    body: JSON.stringify(mockResponse)
  })));
});
...
{% endraw %}
{% endhighlight %}

Cool! With this code we now get a fake response inside that particular test spec. Even though it looks like we're done, **there's one more thing we need to do**.

### Making the test asynchronous

<s>Because the code we want to test is asynchronous, we need to inform Jasmine when the asynchronous operation is done, so it can run our assertions.</s>

[Johannes Hoppe pointed out](http://stackoverflow.com/questions/41273244/angular-testing-http-with-mockbackend-is-async-really-required) that `MockConnection.mockRespond()` actually emits **synchronously**, not asynchronously, which means that the rest of this section is not needed for our particular test (Thank you Johannes!). However, it's still a useful gem if we **are** writing tests that need asynchronous operations, read on!

When testing asynchronous code, assertions might be executed later in another tick. That's why we can explicitly tell Jasmine that we're writing an asynchronous test. We just need to also tell Jasmine, when the actual code is "done".

Jasmine usually provides access to a function `done()` that we can ask for inside our test spec and then call it when we think our code is done. This looks something like this:

{% highlight js %}
{% raw %}
it('should do something async', (done) => {
  setTimeout(() => {
    expect(true).toBe(true);
    done();
  }, 2000);
});
{% endraw %}
{% endhighlight %}

Angular makes this a little bit more convenient. It comes with another helper function `async()` which takes a test spec and then runs `done()` behind the scenes for us. This is pretty cool, because we can write our test code as if it was synchronous!

How does that work? Well... Angular takes advantage of a feature called Zones. It creates a "testZone", which automatically figures out when it needs to call `done()`. If you havent heard about Zones before, we wrote about them [here](/angular/2016/01/22/understanding-zones.html) and [here](/angular/2016/02/01/zones-in-angular-2.html).

> **Special Tip**: Angular's `async()` function executes test specs in a test zone!

## The complete code

Putting it all together, here's what the test spec for the `getVideos()` method looks like:

{% highlight js %}
{% raw %}
import { TestBed, async, inject } from '@angular/core/testing';
import {
  HttpModule,
  Http,
  Response,
  ResponseOptions,
  XHRBackend
} from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { VideoService } from './video.service';
import { VIMEO_API_URL } from '../config';

describe('VideoService', () => {

  beforeEach(() => {

    TestBed.configureTestingModule({
      imports: [HttpModule],
      providers: [
        { provide: VIMEO_API_URL, useValue: 'http://example.com' },
        VideoService,
        { provide: XHRBackend, useClass: MockBackend },
      ]
    });
  });

  describe('getVideos()', () => {

    it('should return an Observable<Array<Video>>',
        inject([VideoService, XHRBackend], (videoService, mockBackend) => {

        const mockResponse = {
          data: [
            { id: 0, name: 'Video 0' },
            { id: 1, name: 'Video 1' },
            { id: 2, name: 'Video 2' },
            { id: 3, name: 'Video 3' },
          ]
        };

        mockBackend.connections.subscribe((connection) => {
          connection.mockRespond(new Response(new ResponseOptions({
            body: JSON.stringify(mockResponse)
          })));
        });

        videoService.getVideos().subscribe((videos) => {
          expect(videos.length).toBe(4);
          expect(videos[0].name).toEqual('Video 0');
          expect(videos[1].name).toEqual('Video 1');
          expect(videos[2].name).toEqual('Video 2');
          expect(videos[3].name).toEqual('Video 3');
        });

    }));
  });
});
{% endraw %}
{% endhighlight %}

This pattern works for pretty much every test that involves http operations. Hopefully this gave you a better understanding of what `TestBed`, `MockBackend` and `async` are all about.


text:
                        搜索:

                            <input id="authEdtSearch" class="layui-input" type="text" placeholder="输入关键字"/>

                        <button id="authBtnSearch" class="layui-btn icon-btn">搜索
                        </button>
                        <button id="authBtnSync" class="layui-btn icon-btn">同步
                        </button>


text:
package sotrc.common;

import java.io.*;
import common.*;

/**
 * Basically a persistable string.
 * To be wrapped in Encrypted to send over.
 */
public class Message implements Persistable {
	private String message;

	public Message(String message) {
		this.message = message;
	}

	@Override public void persist(OutputStream os) throws IOException {
		DataOutputStream dos = new DataOutputStream(os);
		dos.writeUTF(message);
	}
	@Override public void reconstruct(InputStream is) throws IOException {
		DataInputStream dis = new DataInputStream(is);
		this.message = dis.readUTF();
	}

	@Override
	public String toString() {
		return this.message;
	}
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:app="http://schemas.android.com/apk/res-auto"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:background="@color/colorPrimary"
             tools:context="com.karambit.bookie.fragment.HomeFragment">

    <com.karambit.bookie.helper.pull_refresh_layout.PullRefreshLayout
        android:id="@+id/swipeRefreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:refreshColor="@color/progressBarColor"
        app:refreshType="smartisan">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/homeRecyclerView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:overScrollMode="never"/>
    </com.karambit.bookie.helper.pull_refresh_layout.PullRefreshLayout>

</FrameLayout>


text:
/* AFE Firmware for smarthome devices, More info: https://afe.smartnydom.pl/ */

#ifndef _AFE_Thermal_Protection_h
#define _AFE_Thermal_Protection_h

#include <AFE-Configuration.h>
#ifdef AFE_CONFIG_FUNCTIONALITY_THERMAL_PROTECTOR

#include <AFE-Data-Access.h>

#ifdef DEBUG
#include <Streaming.h>
#endif

class AFEThermalProtector {

private:
  AFEDataAccess *_Data;
  uint8_t _id;

  /* Method enables / disables thermal protector */
  void enable(void);

public:
  THERMAL_PROTECTOR *configuration = new THERMAL_PROTECTOR;
  boolean turnOff = false;

  /* Constructors */
  AFEThermalProtector();

  /* Method initialize protection */
  void begin(AFEDataAccess *, uint8_t id);

  /* Method monitors current temeprature and allowed one */
  bool listener(float currentTemperature);

  /* Method turns on thermal protector */
  void on(void);

  /* Method turns off therthermal protector mostat */
  void off(void);

  /* Method turns thermal protector  to opposite to current state */
  void toggle(void);

  /* Returns the sensor data in JSON format */
  void getJSON(char *json);
};

#endif // AFE_CONFIG_FUNCTIONALITY_THERMAL_PROTECTOR
#endif // _AFE_Thermal_Protection_h


text:
"""Classes for handling high score tables.
"""

import os

def High(fname,limit=10):
    """Create a Highs object and returns the default high score table.

    Arguments:
        fname -- filename to store high scores in
        limit -- limit of scores to be recorded, defaults to 10

    """
    return Highs(fname,limit)['default']

class _Score:
    def __init__(self,score,name,data=None):
        self.score,self.name,self.data=score,name,data

class _High:
    """A high score table.  These objects are passed to the user, but should
    not be created directly.

    You can iterate them:
        for e in myhigh:
            print(e.score,e.name,e.data)

    You can modify them:
        myhigh[0].name = 'Cuzco'

    You can find out their length:
        print(len(myhigh))
    """

    def __init__(self,highs,limit=10):
        self.highs = highs
        self._list = []
        self.limit = limit

    def save(self):
        """Save the high scores."""
        self.highs.save()

    def submit(self,score,name,data=None):
        """Submit a high score to this table.

        Return -- the position in the table that the score attained.  None if
        the score did not attain a position in the table.

        """
        n = 0
        for e in self._list:
            if score > e.score:
                self._list.insert(n,_Score(score,name,data))
                self._list = self._list[0:self.limit]
                return n
            n += 1
        if len(self._list) < self.limit:
            self._list.append(_Score(score,name,data))
            return len(self._list)-1

    def check(self,score):
        """Check if a score will attain a position in the table.

        Return -- the position the score will attain, else None

        """
        n = 0
        for e in self._list:
            if score > e.score:
                return n
            n += 1
        if len(self._list) < self.limit:
            return len(self._list)

    def __iter__(self):
        return self._list.__iter__()

    def __getitem__(self,key):
        return self._list[key]

    def __len__(self):
        return self._list.__len__()

class Highs:
    """The high score object.

    Arguments:
        fname -- filename to store high scores in
        limit -- limit of scores to be recorded, defaults to 10

    You may access _High objects through this object:

        my_easy_hs = highs['easy']
        my_hard_hs = highs['hard']

    """
    def __init__(self,fname,limit=10):
        self.fname = fname
        self.limit = limit
        self.load()

    def load(self):
        """Re-load the high scores."""

        self._dict = {}
        try:
            f = open(self.fname)
            for line in f.readlines():
                key,score,name,data = line.strip().split("\t")
                if key not in self._dict:
                    self._dict[key] = _High(self,self.limit)
                high = self._dict[key]
                high.submit(int(score),name,data)
            f.close()
        except:
            pass

    def save(self):
        """Save the high scores."""

        f = open(self.fname,"w")
        for key,high in self._dict.items():
            for e in high:
                f.write("%s\t%d\t%s\t%s\n"%(key,e.score,e.name,str(e.data)))
        f.close()

    def __getitem__(self,key):
        if key not in self._dict:
            self._dict[key] = _High(self,self.limit)
        return self._dict[key]


text:
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''

---

#### Describe the bug

[A clear and concise description of what the bug is. This should explain **why** the current behaviour is a problem and why the expected output is a better solution.]

#### Code Sample, a copy-pastable example if possible

```python
# Your code here that produces the bug
# This example should be self-contained, and so not rely on external data.
# It should run in a fresh ipython session, and so include all relevant imports.
```
<details>

**Note**: As you can see, there are many issues on our GitHub tracker, so it is very possible that your issue has been posted before. Please check first before submitting so that we do not have to handle and close duplicates.

**Note**: Please be sure you are using the latest released version of `statsmodels`, or a recent build of `master`. If your problem has been fixed in an unreleased version, you might be able to use `master` until a new release occurs.

**Note**: If you are using a released version, have you verified that the bug exists in the master branch of this repository? It helps the limited resources if we know problems exist in the current master so that they do not need to check whether the code sample produces a bug in the next release.

</details>

If the issue has not been resolved, please file it in the issue tracker.

#### Expected Output

A clear and concise description of what you expected to happen.

#### Output of ``import statsmodels.api as sm; sm.show_versions()``

<details>

[paste the output of ``import statsmodels.api as sm; sm.show_versions()`` here below this line]

</details>


text:
describe(`queries in packages`, () => {
  beforeEach(() => {
    cy.visit(`/queries-in-packages`).waitForRouteChange()
  })

  it(`Should extract and run query from gatsby component`, () => {
    // we are using `gatsby-seo` package which sets
    // window's title to title passed as prop followed by siteMetadata.title
    cy.title().should(
      `eq`,
      `Testing queries in packages | Gatsby Default Starter`
    )
  })
})


text:
package org.apache.kylin.gridtable.benchmark;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Random;

import org.apache.kylin.common.util.ByteArray;
import org.apache.kylin.common.util.BytesUtil;
import org.apache.kylin.common.util.ImmutableBitSet;
import org.apache.kylin.gridtable.GTInfo;
import org.apache.kylin.gridtable.GTInfo.Builder;
import org.apache.kylin.gridtable.GTRecord;
import org.apache.kylin.gridtable.GTSampleCodeSystem;
import org.apache.kylin.gridtable.GTScanRequest;
import org.apache.kylin.gridtable.GTScanRequestBuilder;
import org.apache.kylin.gridtable.IGTScanner;
import org.apache.kylin.gridtable.benchmark.SortedGTRecordGenerator.Randomizer;
import org.apache.kylin.measure.hllc.HLLCounter;
import org.apache.kylin.metadata.datatype.DataType;
import org.apache.kylin.metadata.filter.ColumnTupleFilter;
import org.apache.kylin.metadata.filter.CompareTupleFilter;
import org.apache.kylin.metadata.filter.ConstantTupleFilter;
import org.apache.kylin.metadata.filter.LogicalTupleFilter;
import org.apache.kylin.metadata.filter.TupleFilter;
import org.apache.kylin.metadata.filter.TupleFilter.FilterOperatorEnum;

import org.apache.kylin.shaded.com.google.common.collect.Lists;

/**
 * Benchmark of processing 10 million GTRecords. 5 dimensions of type int4, and 2 measures of type long8.
 *
 * All the same as GTScannerBenchmark except for the last measure is single-value HLLC
 */
public class GTScannerBenchmark2 {

    final GTInfo info;
    final SortedGTRecordGenerator gen;

    final ImmutableBitSet dimensions = ImmutableBitSet.valueOf(0, 1, 2, 3, 4);
    final ImmutableBitSet metrics = ImmutableBitSet.valueOf(5, 6);
    final String[] aggrFuncs = new String[] { "SUM", "COUNT_DISTINCT" };

    final long N = 10000000; // 10M
    final long genTime;

    public GTScannerBenchmark2() {
        Builder builder = GTInfo.builder();
        builder.setCodeSystem(new GTSampleCodeSystem());
        DataType tint = DataType.getType("int4");
        DataType tlong = DataType.getType("long8");
        DataType thllc = DataType.getType("hllc(12)");
        builder.setColumns(tint, tint, tint, tint, tint, tlong, thllc);
        builder.setPrimaryKey(ImmutableBitSet.valueOf(0, 1, 2, 3, 4));
        info = builder.build();

        gen = new SortedGTRecordGenerator(info);
        gen.addDimension(10, 4, null);
        gen.addDimension(10, 4, null);
        gen.addDimension(10, 4, null);
        gen.addDimension(10, 4, null);
        gen.addDimension(100, 4, null);
        gen.addMeasure(8);
        gen.addMeasure(8, new Randomizer() {
            HLLCounter hllc = new HLLCounter(12);

            @Override
            public int fillRandom(Random rand, byte[] array, int offset) {
                try {
                    hllc.clear();
                    hllc.add(rand.nextInt());
                    ByteBuffer wrap = ByteBuffer.wrap(array, offset, array.length - offset);
                    hllc.writeRegisters(wrap);
                    return wrap.position() - offset;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        // warm up
        long t = System.currentTimeMillis();
        testGenerate();
        genTime = System.currentTimeMillis() - t;
    }

    @SuppressWarnings("unused")
    public void testGenerate() {
        long count = 0;
        for (GTRecord rec : gen.generate(N)) {
            count++;
        }
    }

    //@Test
    public void testAggregate2() throws IOException {
        testAggregate(ImmutableBitSet.valueOf(0, 1));
    }

    //@Test
    public void testAggregate2_() throws IOException {
        testAggregate(ImmutableBitSet.valueOf(0, 2));
    }

    //@Test
    public void testAggregate4() throws IOException {
        testAggregate(ImmutableBitSet.valueOf(0, 1, 2, 3));
    }

    //@Test
    public void testAggregate5() throws IOException {
        testAggregate(ImmutableBitSet.valueOf(0, 1, 2, 3, 4));
    }

    @SuppressWarnings("unused")
    private void testAggregate(ImmutableBitSet groupBy) throws IOException {
        long t = System.currentTimeMillis();
        GTScanRequest req = new GTScanRequestBuilder().setInfo(info).setRanges(null).setDimensions(dimensions).setAggrGroupBy(groupBy).setAggrMetrics(metrics).setAggrMetricsFuncs(aggrFuncs).setFilterPushDown(null).createGTScanRequest();
        IGTScanner scanner = req.decorateScanner(gen.generate(N));

        long count = 0;
        for (GTRecord rec : scanner) {
            count++;
        }

        t = System.currentTimeMillis() - t;
        System.out.println(N + " records aggregated to " + count + ", " + calcSpeed(t) + "K rec/sec");
    }

    private int calcSpeed(long t) {
        double sec = (double) (t - genTime) / 1000;
        return (int) (N / sec / 1000);
    }

    //@Test
    public void testFilter1() throws IOException {
        testFilter(eq(col(1), 1, 5, 7));
    }

    //@Test
    public void testFilter2() throws IOException {
        testFilter(//
                and(//
                        gt(col(0), 5), //
                        eq(col(2), 2, 4)));
    }

    //@Test
    public void testFilter3() throws IOException {
        testFilter(//
                and(//
                        gt(col(0), 2), //
                        eq(col(4), 1, 3, 5, 9, 12, 14, 23, 43, 52, 78, 92), //
                        or(//
                                eq(col(1), 2, 4), //
                                eq(col(2), 2, 4, 5, 9))));
    }

    @SuppressWarnings("unused")
    private void testFilter(TupleFilter filter) throws IOException {
        long t = System.currentTimeMillis();
        GTScanRequest req = new GTScanRequestBuilder().setInfo(info).setRanges(null).setDimensions(info.getAllColumns()).setFilterPushDown(filter).createGTScanRequest();
        IGTScanner scanner = req.decorateScanner(gen.generate(N));

        long count = 0;
        for (GTRecord rec : scanner) {
            count++;
        }

        t = System.currentTimeMillis() - t;
        System.out.println(N + " records filtered to " + count + ", " + calcSpeed(t) + "K rec/sec");
    }

    private LogicalTupleFilter and(TupleFilter... filters) {
        return logical(FilterOperatorEnum.AND, filters);
    }

    private LogicalTupleFilter or(TupleFilter... filters) {
        return logical(FilterOperatorEnum.OR, filters);
    }

    private LogicalTupleFilter logical(FilterOperatorEnum op, TupleFilter[] filters) {
        LogicalTupleFilter r = new LogicalTupleFilter(op);
        for (TupleFilter f : filters)
            r.addChild(f);
        return r;
    }

    private CompareTupleFilter gt(ColumnTupleFilter col, int v) {
        CompareTupleFilter r = new CompareTupleFilter(FilterOperatorEnum.GT);
        r.addChild(col);

        int c = col.getColumn().getColumnDesc().getZeroBasedIndex();
        int len = info.getCodeSystem().maxCodeLength(c);
        ByteArray bytes = new ByteArray(len);
        BytesUtil.writeLong(v, bytes.array(), bytes.offset(), len);
        r.addChild(new ConstantTupleFilter(bytes));

        return r;
    }

    private CompareTupleFilter eq(ColumnTupleFilter col, int... values) {
        CompareTupleFilter r = new CompareTupleFilter(FilterOperatorEnum.IN);
        r.addChild(col);

        List<ByteArray> list = Lists.newArrayList();
        for (int v : values) {
            int c = col.getColumn().getColumnDesc().getZeroBasedIndex();
            int len = info.getCodeSystem().maxCodeLength(c);
            ByteArray bytes = new ByteArray(len);
            BytesUtil.writeLong(v, bytes.array(), bytes.offset(), len);
            list.add(bytes);
        }
        r.addChild(new ConstantTupleFilter(list));
        return r;
    }

    private ColumnTupleFilter col(int i) {
        return new ColumnTupleFilter(info.colRef(i));
    }

    public static void main(String[] args) throws IOException {
        GTScannerBenchmark2 benchmark = new GTScannerBenchmark2();

        benchmark.testFilter1();
        benchmark.testFilter2();
        benchmark.testFilter3();

        benchmark.testAggregate2();
        benchmark.testAggregate2_();
        benchmark.testAggregate4();
        //benchmark.testAggregate5(); // causes OOM in 4G heap
    }
}


text:
var page = tabris.create("Page", {
  title: "Text Input",
  topLevel: true
});

tabris.create("TextInput", {
  layoutData: {top: 20, left: "20%", right: "20%"},
  message: "Type here, then confirm"
}).on("accept", function(widget, text) {
  tabris.create("TextView", {
    layoutData: {top: [page.children().last(), 20], left: "20%"},
    text: text
  }).appendTo(page);
}).appendTo(page);

page.open();


text:
using System.Collections;
using System.Collections.Generic;

namespace Tests.Collections.Implementations
{
    public class GenericStringEnumerableImpl : IEnumerable<string>
    {
        private readonly IEnumerable<string> _enumerable;

        public GenericStringEnumerableImpl()
        {
            _enumerable = new List<string>();
        }

        public GenericStringEnumerableImpl(IEnumerable<string> enumerable)
        {
            _enumerable = enumerable;
        }

        public IEnumerator<string> GetEnumerator()
        {
            return _enumerable.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}


text:
"""`FadingTemporal`"""
import numpy as np
from .base import TemporalModel
from ._temporal import fading_fast

class FadingTemporal(TemporalModel):
    """A generic temporal model for phosphene fading

    Implements phosphene fading using a leaky integrator:

    .. math::

        \\frac{dB}{dt} = -\\frac{A+B}{\\tau}

    where :math:`A` is the stimulus  amplitude, :math:`B` is the perceived
    brightness, and :math:`\\tau` is the exponential  decay constant (``tau``).

    The model makes the following assumptions:

    *  Cathodic currents (negative amplitudes) will increase perceived
       brightness
    *  Anodic currents (positive amplitudes) will decrease brightness
    *  Brightness is bounded in :math:`[\\theta, \\infty]`, where
       :math:`\\theta` (``thresh_percept``) is a nonnegative scalar

    Parameters
    ----------
    dt : float, optional
        Sampling time step of the simulation (ms)
    tau : float, optional
        Time decay constant for the exponential decay (ms).
        Larger values lead to slower decay.
        Brightness should decay to half its peak ("half-life") after
        :math:`\\ln(2) \\tau` milliseconds.
    thresh_percept: float, optional
        Below threshold, the percept has brightness zero.
    n_threads: int, optional
            Number of CPU threads to use during parallelization using OpenMP. Defaults to max number of user CPU cores.

    .. versionadded:: 0.7.1

    """

    def get_default_params(self):
        base_params = super(FadingTemporal, self).get_default_params()
        params = {
            # Time constant for the exponential decay:
            'tau': 100,
        }
        # This is subtle: Rather than calling `params.update(base_params)`, we
        # call `base_params.update(params)`. This will overwrite `base_params`
        # with values from `params`, which allows us to set `thresh_percept`=0
        # rather than what the BaseModel dictates:
        base_params.update(params)
        return base_params

    def _build(self):
        if self.tau < 0:
            raise ValueError('"tau" cannot be negative.')

    def _predict_temporal(self, stim, t_percept):
        """Predict the temporal response"""
        # Pass the stimulus as a 2D NumPy array to the fast Cython function:
        stim_data = stim.data.reshape((-1, len(stim.time)))
        # Calculate at which simulation time steps we need to output a percept.
        # This is basically t_percept/self.dt, but we need to beware of
        # floating point rounding errors! 29.999 will be rounded down to 29 by
        # np.uint32, so we need to np.round it first:
        idx_percept = np.uint32(np.round(t_percept / self.dt))
        if np.unique(idx_percept).size < t_percept.size:
            raise ValueError(f"All times 't_percept' must be distinct multiples "
                             f"of `dt`={self.dt:.2e}")
        # Cython returns a 2D (space x time) NumPy array:
        return fading_fast(stim_data.astype(np.float32),
                           stim.time.astype(np.float32),
                           idx_percept, self.dt, self.tau, self.thresh_percept, self.n_threads)