text:
package org.apache.camel.component.cache;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.Configuration;
import org.apache.camel.support.ServiceSupport;
import org.apache.camel.util.ReflectionHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class CacheManagerFactory extends ServiceSupport {
    private static final Logger LOG = LoggerFactory.getLogger(CacheManagerFactory.class);
    private CacheManager cacheManager;

    public synchronized CacheManager getInstance() {
        if (cacheManager == null) {
            cacheManager = createCacheManagerInstance();

            // always turn off ET phone-home
            LOG.debug("Turning off EHCache update checker ...");
            Configuration config = cacheManager.getConfiguration();
            try {
                // need to set both the system property and bypass the setUpdateCheck method as that can be changed dynamically
                System.setProperty("net.sf.ehcache.skipUpdateCheck", "true");
                ReflectionHelper.setField(config.getClass().getDeclaredField("updateCheck"), config, false);

                LOG.info("Turned off EHCache update checker. updateCheck={}", config.getUpdateCheck());
            } catch (Throwable e) {
                // ignore
                LOG.warn("Error turning off EHCache update checker. Beware information sent over the internet!", e);
            }
        }

        return cacheManager;
    }

    /**
     * Creates {@link CacheManager}.
     * <p/>
     * The default implementation is {@link DefaultCacheManagerFactory}.
     *
     * @return {@link CacheManager}
     */
    protected abstract CacheManager createCacheManagerInstance();

    @Override
    protected void doStart() throws Exception {
    }

    @Override
    protected synchronized void doStop() throws Exception {
        // only shutdown cache manager if no longer in use
        // (it may be reused when running in app servers like Karaf)
        if (cacheManager != null) {
            int size = cacheManager.getCacheNames().length;
            if (size <= 0) {
                LOG.info("Shutting down CacheManager as its no longer in use");
                cacheManager.shutdown();
                cacheManager = null;
            } else {
                LOG.info("Cannot stop CacheManager as its still in use by {} clients", size);
            }
        }
    }
}


text:
/**
* Find the maximum number in a sequence.
**/
int findMax(int numbers[], int size);

/**
* Finds the maximum number of a sequence but excluding a specific value.
**/
int findMaxExcept(int numbers[], int size, int except);

/**
* Calculates the maximum pairwise product of the numbers in an array.
**/
long long MaxPairwiseProduct(int numbers[], int size);

redpajama_set_name: RedPajamaGithub


text:
describe('<Account />', () => {
  it('Expect to have unit tests specified', () => {
    expect(true).toEqual(false);
  });
});


text:
           <link type="text/css" rel="stylesheet" href="./resources/templates/f39803f7-df02-4169-93eb-7547fb8c961a-1445822636718.css" />

           <link type="text/css" rel="stylesheet" href="./resources/screens/b8531a48-211d-41e4-97d3-c673bab8b2d9-1445822636718.css" />

收入

首页







4:02 PM



80%

收入折线图说明






text:
package org.apache.nifi.processors.elasticsearch;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.apache.commons.io.IOUtils;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.OngoingStubbing;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class TestQueryElasticsearchHttpNoHits {

        private TestRunner runner;

        @AfterEach
        public void teardown() {
                runner = null;
        }

        @Test
        public void testQueryElasticsearchOnTrigger_NoHits_NoHits() throws IOException {
                runner = TestRunners.newTestRunner(new QueryElasticsearchHttpTestProcessor());
                runner.setValidateExpressionUsage(true);
                runner.setProperty(AbstractElasticsearchHttpProcessor.ES_URL, "http://127.0.0.1:9200");

                runner.setProperty(QueryElasticsearchHttp.INDEX, "doc");
                runner.assertNotValid();
                runner.setProperty(QueryElasticsearchHttp.TYPE, "status");
                runner.assertNotValid();
                runner.setProperty(QueryElasticsearchHttp.QUERY,
                        "source:Twitter AND identifier:\"${identifier}\"");
                runner.assertValid();
                runner.setProperty(QueryElasticsearchHttp.PAGE_SIZE, "2");
                runner.assertValid();
                runner.setProperty(QueryElasticsearchHttp.ROUTING_QUERY_INFO_STRATEGY, QueryElasticsearchHttp.QueryInfoRouteStrategy.NOHIT.name());
                runner.assertValid();

                runner.setIncomingConnection(false);
                runAndVerify(0,1,0,true);
        }

        @Test
        public void testQueryElasticsearchOnTrigger_NoHits_Never() throws IOException {
                runner = TestRunners.newTestRunner(new QueryElasticsearchHttpTestProcessor());
                runner.setValidateExpressionUsage(true);
                runner.setProperty(AbstractElasticsearchHttpProcessor.ES_URL, "http://127.0.0.1:9200");

                runner.setProperty(QueryElasticsearchHttp.INDEX, "doc");
                runner.assertNotValid();
                runner.setProperty(QueryElasticsearchHttp.TYPE, "status");
                runner.assertNotValid();
                runner.setProperty(QueryElasticsearchHttp.QUERY,
                        "source:Twitter AND identifier:\"${identifier}\"");
                runner.assertValid();
                runner.setProperty(QueryElasticsearchHttp.PAGE_SIZE, "2");
                runner.assertValid();
                runner.setProperty(QueryElasticsearchHttp.ROUTING_QUERY_INFO_STRATEGY, QueryElasticsearchHttp.QueryInfoRouteStrategy.NEVER.name());
                runner.assertValid();

                runner.setIncomingConnection(false);
                runAndVerify(0,0,0,true);
        }

        @Test
        public void testQueryElasticsearchOnTrigger_NoHits_Always() throws IOException {
                runner = TestRunners.newTestRunner(new QueryElasticsearchHttpTestProcessor());
                runner.setValidateExpressionUsage(true);
                runner.setProperty(AbstractElasticsearchHttpProcessor.ES_URL, "http://127.0.0.1:9200");

                runner.setProperty(QueryElasticsearchHttp.INDEX, "doc");
                runner.assertNotValid();
                runner.setProperty(QueryElasticsearchHttp.TYPE, "status");
                runner.assertNotValid();
                runner.setProperty(QueryElasticsearchHttp.QUERY,
                        "source:Twitter AND identifier:\"${identifier}\"");
                runner.assertValid();
                runner.setProperty(QueryElasticsearchHttp.PAGE_SIZE, "2");
                runner.assertValid();
                runner.setProperty(QueryElasticsearchHttp.ROUTING_QUERY_INFO_STRATEGY, QueryElasticsearchHttp.QueryInfoRouteStrategy.ALWAYS.name());
                runner.assertValid();

                runner.setIncomingConnection(false);
                runAndVerify(0,1,0,true);
        }

        @Test
        public void testQueryElasticsearchOnTrigger_Hits_NoHits() throws IOException {
                runner = TestRunners.newTestRunner(new QueryElasticsearchHttpTestProcessor(true));
                runner.setValidateExpressionUsage(true);
                runner.setProperty(AbstractElasticsearchHttpProcessor.ES_URL, "http://127.0.0.1:9200");

                runner.setProperty(QueryElasticsearchHttp.INDEX, "doc");
                runner.assertNotValid();
                runner.setProperty(QueryElasticsearchHttp.TYPE, "status");
                runner.assertNotValid();
                runner.setProperty(QueryElasticsearchHttp.QUERY,
                        "source:Twitter AND identifier:\"${identifier}\"");
                runner.assertValid();
                runner.setProperty(QueryElasticsearchHttp.PAGE_SIZE, "2");
                runner.assertValid();
                runner.setProperty(QueryElasticsearchHttp.ROUTING_QUERY_INFO_STRATEGY, QueryElasticsearchHttp.QueryInfoRouteStrategy.NOHIT.name());
                runner.assertValid();

                runner.setIncomingConnection(false);
                runAndVerify(3,0,0,true);
        }

        @Test
        public void testQueryElasticsearchOnTrigger_Hits_Never() throws IOException {
                runner = TestRunners.newTestRunner(new QueryElasticsearchHttpTestProcessor(true));
                runner.setValidateExpressionUsage(true);
                runner.setProperty(AbstractElasticsearchHttpProcessor.ES_URL, "http://127.0.0.1:9200");

                runner.setProperty(QueryElasticsearchHttp.INDEX, "doc");
                runner.assertNotValid();
                runner.setProperty(QueryElasticsearchHttp.TYPE, "status");
                runner.assertNotValid();
                runner.setProperty(QueryElasticsearchHttp.QUERY,
                        "source:Twitter AND identifier:\"${identifier}\"");
                runner.assertValid();
                runner.setProperty(QueryElasticsearchHttp.PAGE_SIZE, "2");
                runner.assertValid();
                runner.setProperty(QueryElasticsearchHttp.ROUTING_QUERY_INFO_STRATEGY, QueryElasticsearchHttp.QueryInfoRouteStrategy.NEVER.name());
                runner.assertValid();

                runner.setIncomingConnection(false);
                runAndVerify(3,0,0,true);
        }

        @Test
        public void testQueryElasticsearchOnTrigger_Hits_Always() throws IOException {
                runner = TestRunners.newTestRunner(new QueryElasticsearchHttpTestProcessor(true));
                runner.setValidateExpressionUsage(true);
                runner.setProperty(AbstractElasticsearchHttpProcessor.ES_URL, "http://127.0.0.1:9200");

                runner.setProperty(QueryElasticsearchHttp.INDEX, "doc");
                runner.assertNotValid();
                runner.setProperty(QueryElasticsearchHttp.TYPE, "status");
                runner.assertNotValid();
                runner.setProperty(QueryElasticsearchHttp.QUERY,
                        "source:Twitter AND identifier:\"${identifier}\"");
                runner.assertValid();
                runner.setProperty(QueryElasticsearchHttp.PAGE_SIZE, "2");
                runner.assertValid();
                runner.setProperty(QueryElasticsearchHttp.ROUTING_QUERY_INFO_STRATEGY, QueryElasticsearchHttp.QueryInfoRouteStrategy.ALWAYS.name());
                runner.assertValid();

                runner.setIncomingConnection(false);
                runAndVerify(3,3,2,true);
        }

        @Test
        public void testQueryElasticsearchOnTrigger_Hits_AppendAsAttributes() throws IOException {
                runner = TestRunners.newTestRunner(new QueryElasticsearchHttpTestProcessor(false));
                runner.setValidateExpressionUsage(true);
                runner.setProperty(AbstractElasticsearchHttpProcessor.ES_URL, "http://127.0.0.1:9200");

                runner.setProperty(QueryElasticsearchHttp.INDEX, "doc");
                runner.assertNotValid();
                runner.setProperty(QueryElasticsearchHttp.TYPE, "status");
                runner.assertNotValid();
                runner.setProperty(QueryElasticsearchHttp.QUERY,
                        "source:Twitter AND identifier:\"${identifier}\"");
                runner.assertValid();
                runner.setProperty(QueryElasticsearchHttp.PAGE_SIZE, "2");
                runner.assertValid();
                runner.setProperty(QueryElasticsearchHttp.ROUTING_QUERY_INFO_STRATEGY, QueryElasticsearchHttp.QueryInfoRouteStrategy.APPEND_AS_ATTRIBUTES.name());
                runner.assertValid();

                runner.setIncomingConnection(true);
                runAndVerify(1,0,0,false, false);
        }

        @Test
        public void testQueryElasticsearchOnTrigger_Hits_AppendAsAttributes_noHits() throws IOException {
                runner = TestRunners.newTestRunner(new QueryElasticsearchHttpTestProcessor(true));
                runner.setValidateExpressionUsage(true);
                runner.setProperty(AbstractElasticsearchHttpProcessor.ES_URL, "http://127.0.0.1:9200");

                runner.setProperty(QueryElasticsearchHttp.INDEX, "doc");
                runner.assertNotValid();
                runner.setProperty(QueryElasticsearchHttp.TYPE, "status");
                runner.assertNotValid();
                runner.setProperty(QueryElasticsearchHttp.QUERY,
                        "source:Twitter AND identifier:\"${identifier}\"");
                runner.assertValid();
                runner.setProperty(QueryElasticsearchHttp.PAGE_SIZE, "2");
                runner.assertValid();
                runner.setProperty(QueryElasticsearchHttp.ROUTING_QUERY_INFO_STRATEGY, QueryElasticsearchHttp.QueryInfoRouteStrategy.APPEND_AS_ATTRIBUTES.name());
                runner.assertValid();

                runner.setIncomingConnection(false);
                runAndVerify(3,3,2,true, false);
        }

        private void runAndVerify(int expectedResults,int expectedQueryInfoResults,int expectedHits, boolean targetIsContent) {
            runAndVerify(expectedResults, expectedQueryInfoResults, expectedHits, targetIsContent, true);
        }

        private void runAndVerify(int expectedResults,int expectedQueryInfoResults,int expectedHits, boolean targetIsContent,
                boolean expectHitCountOnQueryInfo) {
                runner.enqueue("blah".getBytes(), new HashMap<String, String>() {
                        {
                                put("identifier", "28039652140");
                        }
                });

                // Running once should page through the no hit doc
                runner.run(1, true, true);

                if (expectHitCountOnQueryInfo) {
                    runner.assertTransferCount(QueryElasticsearchHttp.REL_QUERY_INFO, expectedQueryInfoResults);
                    if (expectedQueryInfoResults > 0) {
                        final MockFlowFile out = runner.getFlowFilesForRelationship(QueryElasticsearchHttp.REL_QUERY_INFO).get(0);
                        assertNotNull(out);
                        if (targetIsContent) {
                            if (expectHitCountOnQueryInfo) {
                                out.assertAttributeEquals("es.query.hitcount", String.valueOf(expectedHits));
                            }
                            assertTrue(out.getAttribute("es.query.url").startsWith("http://127.0.0.1:9200/doc/status/_search?q=source%3ATwitter%20AND%20identifier%3A%22%22&size=2"));
                        }
                    }
                }

                runner.assertTransferCount(QueryElasticsearchHttp.REL_SUCCESS, expectedResults);
                if (expectedResults > 0) {
                        final MockFlowFile out = runner.getFlowFilesForRelationship(QueryElasticsearchHttp.REL_SUCCESS).get(0);
                        assertNotNull(out);
                        if (!expectHitCountOnQueryInfo) {
                            out.assertAttributeEquals("es.query.hitcount", String.valueOf(expectedHits));
                        }
                        if (targetIsContent) {
                                out.assertAttributeEquals("filename", "abc-97b-ASVsZu_" + "vShwtGCJpGOObmuSqUJRUC3L_-SEND-S3");
                        }
                }
        }

        // By default, 3 files should go to Success
        private void runAndVerify(boolean targetIsContent) {
                runAndVerify(0,1,0, targetIsContent);
        }

        /**
         * A Test class that extends the processor in order to inject/mock behavior
         */
        private static class QueryElasticsearchHttpTestProcessor extends QueryElasticsearchHttp {
                Exception exceptionToThrow = null;
                OkHttpClient client;
                int goodStatusCode = 200;
                String goodStatusMessage = "OK";

                int badStatusCode;
                String badStatusMessage;
                int runNumber;

                boolean useHitPages;

                // query-page3 has no hits
                List<String> noHitPages = Arrays.asList(getDoc("query-page3.json"));
                List<String> hitPages = Arrays.asList(getDoc("query-page1.json"), getDoc("query-page2.json"),
                        getDoc("query-page3.json"));

                String expectedParam = null;

                public QueryElasticsearchHttpTestProcessor() {
                        this(false);
                }
                public QueryElasticsearchHttpTestProcessor(boolean useHitPages) {
                        this.useHitPages = useHitPages;
                }

                public void setExceptionToThrow(Exception exceptionToThrow) {
                        this.exceptionToThrow = exceptionToThrow;
                }

                /**
                 * Sets the status code and message for the 1st query
                 *
                 * @param code
                 *            The status code to return
                 * @param message
                 *            The status message
                 */
                void setStatus(int code, String message) {
                        this.setStatus(code, message, 1);
                }

                /**
                 * Sets an query parameter (name=value) expected to be at the end of the URL for the query operation
                 *
                 * @param param
                 *            The parameter to expect
                 */
                void setExpectedParam(String param) {
                        expectedParam = param;
                }

                /**
                 * Sets the status code and message for the runNumber-th query
                 *
                 * @param code
                 *            The status code to return
                 * @param message
                 *            The status message
                 * @param runNumber
                 *            The run number for which to set this status
                 */
                void setStatus(int code, String message, int runNumber) {
                        badStatusCode = code;
                        badStatusMessage = message;
                        this.runNumber = runNumber;
                }

                @Override
                protected void createElasticsearchClient(ProcessContext context) throws ProcessException {
                        client = mock(OkHttpClient.class);

                        OngoingStubbing<Call> stub = when(client.newCall(any(Request.class)));
                        List<String> pages;
                        if(useHitPages) {
                                pages = hitPages;
                        } else {
                                pages = noHitPages;
                        }

                        for (int i = 0; i < pages.size(); i++) {
                                String page = pages.get(i);
                                if (runNumber == i + 1) {
                                        stub = mockReturnDocument(stub, page, badStatusCode, badStatusMessage);
                                } else {
                                        stub = mockReturnDocument(stub, page, goodStatusCode, goodStatusMessage);
                                }
                        }
                }

                private OngoingStubbing<Call> mockReturnDocument(OngoingStubbing<Call> stub,
                        final String document, int statusCode, String statusMessage) {
                        return stub.thenAnswer((Answer<Call>) invocationOnMock -> {
                                Request realRequest = (Request) invocationOnMock.getArguments()[0];
                                assertTrue((expectedParam == null) || (realRequest.url().toString().endsWith(expectedParam)));
                                Response mockResponse = new Response.Builder()
                                        .request(realRequest)
                                        .protocol(Protocol.HTTP_1_1)
                                        .code(statusCode)
                                        .message(statusMessage)
                                        .body(ResponseBody.create(MediaType.parse("application/json"), document))
                                        .build();
                                final Call call = mock(Call.class);
                                if (exceptionToThrow != null) {
                                        when(call.execute()).thenThrow(exceptionToThrow);
                                } else {
                                        when(call.execute()).thenReturn(mockResponse);
                                }
                                return call;
                        });
                }

                protected OkHttpClient getClient() {
                        return client;
                }
        }

        private static String getDoc(String filename) {
                try {
                        return IOUtils.toString(QueryElasticsearchHttp.class.getClassLoader().getResourceAsStream(filename), StandardCharsets.UTF_8);
                } catch (IOException e) {
                        System.out.println("Error reading document " + filename);
                        return "";
                }
        }
}


text:
using Toggl.Storage.Models;

namespace Toggl.Core.Models.Interfaces
{
    public interface IThreadSafeModel : IDatabaseModel
    {
    }
}


text:
package cmwell.tools.data.utils.akka

import akka.http.scaladsl.model.HttpHeader

object HeaderOps {
  val CMWELL_HOSTNAME = "X-CMWELL-Hostname"
  val CMWELL_POSITION = "X-CM-WELL-POSITION"
  val CMWELL_N = "X-CM-WELL-N"
  val CMWELL_RT = "X-CMWELL-RT"
  val CMWELL_TO = "X-CM-WELL-TO"
  val CMWELL_N_LEFT = "X-CM-WELL-N-LEFT"

  def getHeader(name: String)(headers: Seq[HttpHeader]) = headers.find(_.name == name)

  def getHeaderValue(header: Option[HttpHeader]) = header match {
    case None                       => "NA"
    case Some(HttpHeader(_, value)) => value
  }

  val getNLeft = getHeader(CMWELL_N_LEFT) _
  val getHostname = getHeader(CMWELL_HOSTNAME) _
  val getPosition = getHeader(CMWELL_POSITION) _
  val getNumInfotons = getHeader(CMWELL_N) _
  val getResponseTime = getHeader(CMWELL_RT) _
  val getTo = getHeader(CMWELL_TO) _

  val getHostnameValue = getHostname.andThen(getHeaderValue)
  val getPositionValue = getPosition.andThen(getHeaderValue)
  val getNumInfotonsValue = getNumInfotons.andThen(getHeaderValue)
  val getResponseTimeValue = getResponseTime.andThen(getHeaderValue)
}


text:
class ContentNews < ApplicationRecord
  belongs_to :content
  belongs_to :news_article
  belongs_to :activity, foreign_key: :content_id, class_name: 'Activity'
  belongs_to :publication, foreign_key: :content_id, class_name: 'Publication'
end


text:
import { expect }               from 'chai';
import { assert, spy, stub }    from 'sinon';
import { debug }                from '../../src/utils/debug';

import { MiniDroneController } from '../../src/controllers/MiniDroneController';

let miniDroneController = null,
    fakePromise,
    startScanServiceStub,
    stopScanServiceStub,
    discDeviceServiceStub,
    conServiceStub,
    upProxServiceStub,
    discServicesStub,
    discCharServiceStub,
    identifyCharServiceStub,
    sendDroneCmdServiceStub,
    disconnectServiceStub;

before(() => {
    miniDroneController = new MiniDroneController();
    fakePromise = {
        then: function(fn) {
            fn();
            return {
                catch: function() {}
            }
        },
        // catch: function() { }
    };

    startScanServiceStub = stub(miniDroneController.droneService, 'startScanning').callsFake(() => fakePromise);
    stopScanServiceStub = stub(miniDroneController.droneService, 'stopScanning').callsFake(() => fakePromise);
    discDeviceServiceStub = stub(miniDroneController.droneService, 'discoverDevice').callsFake(() => fakePromise);
    conServiceStub = stub(miniDroneController.droneService, 'connect').callsFake(() => fakePromise);
    upProxServiceStub = stub(miniDroneController.droneService, 'updateProximity').callsFake(() => fakePromise);
    discServicesStub = stub(miniDroneController.droneService, 'discoverServices').callsFake(() => fakePromise);
    discCharServiceStub = stub(miniDroneController.droneService, 'discoverCharacteristics').callsFake(() => fakePromise);
    identifyCharServiceStub = stub(miniDroneController.droneService, 'identifyCharacteristics').callsFake(() => fakePromise);
    sendDroneCmdServiceStub = stub(miniDroneController.droneService, 'sendNavCommand').callsFake(() => fakePromise);
    disconnectServiceStub = stub(miniDroneController.droneService, 'disconnect').callsFake(() => fakePromise);

    miniDroneController.droneService.cmdObservable = {
        distinctUntilChanged: function() {
            return {
                subscribe: function() {}
            }
        }
    };

    miniDroneController.droneService.ftpObservable = {
        filter: function() {
            return {
                subscribe: function() {}
            }
        }
    };
});

describe("MiniDroneController", () => {

    it("test if exists", () => {
        expect(miniDroneController).to.exist;
    });

    it("test if all the properties are initialized", () => {
        expect(miniDroneController.droneService).to.exist;
        expect(miniDroneController.droneCmds).to.exist;
        expect(miniDroneController.commonCmds).to.exist;
        expect(miniDroneController.steps).to.exist;
        expect(miniDroneController.cmdSubscription).to.be.null;
        expect(miniDroneController.ftpSubscription).to.be.null;
    });

    describe("test method: connect", () => {
        it("test if exists", () => {
            expect(miniDroneController.connect).to.exist;
        });

        it("test if method is called", (done) => {
            let conSpy = spy(miniDroneController, 'connect'),
                listenerSpy = spy(miniDroneController, 'addListeners');

            miniDroneController.connect('RS_').then(value => {
                assert.called(conSpy);
                assert.called(listenerSpy);
                assert.called(startScanServiceStub);
                assert.called(stopScanServiceStub);
                assert.called(discDeviceServiceStub);
                assert.called(conServiceStub);
                assert.called(upProxServiceStub);
                assert.called(discServicesStub);
                assert.called(discCharServiceStub);
                assert.called(identifyCharServiceStub);
                expect(value).to.exist;
                expect(value).to.be.equal('success');
                done();
            }).catch(e => {
                assert.fail(e);
                done();
            });

            miniDroneController.connect.restore();
            miniDroneController.addListeners.restore();
        });

        it("test if method fails", (done) => {
            let conSpy = spy(miniDroneController, 'connect'),
                listenerSpy = stub(miniDroneController, 'addListeners').callsFake(() => {
                    throw new Error('failed');
                });

            miniDroneController.connect('RS_').then(value => {
                done();
            }).catch(e => {
                assert.calledOnce(conSpy);
                assert.calledOnce(listenerSpy);
                assert.called(startScanServiceStub);
                assert.called(stopScanServiceStub);
                assert.called(discDeviceServiceStub);
                assert.called(conServiceStub);
                assert.called(upProxServiceStub);
                assert.called(discServicesStub);
                assert.called(discCharServiceStub);
                assert.called(identifyCharServiceStub);
                expect(e).to.exist;
                done();
            });

            miniDroneController.connect.restore();
            miniDroneController.addListeners.restore();
        });
    });

    describe("test method: checkAllStates", () => {
        it("test if exists", () => {
            expect(miniDroneController.checkAllStates).to.exist;
        });

        it("test if method is called", (done) => {
            let statesSpy = spy(miniDroneController, 'checkAllStates'),
                genCmdSpy = spy(miniDroneController, 'genCommonCmds');

            miniDroneController.checkAllStates().then(value => {
                assert.called(statesSpy);
                assert.called(genCmdSpy);
                assert.called(sendDroneCmdServiceStub);
                expect(value).to.exist;
                expect(value).to.be.equal('success');
                done();
            }).catch(e => {
                assert.fail(e);
                done();
            });

            miniDroneController.checkAllStates.restore();
            miniDroneController.genCommonCmds.restore();
        });

        it("test if method fails", (done) => {
            let statesSpy = spy(miniDroneController, 'checkAllStates'),
                genCmdStub = stub(miniDroneController, 'genCommonCmds').callsFake(() => {
                    throw new Error('failed');
                });

            miniDroneController.checkAllStates().then(value => {

                done();
            }).catch(e => {
                assert.called(statesSpy);
                assert.called(genCmdStub);
                expect(e).to.exist;
                done();
            });

            miniDroneController.checkAllStates.restore();
            miniDroneController.genCommonCmds.restore();
        });
    });

    describe("test method: disconnect", () => {
        it("test if exists", () => {
            expect(miniDroneController.disconnect).to.exist;
        });

        it("test if method is called", (done) => {
            let disconSpy = spy(miniDroneController, 'disconnect');

            miniDroneController.cmdSubscription = {
                unsubscribe: function () {
                    return true;
                }
            };

            miniDroneController.ftpSubscription = {
                unsubscribe: function () {
                    return true;
                }
            };

            miniDroneController.disconnect().then(value => {
                assert.called(disconSpy);
                assert.called(disconnectServiceStub);
                expect(value).to.exist;
                expect(value).to.be.equal('success');
                done();
            }).catch(e => {
                assert.fail(e);
                done();
            });

            miniDroneController.disconnect.restore();
        });

        it("test if method fails", (done) => {
            let disconSpy = spy(miniDroneController, 'disconnect');
            miniDroneController.cmdSubscription = {
                unsubscribe: function () {
                    throw new Error('failed');
                }
            };

            miniDroneController.disconnect().then(value => {
                done();
            }).catch(e => {
                assert.called(disconSpy);
                assert.called(disconnectServiceStub);
                expect(e).to.exist;
                done();
            });

            miniDroneController.disconnect.restore();
        });
    });

    describe("test method: addListeners", () => {
        it("test if exists", () => {
            expect(miniDroneController.addListeners).to.exist;
        });

        it("test if method is called", (done) => {
            let listenerSpy = spy(miniDroneController, 'addListeners'),
                distinctSpy = spy(miniDroneController.droneService.cmdObservable, 'distinctUntilChanged');

            miniDroneController.addListeners()
            assert.called(listenerSpy);
            assert.called(distinctSpy);
            done();

            miniDroneController.addListeners.restore();
            miniDroneController.droneService.cmdObservable.distinctUntilChanged.restore();
        });

        it("test if method fails", (done) => {
            let listenerSpy = spy(miniDroneController, 'addListeners'),
                distinctStub = stub(miniDroneController.droneService.cmdObservable, 'distinctUntilChanged')
                    .callsFake(() => {
                        throw new Error('failed');
                    });

            try  {
                miniDroneController.addListeners();
            } catch (e) {
                assert.called(listenerSpy);
                assert.called(distinctStub);
                expect(e).to.exist;
                done();
            }

            miniDroneController.addListeners.restore();
            miniDroneController.droneService.cmdObservable.distinctUntilChanged.restore();
        });
    });

    describe("test method: parseData", () => {
        it("test if exists", () => {
            expect(miniDroneController.parseData).to.exist;
        });

        it("test if method is called with minidrone command", (done) => {
            let methodSpy = spy(miniDroneController, 'parseData'),
                data = [2, 1, 2, 3, 1, 0, 0];

            let navInfo = miniDroneController.parseData(data);
            assert.called(methodSpy);
            expect(navInfo).to.exist;
            expect(navInfo.name).to.be.equal('flyingStateChanged');
            expect(navInfo.args).to.exist;
            expect(navInfo.args.length).to.equal(1);
            expect(navInfo.args[0].name).to.equal('state');
            expect(navInfo.args[0].value).to.equal('landed');
            done();

            miniDroneController.parseData.restore();
        });

        it("test if method is called with common command", (done) => {
            let methodSpy = spy(miniDroneController, 'parseData'),
                data = [4, 1, 0, 5, 1, 0, 95];

            let navInfo = miniDroneController.parseData(data);
            assert.called(methodSpy);
            expect(navInfo).to.exist;
            expect(navInfo.name).to.be.equal('batteryStateChanged');
            expect(navInfo.args).to.exist;
            expect(navInfo.args.length).to.equal(1);
            expect(navInfo.args[0].name).to.equal('percent');
            expect(navInfo.args[0].value).to.equal(95);
            done();

            miniDroneController.parseData.restore();
        });

        it("test if method is called with common command", (done) => {
            let methodSpy = spy(miniDroneController, 'parseData'),
                data = [4, 1, 0, 30, 0, 0, 0];

            let navInfo = miniDroneController.parseData(data);
            assert.called(methodSpy);
            expect(navInfo).to.exist;
            expect(navInfo.name).to.be.equal('runIdChanged');
            expect(navInfo.args).to.exist;
            expect(navInfo.args.length).to.equal(1);
            expect(navInfo.args[0].name).to.equal('runId');
            expect(navInfo.args[0].value).to.equal('\u0000');
            done();

            miniDroneController.parseData.restore();
        });

        it("test if method is called with no data", (done) => {
            let methodSpy = spy(miniDroneController, 'parseData'),
                data = null;

            let navInfo = miniDroneController.parseData(data);
            assert.called(methodSpy);
            expect(navInfo).to.not.exist;
            done();

            miniDroneController.parseData.restore();
        });

        it("test if method is called with data.length equal to 0", (done) => {
            let methodSpy = spy(miniDroneController, 'parseData'),
                data = [];

            let navInfo = miniDroneController.parseData(data);
            assert.called(methodSpy);
            expect(navInfo).to.not.exist;
            done();

            miniDroneController.parseData.restore();
        });
    });

    describe("test method: getValuesByType", () => {
        it("test if exists", () => {
            expect(miniDroneController.getValuesByType).to.exist;
        });

        it("test if method is called with u8 value", (done) => {
            let methodSpy = spy(miniDroneController, 'getValuesByType'),
                buffer = Buffer.from([95]),
                arg = {
                    name: 'percent',
                    type: 'u8'
                };

            let args = miniDroneController.getValuesByType(buffer, 0, arg);
            assert.called(methodSpy);
            expect(args).to.exist;
            expect(args.length).to.equal(1);
            expect(args[0].name).to.equal('percent');
            expect(args[0].value).to.equal(95);
            done();

            miniDroneController.getValuesByType.restore();
        });

        it("test if method is called with u16 value", (done) => {
            let methodSpy = spy(miniDroneController, 'getValuesByType'),
                buffer = Buffer.alloc(2),
                arg = {
                    name: 'percent',
                    type: 'u16'
                };

            buffer.writeUInt16LE(95, 0);

            let args = miniDroneController.getValuesByType(buffer, 0, arg);
            assert.called(methodSpy);
            expect(args).to.exist;
            expect(args.length).to.equal(1);
            expect(args[0].name).to.equal('percent');
            expect(args[0].value).to.equal(95);
            done();

            miniDroneController.getValuesByType.restore();
        });

        it("test if method is called with u32 value", (done) => {
            let methodSpy = spy(miniDroneController, 'getValuesByType'),
                buffer = Buffer.alloc(4),
                arg = {
                    name: 'percent',
                    type: 'u32'
                };

            buffer.writeUInt32LE(95, 0);

            let args = miniDroneController.getValuesByType(buffer, 0, arg);
            assert.called(methodSpy);
            expect(args).to.exist;
            expect(args.length).to.equal(1);
            expect(args[0].name).to.equal('percent');
            expect(args[0].value).to.equal(95);
            done();

            miniDroneController.getValuesByType.restore();
        });

        it("test if method is called with i8 value", (done) => {
            let methodSpy = spy(miniDroneController, 'getValuesByType'),
                buffer = Buffer.alloc(1),
                arg = {
                    name: 'percent',
                    type: 'i8'
                };

            buffer.writeInt8(95, 0);

            let args = miniDroneController.getValuesByType(buffer, 0, arg);
            assert.called(methodSpy);
            expect(args).to.exist;
            expect(args.length).to.equal(1);
            expect(args[0].name).to.equal('percent');
            expect(args[0].value).to.equal(95);
            done();

            miniDroneController.getValuesByType.restore();
        });

        it("test if method is called with i16 value", (done) => {
            let methodSpy = spy(miniDroneController, 'getValuesByType'),
                buffer = Buffer.alloc(2),
                arg = {
                    name: 'percent',
                    type: 'i16'
                };

            buffer.writeInt16LE(95, 0);

            let args = miniDroneController.getValuesByType(buffer, 0, arg);
            assert.called(methodSpy);
            expect(args).to.exist;
            expect(args.length).to.equal(1);
            expect(args[0].name).to.equal('percent');
            expect(args[0].value).to.equal(95);
            done();

            miniDroneController.getValuesByType.restore();
        });

        it("test if method is called with i32 value", (done) => {
            let methodSpy = spy(miniDroneController, 'getValuesByType'),
                buffer = Buffer.alloc(4),
                arg = {
                    name: 'percent',
                    type: 'i32'
                };

            buffer.writeInt16LE(95, 0);

            let args = miniDroneController.getValuesByType(buffer, 0, arg);
            assert.called(methodSpy);
            expect(args).to.exist;
            expect(args.length).to.equal(1);
            expect(args[0].name).to.equal('percent');
            expect(args[0].value).to.equal(95);
            done();

            miniDroneController.getValuesByType.restore();
        });

        it("test if method is called with float value", (done) => {
            let methodSpy = spy(miniDroneController, 'getValuesByType'),
                buffer = Buffer.alloc(4),
                arg = {
                    name: 'percent',
                    type: 'float'
                };

            buffer.writeFloatLE(95, 0);

            let args = miniDroneController.getValuesByType(buffer, 0, arg);
            assert.called(methodSpy);
            expect(args).to.exist;
            expect(args.length).to.equal(1);
            expect(args[0].name).to.equal('percent');
            expect(args[0].value).to.equal(95);
            done();

            miniDroneController.getValuesByType.restore();
        });

        it("test if method is called with enum value", (done) => {
            let methodSpy = spy(miniDroneController, 'getValuesByType'),
                buffer = Buffer.alloc(1),
                arg = {
                    name: 'sensorName',
                    type: 'enum',
                    values: [
                        {
                            "name": "IMU",
                            "value": 1
                        },
                        {
                            "name": "barometer",
                            "value": 2
                        },
                        {
                            "name": "ultrasound",
                            "value": 3
                        }
                    ]
                };

            buffer.writeUInt8(3, 0);

            let args = miniDroneController.getValuesByType(buffer, 0, arg);
            assert.called(methodSpy);
            expect(args).to.exist;
            expect(args.length).to.equal(1);
            expect(args[0].name).to.equal('sensorName');
            expect(args[0].value).to.equal('ultrasound');
            done();

            miniDroneController.getValuesByType.restore();
        });

        it("test if method is called with string value", (done) => {
            let methodSpy = spy(miniDroneController, 'getValuesByType'),
                str = 'internal',
                buffer = Buffer.alloc(str.length),
                arg = {
                    name: 'mass_storage_name',
                    type: 'string'
                };

            buffer.write(str, 0, str.length, 'utf8');

            let args = miniDroneController.getValuesByType(buffer, 0, arg);
            assert.called(methodSpy);
            expect(args).to.exist;
            expect(args.length).to.equal(1);
            expect(args[0].name).to.equal('mass_storage_name');
            expect(args[0].value).to.equal('internal');
            done();

            miniDroneController.getValuesByType.restore();
        });

        it("test if method is called with no args", (done) => {
            let methodSpy = spy(miniDroneController, 'getValuesByType'),
                buffer = Buffer.from([]),
                arg = null;

            let args = miniDroneController.getValuesByType(buffer, 0, arg);
            assert.called(methodSpy);
            expect(args).to.exist;
            expect(args.length).to.equal(0);
            done();

            miniDroneController.getValuesByType.restore();
        });
    });

    describe("test method: genCommonCmds", () => {
        it("test if exists", () => {
            expect(miniDroneController.genCommonCmds).to.exist;
        });

        it("test if method is called", (done) => {
            let cmdSpy = spy(miniDroneController, 'genCommonCmds');

            let buffer = miniDroneController.genCommonCmds('allStates');
            assert.called(cmdSpy);
            expect(buffer).to.exist;
            done();

            miniDroneController.genCommonCmds.restore();
        });

        it("test all states command", (done) => {
            let cmdSpy = spy(miniDroneController, 'genCommonCmds');

            let buffer = miniDroneController.genCommonCmds('allStates');
            let str = Array.prototype.slice.call(buffer, 0).join('+');

            assert.called(cmdSpy);
            expect(buffer).to.exist;
            expect(str).to.exist;
            expect(str).to.be.equal('2+3+0+4+0+0');
            done();

            miniDroneController.genCommonCmds.restore();
        });
    });

    describe("test method: genMiniDroneCmds", () => {
        it("test if exists", () => {
            expect(miniDroneController.genMiniDroneCmds).to.exist;
        });

        it("test if method is called", (done) => {
            let cmdSpy = spy(miniDroneController, 'genMiniDroneCmds');

            let buffer = miniDroneController.genMiniDroneCmds('piloting', 'takeOff');
            assert.called(cmdSpy);
            expect(buffer).to.exist;
            done();

            miniDroneController.genMiniDroneCmds.restore();
        });

        it("test flatTrim command", (done) => {
            let cmdSpy = spy(miniDroneController, 'genMiniDroneCmds');

            let buffer = miniDroneController.genMiniDroneCmds('piloting', 'flatTrim');
            let str = Array.prototype.slice.call(buffer, 0).join('+');

            assert.called(cmdSpy);
            expect(buffer).to.exist;
            expect(str).to.exist;
            expect(str).to.be.equal('2+5+2+0+0+0');
            done();

            miniDroneController.genMiniDroneCmds.restore();
        });

        it("test takeOff command", (done) => {
            let cmdSpy = spy(miniDroneController, 'genMiniDroneCmds');

            let buffer = miniDroneController.genMiniDroneCmds('piloting', 'takeOff');
            let str = Array.prototype.slice.call(buffer, 0).join('+');

            assert.called(cmdSpy);
            expect(buffer).to.exist;
            expect(str).to.exist;
            expect(str).to.be.equal('2+6+2+0+1+0');
            done();

            miniDroneController.genMiniDroneCmds.restore();
        });

        it("test landing command", (done) => {
            let cmdSpy = spy(miniDroneController, 'genMiniDroneCmds');

            let buffer = miniDroneController.genMiniDroneCmds('piloting', 'landing');
            let str = Array.prototype.slice.call(buffer, 0).join('+');

            assert.called(cmdSpy);
            expect(buffer).to.exist;
            expect(str).to.exist;
            expect(str).to.be.equal('2+7+2+0+3+0');
            done();

            miniDroneController.genMiniDroneCmds.restore();
        });

        it("test emergency command", (done) => {
            let cmdSpy = spy(miniDroneController, 'genMiniDroneCmds');

            let buffer = miniDroneController.genMiniDroneCmds('piloting', 'emergency');
            let str = Array.prototype.slice.call(buffer, 0).join('+');

            assert.called(cmdSpy);
            expect(buffer).to.exist;
            expect(str).to.exist;
            expect(str).to.be.equal('2+8+2+0+4+0');
            done();

            miniDroneController.genMiniDroneCmds.restore();
        });

        it("test maneuver - roll command", (done) => {
            let cmdSpy = spy(miniDroneController, 'genMiniDroneCmds'),
                args = [0, 10, 0, 0, 0, 1000];

            let buffer = miniDroneController.genMiniDroneCmds('piloting', 'maneuver', args, args.length + 3);
            let str = Array.prototype.slice.call(buffer, 0).join('+');

            assert.called(cmdSpy);
            expect(buffer).to.exist;
            expect(str).to.exist;
            expect(str).to.be.equal('2+9+2+0+2+0+0+10+0+0+0+232+3+0+0');
            done();

            miniDroneController.genMiniDroneCmds.restore();
        });

        it("test maneuver - pitch command", (done) => {
            let cmdSpy = spy(miniDroneController, 'genMiniDroneCmds'),
                args = [0, 0, 10, 0, 0, 1000];

            let buffer = miniDroneController.genMiniDroneCmds('piloting', 'maneuver', args, args.length + 3);
            let str = Array.prototype.slice.call(buffer, 0).join('+');

            assert.called(cmdSpy);
            expect(buffer).to.exist;
            expect(str).to.exist;
            expect(str).to.be.equal('2+10+2+0+2+0+0+0+10+0+0+232+3+0+0');
            done();

            miniDroneController.genMiniDroneCmds.restore();
        });

        it("test maneuver - yaw command", (done) => {
            let cmdSpy = spy(miniDroneController, 'genMiniDroneCmds'),
                args = [0, 0, 0, -10, 0, 1000];

            let buffer = miniDroneController.genMiniDroneCmds('piloting', 'maneuver', args, args.length + 3);
            let str = Array.prototype.slice.call(buffer, 0).join('+');

            assert.called(cmdSpy);
            expect(buffer).to.exist;
            expect(str).to.exist;
            expect(str).to.be.equal('2+11+2+0+2+0+0+0+0+246+0+232+3+0+0');
            done();

            miniDroneController.genMiniDroneCmds.restore();
        });

        it("test maneuver - gaz command", (done) => {
            let cmdSpy = spy(miniDroneController, 'genMiniDroneCmds'),
                args = [0, 0, 0, 0, -100, 1000];

            let buffer = miniDroneController.genMiniDroneCmds('piloting', 'maneuver', args, args.length + 3);
            let str = Array.prototype.slice.call(buffer, 0).join('+');

            assert.called(cmdSpy);
            expect(buffer).to.exist;
            expect(str).to.exist;
            expect(str).to.be.equal('2+12+2+0+2+0+0+0+0+0+156+232+3+0+0');
            done();

            miniDroneController.genMiniDroneCmds.restore();
        });

        it("test animations - flip front command", (done) => {
            let cmdSpy = spy(miniDroneController, 'genMiniDroneCmds'),
                args = [0];

            let buffer = miniDroneController.genMiniDroneCmds('animations', 'flip', args, args.length);
            let str = Array.prototype.slice.call(buffer, 0).join('+');

            assert.called(cmdSpy);
            expect(buffer).to.exist;
            expect(str).to.exist;
            expect(str).to.be.equal('2+13+2+4+0+0+'+ args.join());
            done();

            miniDroneController.genMiniDroneCmds.restore();
        });

        it("test animations - flip back command", (done) => {
            let cmdSpy = spy(miniDroneController, 'genMiniDroneCmds'),
                args = [1];

            let buffer = miniDroneController.genMiniDroneCmds('animations', 'flip', args, args.length);
            let str = Array.prototype.slice.call(buffer, 0).join('+');

            assert.called(cmdSpy);
            expect(buffer).to.exist;
            expect(str).to.exist;
            expect(str).to.be.equal('2+14+2+4+0+0+'+ args.join());
            done();

            miniDroneController.genMiniDroneCmds.restore();
        });

        it("test animations - flip right command", (done) => {
            let cmdSpy = spy(miniDroneController, 'genMiniDroneCmds'),
                args = [2];

            let buffer = miniDroneController.genMiniDroneCmds('animations', 'flip', args, args.length);
            let str = Array.prototype.slice.call(buffer, 0).join('+');

            assert.called(cmdSpy);
            expect(buffer).to.exist;
            expect(str).to.exist;
            expect(str).to.be.equal('2+15+2+4+0+0+'+ args.join());
            done();

            miniDroneController.genMiniDroneCmds.restore();
        });

        it("test animations - flip left command", (done) => {
            let cmdSpy = spy(miniDroneController, 'genMiniDroneCmds'),
                args = [3];

            let buffer = miniDroneController.genMiniDroneCmds('animations', 'flip', args, args.length);
            let str = Array.prototype.slice.call(buffer, 0).join('+');

            assert.called(cmdSpy);
            expect(buffer).to.exist;
            expect(str).to.exist;
            expect(str).to.be.equal('2+16+2+4+0+0+'+ args.join());
            done();

            miniDroneController.genMiniDroneCmds.restore();
        });

        it("test take picture command", (done) => {
            let cmdSpy = spy(miniDroneController, 'genMiniDroneCmds'),
                args = [0];

            let buffer = miniDroneController.genMiniDroneCmds('mediaRecord', 'picture', args, args.length);
            let str = Array.prototype.slice.call(buffer, 0).join('+');

            assert.called(cmdSpy);
            expect(buffer).to.exist;
            expect(str).to.exist;
            expect(str).to.be.equal('2+17+2+6+0+0+'+ args.join());
            done();

            miniDroneController.genMiniDroneCmds.restore();
        });
    });

    describe("test method: sendPilotingCommand", () => {
        it("test if exists", () => {
            expect(miniDroneController.sendPilotingCommand).to.exist;
        });

        it("test if method is called", (done) => {
            let sendCmdSpy = spy(miniDroneController, 'sendPilotingCommand'),
                genCmdSpy = spy(miniDroneController, 'genMiniDroneCmds');

            miniDroneController.sendPilotingCommand('piloting', 'takeOff').then(value => {
                assert.called(sendCmdSpy);
                assert.called(genCmdSpy);
                assert.called(sendDroneCmdServiceStub);
                expect(value).to.exist;
                expect(value).to.be.equal('success');
                done();
            }).catch(e => {
                assert.fail(e);
                done();
            });

            miniDroneController.sendPilotingCommand.restore();
            miniDroneController.genMiniDroneCmds.restore();
        });

        it("test if method fails", (done) => {
            let sendCmdSpy = spy(miniDroneController, 'sendPilotingCommand'),
                genCmdSpy = stub(miniDroneController, 'genMiniDroneCmds').callsFake(() => {
                    throw new Error('failed');
                });

            miniDroneController.sendPilotingCommand('piloting', 'takeOff').then(value => {
                done();
            }).catch(e => {
                assert.called(sendCmdSpy);
                assert.called(genCmdSpy);
                assert.called(sendDroneCmdServiceStub);
                expect(e).to.exist;
                done();
            });

            miniDroneController.sendPilotingCommand.restore();
            miniDroneController.genMiniDroneCmds.restore();
        });
    });
});

after(() => {
    miniDroneController.droneService.startScanning.restore();
    miniDroneController.droneService.stopScanning.restore();
    miniDroneController.droneService.discoverDevice.restore();
    miniDroneController.droneService.connect.restore();
    miniDroneController.droneService.updateProximity.restore();
    miniDroneController.droneService.discoverServices.restore();
    miniDroneController.droneService.discoverCharacteristics.restore();
    miniDroneController.droneService.identifyCharacteristics.restore();
    miniDroneController.droneService.sendNavCommand.restore();
    miniDroneController.droneService.disconnect.restore();

    miniDroneController = null;
    fakePromise = null;
});


text:
require "class2"
Class2.autoload


text:
require File.expand_path('../application', __FILE__)

# Initialize the Rails application.
Umweltpaedagogik::Application.initialize!

ActionMailer::Base.smtp_settings = {
  :user_name => ENV["SENDGRID_USERNAME"],
  :password => ENV["SENDGRID_PASSWORD"],
  :domain => ENV["SENDGRID_DOMAIN"],
  :address => ENV["SENDGRID_ADDRESS"],
  :port => 587,
  :authentication => :plain,
  :enable_starttls_auto => true
}


text:
"""Test for auth methods supported by MariaDB 10.3+"""

import pymysql

# pymysql.connections.DEBUG = True
# pymysql._auth.DEBUG = True

host = "127.0.0.1"
port = 3306

def test_ed25519_no_password():
    con = pymysql.connect(user="nopass_ed25519", host=host, port=port, ssl=None)
    con.close()

def test_ed25519_password():  # nosec
    con = pymysql.connect(
        user="user_ed25519", password="pass_ed25519", host=host, port=port, ssl=None
    )
    con.close()

# default mariadb docker images aren't configured with SSL


text:
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using DevExpress.CodeRush.Core;
using System.Collections;

namespace DX_ShortcutEngine
{
  public partial class FrmAddToKeyMappingWindow : Form
  {
    const string STR_GetKeyMappingWindowGroups = "Get Key Mapping Window Groups";

    public FrmAddToKeyMappingWindow()
    {
      InitializeComponent();

      Action actGetKeyMappingWindowGroups = CodeRush.Actions[STR_GetKeyMappingWindowGroups];
      object aVarIn = null;
      object aVarOut = null;
      if(actGetKeyMappingWindowGroups != null)
      {
        actGetKeyMappingWindowGroups.DoExecute(ref aVarIn, ref aVarOut);
        string[] groups = aVarOut as string[];
        if (groups != null && groups.Length > 0)
          cmbParentGroups.Properties.Items.AddRange(groups);
      }
      LoadCommands();
      DialogResult = System.Windows.Forms.DialogResult.Cancel;
    }
    private void LoadCommands()
    {
      cmbCommands.Properties.Items.Clear();

      ActionCollection actions = CodeRush.Actions;

      ArrayList actionNames = new ArrayList(actions.Count);
      foreach (Action action in actions)
      {
        if (!action.VisibleToUsers)
          continue;

        actionNames.Add(action.ActionName);
      }

      actionNames.Sort();

      cmbCommands.Properties.Items.AddRange((string[])actionNames.ToArray(typeof(string)));
    }

    // public properties...
    public string Description
    {
      get
      {
        return tbxDescription.Text;
      }
      set
      {
        tbxDescription.Text = value;
      }
    }
    public string Command
    {
      get
      {
        return cmbCommands.Text;
      }
      set
      {
        cmbCommands.Text = value;
      }
    }
    public string Shortcut
    {
      get
      {
        return tbxShortcut.Text;
      }
      set
      {
        tbxShortcut.Text = value;
      }
    }
    public string ParentGroup
    {
      get
      {
        return cmbParentGroups.Text;
      }
      set
      {
        cmbParentGroups.Text = value;
      }
    }

    // event handlers...
    private void btnAdd_Click(object sender, EventArgs e)
    {
      DialogResult = System.Windows.Forms.DialogResult.OK;
      Close();
    }

    private void btnCancel_Click(object sender, EventArgs e)
    {
      Close();
    }
  }
}


text:
from notifications import Notification, SuccessNotification, ErrorNotification, InfoNotification, WarningNotification

__all__ = (
	'Notification',
	'SuccessNotification',
	'ErrorNotification',
	'InfoNotification',
	'WarningNotification',
)


text:
#include "CustomOpenGLWrapper.h"
#include <fstream>

/*
 *@Description: Creates a Vertex Array Object (VAO) that will be stored into the
    Graphics Processing Unit (GPU). The Vertex Array Object also contains an Vertex
    Buffer Object (VBO) which holds the world-Coordinates of where the vertex is and
    the UV-Coordinates on how texture is applied onto the vertex. The vertices are drawn
    based on how the indices selected
 *@*vertexID - used to store the pointer of the vertex array object (VAO)
 *@*bufferID - used to store the pointer of the vertex buffer object (VBO)
 *@*indicesID - used to store the pointer of the indices that tells
    the renderer how to draw the vertexes.
 *@width - The width of the Vertex Array Object
 *@height - The height of the Vertex Array Object
 */
void createVertex(GLuint *vertexID, GLuint *bufferID, GLuint *indicesID, int width, int height){
    // Create 4 vertices for the Vertex Array Object
    // The VertexData is initialized like this:
    // Format: { {x, y, z}, {s, t} }
    // Example: { {50, 30, 0.0f}, {0, 0} };
    VertexData v0 = { { width / 2, -height / 2, 0.0f }, { 0, 0 } };     // This vertex defines the Left-Top
    VertexData v1 = { { width / 2, height / 2, 0.0f }, { 0, 1 } };      // This vertex defines the Left-Bottom
    VertexData v2 = { { -width / 2, height / 2, 0.0f }, { 1, 1 } };     // This vertex defines the Right-Bottom
    VertexData v3 = { { -width / 2, -height / 2, 0.0f }, { 1, 0 } };    // This vertex defines the Right-Top

    // You may be confused to why the the Right side is -width and left side is width
    // It is because when the Camera views the front of the Vertex Array Object
    // The Camera's Left is the Vertex Array Object's Right

    VertexData vertices[] = { v0, v1, v2, v3 };

    // OpenGL draws vertices in counter-clockwise order,
    // So we create indices to create two triangles that form a square

    byte indices[] = {
        // Left-Bottom Triangle
        0, 1, 2,
        // Right-Top Triangle
        2, 3, 0
    };

    // Create a Vertex Array Object (VAO) in memory
    // And store the pointer to the memory into vertexID
    glGenVertexArrays(1, vertexID);

    // Next we select(Bind) the Vertex Array Object for editing
    glBindVertexArray(*vertexID);

    // Create a Vertex Buffer Object (VBO) in memory
    // And store the pointer to the memory into bufferID
    glGenBuffers(1, bufferID);

    // Next we select(Bind) the Vertex Buffer Object for editing
    glBindBuffer(GL_ARRAY_BUFFER, *bufferID);

    // Store the data into the buffer memory
    // We use GL_STREAM_DRAW to tell OpenGL that we will be
    // modifying the buffer once and it will be used a few times
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STREAM_DRAW);

    // Now that we have stored the data into the buffer memory
    // We will use the data in that memory to tell OpenGL
    // The position of the vertex, and how the textures are drawn

    // We point to the position data in the buffer
    // glVertexAttribPointer is defined as this:
    // glVertexAttribPointer( attributeIndex, size of the data, datatype, to Normalize or not, stride, pointer to data);
    // A vertex object array can contain 16 Vertex Buffer Objects
    // which is contained into an attributeList
    // We can modify the elements in the attributeList by
    // using the attributeIndex
    // Stride is the offset in bytes between each vertex
    // In this case the offset is the struct: VertexData
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexData),
        (GLvoid *)offsetof(VertexData, positionCoordinates));

    // Next we want to point to our texture coordinate data in the buffer
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(VertexData),
        (GLvoid *)offsetof(VertexData, textureCoordinates));

    // Deselect the Vertex Buffer Object from further editing
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    // Deselect the Vertex Array Object from further editing
    glBindVertexArray(0);

    // We create a Vertex Buffer Object for the indices
    glGenBuffers(1, indicesID);

    // Select the new Vertex Buffer Object
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *indicesID);

    // Next we store the indices data into memory
    // We use GL_STATIC_DRAW because we are going to modify it once
    // And use it to draw many times
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    // Deselect the Vertex Buffer Object
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

/*
 *@Description: Loads and buffers the Image into memory
 *@fileName - Filepath of the image
 *@textureUnit - The texture unit this is buffering for
 */
GLuint loadAndBufferImage(const char* fileName, int textureUnit){
    ILuint imageID;
    GLuint textureBufferID;

    // Create a Image in the buffer and store the pointer to imageID
    ilGenImages(1, &imageID);

    // Select(Bind) the image;
    ilBindImage(imageID);

    // Load the image from fileName
    // If the file fails to load then output an error
    if (!ilLoadImage(fileName)){
        std::string error;
        switch (ilGetError()){
        case IL_COULD_NOT_OPEN_FILE: error = "The file pointed to by FileName could not be opened. Either the file does not exist or is in use by another process. \n"; break;
        case IL_ILLEGAL_OPERATION: error = "There is currently no image bound. Use ilGenImages and ilBindImage before calling this function. \n"; break;
        case IL_INVALID_EXTENSION: error = "The file could not be loaded based on extension or header. \n"; break;
        case IL_INVALID_PARAM: error = "FileName was not valid. It was most likely NULL. \n"; break;
        }

        // Output the error string
        OutputDebugString(error.c_str());
    }

    // Convert the image to an image with RGBA values and the bytes are unsigned
    ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);

    // Get the image data in unsigned bytes
    ILubyte *data = ilGetData();

    // Check if there is actually data stored
    if (!data){
        ilBindImage(0);
        OutputDebugString("There is no data\n");
        return 0;
    }

    // Get the Image Properties
    int const imageWidth = ilGetInteger(IL_IMAGE_WIDTH);
    int const imageHeight = ilGetInteger(IL_IMAGE_HEIGHT);
    int const imageFormat = ilGetInteger(IL_IMAGE_FORMAT);

    // Create a Texture object in memory and store the pointer into textureBufferID
    glGenTextures(1, &textureBufferID);

    // Set the active texture to the texture unit
    glActiveTexture(textureUnit);

    // Select(bind) the texture object
    glBindTexture(GL_TEXTURE_2D, textureBufferID);

    // Set the pixel store parameters

    // Set to false to tell OpenGL that the byte ordering
    // for color components should not be reversed
    glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
    // Set to 0 to indicate that the pixels in the row are tightly packed
    // as in there is no offset required
    glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    // Sets the number of components / indices in each pixels as 0
    glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
    // Sets the offset to each pointer to 0
    glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
    // Specifiy the alignment requirement for each pixel row in memory
    // in this case we set it to 1 for byte alignment
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    // Upload the texture data to memory
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageWidth, imageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);

    // Generate Mipmaps for scaling
    glGenerateMipmap(GL_TEXTURE_2D);

    // Setup the Texture Coordinate System this is how we draw textures onto our vertex objects
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    // Setup what to do when the texture has to be scaled
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

    // Check if any errors has occured
    if (ilGetError()){
        ilBindImage(0);
        ilDeleteImages(1, &imageID);
        glBindTexture(GL_TEXTURE_2D, 0);
        glDeleteTextures(1, &textureBufferID);
        OutputDebugString("Some Error Occured with DevIL\n");
        return 0;
    }

    // Deselect the Image
    ilBindImage(0);

    // Delete the Image since we already stored the data into buffer
    ilDeleteImages(1, &imageID);

    return textureBufferID;
}


text:
package org.eclipse.gef.examples.shapes;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;

import org.eclipse.swt.widgets.Composite;

import org.eclipse.core.resources.IFile;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.dialogs.WizardNewFileCreationPage;
import org.eclipse.ui.ide.IDE;

import org.eclipse.gef.examples.shapes.model.ShapesDiagram;

/**
 * Create new new .shape-file. Those files can be used with the ShapesEditor
 * (see plugin.xml).
 *
 * @author Elias Volanakis
 */
public class ShapesCreationWizard extends Wizard implements INewWizard {

	private static int fileCount = 1;
	private CreationPage page1;

	/*
	 * (non-Javadoc)
	 *
	 * @see org.eclipse.jface.wizard.IWizard#addPages()
	 */
	public void addPages() {
		// add pages to this wizard
		addPage(page1);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench,
	 * org.eclipse.jface.viewers.IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		// create pages for this wizard
		page1 = new CreationPage(workbench, selection);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.eclipse.jface.wizard.IWizard#performFinish()
	 */
	public boolean performFinish() {
		return page1.finish();
	}

	/**
	 * This WizardPage can create an empty .shapes file for the ShapesEditor.
	 */
	private class CreationPage extends WizardNewFileCreationPage {
		private static final String DEFAULT_EXTENSION = ".shapes";
		private final IWorkbench workbench;

		/**
		 * Create a new wizard page instance.
		 *
		 * @param workbench
		 *            the current workbench
		 * @param selection
		 *            the current object selection
		 * @see ShapesCreationWizard#init(IWorkbench, IStructuredSelection)
		 */
		CreationPage(IWorkbench workbench, IStructuredSelection selection) {
			super("shapeCreationPage1", selection);
			this.workbench = workbench;
			setTitle("Create a new " + DEFAULT_EXTENSION + " file");
			setDescription("Create a new " + DEFAULT_EXTENSION + " file");
		}

		/*
		 * (non-Javadoc)
		 *
		 * @see
		 * org.eclipse.ui.dialogs.WizardNewFileCreationPage#createControl(org
		 * .eclipse.swt.widgets.Composite)
		 */
		public void createControl(Composite parent) {
			super.createControl(parent);
			setFileName("shapesExample" + fileCount + DEFAULT_EXTENSION);
			setPageComplete(validatePage());
		}

		/** Return a new ShapesDiagram instance. */
		private Object createDefaultContent() {
			return new ShapesDiagram();
		}

		/**
		 * This method will be invoked, when the "Finish" button is pressed.
		 *
		 * @see ShapesCreationWizard#performFinish()
		 */
		boolean finish() {
			// create a new file, result != null if successful
			IFile newFile = createNewFile();
			fileCount++;

			// open newly created file in the editor
			IWorkbenchPage page = workbench.getActiveWorkbenchWindow()
					.getActivePage();
			if (newFile != null && page != null) {
				try {
					IDE.openEditor(page, newFile, true);
				} catch (PartInitException e) {
					e.printStackTrace();
					return false;
				}
			}
			return true;
		}

		/*
		 * (non-Javadoc)
		 *
		 * @see
		 * org.eclipse.ui.dialogs.WizardNewFileCreationPage#getInitialContents()
		 */
		protected InputStream getInitialContents() {
			ByteArrayInputStream bais = null;
			try {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(baos);
				oos.writeObject(createDefaultContent()); // argument must be
															// Serializable
				oos.flush();
				oos.close();
				bais = new ByteArrayInputStream(baos.toByteArray());
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
			return bais;
		}

		/**
		 * Return true, if the file name entered in this page is valid.
		 */
		private boolean validateFilename() {
			if (getFileName() != null
					&& getFileName().endsWith(DEFAULT_EXTENSION)) {
				return true;
			}
			setErrorMessage("The 'file' name must end with "
					+ DEFAULT_EXTENSION);
			return false;
		}

		/*
		 * (non-Javadoc)
		 *
		 * @see org.eclipse.ui.dialogs.WizardNewFileCreationPage#validatePage()
		 */
		protected boolean validatePage() {
			return super.validatePage() && validateFilename();
		}
	}
}


text:
from __future__ import print_function
from BinPy import *
print ('Usage of IC 7424:\n')
ic = IC_7424()
print ('\nThe Pin configuration is:\n')
p = {1: 1, 2: 0, 4: 0, 5: 0, 7: 0, 9: 1, 10: 1, 12: 1, 13: 1, 14: 1}
print (p)
print ('\nPin initialization -using -- ic.setIC(p) --\n')
ic.setIC(p)
print ('\nPowering up the IC - using -- ic.setIC({14:1,7:0}) -- \n')
ic.setIC({14: 1, 7: 0})
print ('\nDraw the IC with the current configuration\n')
ic.drawIC()
print (
    '\nRun the IC with the current configuration using -- print ic.run() -- \n')
print (
    'Note that the ic.run() returns a dict of pin configuration similar to :')
print (ic.run())
print (
    '\nSeting the outputs to the current IC configuration using -- ic.setIC(ic.run()) --\n')
ic.setIC(ic.run())
print ('\nDraw the final configuration\n')
ic.drawIC()
print ('\nConnector Inputs\n')
print ('c = Connector(p[1])\np[1] = c\nic.setIC(p)\n')
c = Connector(p[1])
p[1] = c
ic.setIC(p)
print ('Run the IC\n')
print (ic.run())
print ('\nConnector Outputs')
print ('Set the output -- ic.setOutput(8, c)\n')
ic.setOutput(8, c)
print ('Run the IC\n')
print (ic.run())


text:
package view

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"reflect"
	"strings"
	"sync"

	"github.com/kataras/iris/v12/context"

	"github.com/CloudyKit/jet/v6"
)

const jetEngineName = "jet"

// JetEngine is the jet template parser's view engine.
type JetEngine struct {
	fs          http.FileSystem
	rootDir     string
	extension   string
	left, right string

	loader jet.Loader

	developmentMode bool

	// The Set is the `*jet.Set`, exported to offer any custom capabilities that jet users may want.
	// Available after `Load`.
	Set *jet.Set
	mu  sync.Mutex

	// Note that global vars and functions are set in a single spot on the jet parser.
	// If AddFunc or AddVar called before `Load` then these will be set here to be used via `Load` and clear.
	vars map[string]interface{}

	jetDataContextKey string
}

var (
	_ Engine       = (*JetEngine)(nil)
	_ EngineFuncer = (*JetEngine)(nil)
)

// jet library does not export or give us any option to modify them via Set
// (unless we parse the files by ourselves but this is not a smart choice).
var jetExtensions = [...]string{
	".html.jet",
	".jet.html",
	".jet",
}

// Jet creates and returns a new jet view engine.
// The given "extension" MUST begin with a dot.
//
// Usage:
// Jet("./views", ".jet") or
// Jet(iris.Dir("./views"), ".jet") or
// Jet(AssetFile(), ".jet") for embedded data.
func Jet(fs interface{}, extension string) *JetEngine {
	extOK := false
	for _, ext := range jetExtensions {
		if ext == extension {
			extOK = true
			break
		}
	}

	if !extOK {
		panic(fmt.Sprintf("%s extension is not a valid jet engine extension[%s]", extension, strings.Join(jetExtensions[0:], ", ")))
	}

	s := &JetEngine{
		fs:                getFS(fs),
		rootDir:           "/",
		extension:         extension,
		loader:            &jetLoader{fs: getFS(fs)},
		jetDataContextKey: "_jet",
	}

	return s
}

// String returns the name of this view engine, the "jet".
func (s *JetEngine) String() string {
	return jetEngineName
}

// RootDir sets the directory to be used as a starting point
// to load templates from the provided file system.
func (s *JetEngine) RootDir(root string) *JetEngine {
	s.rootDir = filepath.ToSlash(root)
	return s
}

// Name returns the jet engine's name.
func (s *JetEngine) Name() string {
	return "Jet"
}

// Ext should return the final file extension which this view engine is responsible to render.
// If the filename extension on ExecuteWriter is empty then this is appended.
func (s *JetEngine) Ext() string {
	return s.extension
}

// Delims sets the action delimiters to the specified strings, to be used in
// templates. An empty delimiter stands for the
// corresponding default: {{ or }}.
// Should act before `Load` or `iris.Application#RegisterView`.
func (s *JetEngine) Delims(left, right string) *JetEngine {
	s.left = left
	s.right = right
	return s
}

// JetArguments is a type alias of `jet.Arguments`,
// can be used on `AddFunc$funcBody`.
type JetArguments = jet.Arguments

// AddFunc should adds a global function to the jet template set.
func (s *JetEngine) AddFunc(funcName string, funcBody interface{}) {
	// if something like "urlpath" is registered.
	if generalFunc, ok := funcBody.(func(string, ...interface{}) string); ok {
		// jet, unlike others does not accept a func(string, ...interface{}) string,
		// instead it wants:
		// func(JetArguments) reflect.Value.

		s.AddVar(funcName, jet.Func(func(args JetArguments) reflect.Value {
			n := args.NumOfArguments()
			if n == 0 { // no input, don't execute the function, panic instead.
				panic(funcName + " expects one or more input arguments")
			}

			firstInput := args.Get(0).String()

			if n == 1 { // if only the first argument is given.
				return reflect.ValueOf(generalFunc(firstInput))
			}

			// if has variadic.

			variadicN := n - 1
			variadicInputs := make([]interface{}, variadicN) // except the first one.

			for i := 0; i < variadicN; i++ {
				variadicInputs[i] = args.Get(i + 1).Interface()
			}

			return reflect.ValueOf(generalFunc(firstInput, variadicInputs...))
		}))

		return
	}

	if jetFunc, ok := funcBody.(jet.Func); !ok {
		alternativeJetFunc, ok := funcBody.(func(JetArguments) reflect.Value)
		if !ok {
			panic(fmt.Sprintf("JetEngine.AddFunc: funcBody argument is not a type of func(JetArguments) reflect.Value. Got %T instead", funcBody))
		}

		s.AddVar(funcName, jet.Func(alternativeJetFunc))
	} else {
		s.AddVar(funcName, jetFunc)
	}
}

// AddVar adds a global variable to the jet template set.
func (s *JetEngine) AddVar(key string, value interface{}) {
	if s.Set != nil {
		s.Set.AddGlobal(key, value)
	} else {
		if s.vars == nil {
			s.vars = make(map[string]interface{})
		}
		s.vars[key] = value
	}
}

// Reload if setted to true the templates are reloading on each render,
// use it when you're in development and you're boring of restarting
// the whole app when you edit a template file.
//
// Note that if `true` is passed then only one `View -> ExecuteWriter` will be render each time,
// not safe concurrent access across clients, use it only on development state.
func (s *JetEngine) Reload(developmentMode bool) *JetEngine {
	s.developmentMode = developmentMode
	return s
}

// SetLoader can be used when the caller wants to use something like
// multi.Loader or httpfs.Loader.
func (s *JetEngine) SetLoader(loader jet.Loader) *JetEngine {
	s.loader = loader
	return s
}

type jetLoader struct {
	fs http.FileSystem
}

var _ jet.Loader = (*jetLoader)(nil)

// Open opens a file from file system.
func (l *jetLoader) Open(name string) (io.ReadCloser, error) {
	return l.fs.Open(name)
}

// Exists checks if the template name exists by walking the list of template paths.
func (l *jetLoader) Exists(name string) bool {
	_, err := l.fs.Open(name)
	return err == nil
}

// Load should load the templates from a physical system directory or by an embedded one (assets/go-bindata).
func (s *JetEngine) Load() error {
	return walk(s.fs, s.rootDir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if info == nil || info.IsDir() {
			return nil
		}

		if s.extension != "" {
			if !strings.HasSuffix(path, s.extension) {
				return nil
			}
		}

		buf, err := asset(s.fs, path)
		if err != nil {
			return fmt.Errorf("%s: %w", path, err)
		}

		return s.ParseTemplate(path, string(buf))
	})
}

// ParseTemplate accepts a name and contnets to parse and cache a template.
// This parser does not support funcs per template. Use the `AddFunc` instead.
func (s *JetEngine) ParseTemplate(name string, contents string) error {
	s.initSet()

	_, err := s.Set.Parse(name, contents)
	return err
}

func (s *JetEngine) initSet() {
	s.mu.Lock()
	if s.Set == nil {
		var opts = []jet.Option{
			jet.WithDelims(s.left, s.right),
		}
		if s.developmentMode && !isNoOpFS(s.fs) {
			// this check is made to avoid jet's fs lookup on noOp fs (nil passed by the developer).
			// This can be produced when nil fs passed
			// and only `ParseTemplate` is used.
			opts = append(opts, jet.InDevelopmentMode())
		}

		s.Set = jet.NewSet(s.loader, opts...)
		if s.vars != nil {
			for key, value := range s.vars {
				s.Set.AddGlobal(key, value)
			}
		}
	}
	s.mu.Unlock()
}

type (
	// JetRuntimeVars is a type alias for `jet.VarMap`.
	// Can be used at `AddJetRuntimeVars/JetEngine.AddRuntimeVars`
	// to set a runtime variable ${name} to the executing template.
	JetRuntimeVars = jet.VarMap

	// JetRuntime is a type alias of `jet.Runtime`,
	// can be used on RuntimeVariable input function.
	JetRuntime = jet.Runtime
)

// JetRuntimeVarsContextKey is the Iris Context key to keep any custom jet runtime variables.
// See `AddJetRuntimeVars` package-level function and `JetEngine.AddRuntimeVars` method.
const JetRuntimeVarsContextKey = "iris.jetvarmap"

// AddJetRuntimeVars sets or inserts runtime jet variables through the Iris Context.
// This gives the ability to add runtime variables from different handlers in the request chain,
// something that the jet template parser does not offer at all.
//
// Usage: view.AddJetRuntimeVars(ctx, view.JetRuntimeVars{...}).
// See `JetEngine.AddRuntimeVars` too.
func AddJetRuntimeVars(ctx *context.Context, jetVarMap JetRuntimeVars) {
	if v := ctx.Values().Get(JetRuntimeVarsContextKey); v != nil {
		if vars, ok := v.(JetRuntimeVars); ok {
			for key, value := range jetVarMap {
				vars[key] = value
			}
			return
		}
	}

	ctx.Values().Set(JetRuntimeVarsContextKey, jetVarMap)
}

// AddRuntimeVars sets or inserts runtime jet variables through the Iris Context.
// This gives the ability to add runtime variables from different handlers in the request chain,
// something that the jet template parser does not offer at all.
//
// Usage: view.AddJetRuntimeVars(ctx, view.JetRuntimeVars{...}).
// See `view.AddJetRuntimeVars` if package-level access is more meanful to the code flow.
func (s *JetEngine) AddRuntimeVars(ctx *context.Context, vars JetRuntimeVars) {
	AddJetRuntimeVars(ctx, vars)
}

// ExecuteWriter should execute a template by its filename with an optional layout and bindingData.
func (s *JetEngine) ExecuteWriter(w io.Writer, filename string, layout string, bindingData interface{}) error {
	tmpl, err := s.Set.GetTemplate(filename)
	if err != nil {
		return err
	}

	var vars JetRuntimeVars

	if ctx, ok := w.(*context.Context); ok {
		runtimeVars := ctx.Values().Get(JetRuntimeVarsContextKey)
		if runtimeVars != nil {
			if jetVars, ok := runtimeVars.(JetRuntimeVars); ok {
				vars = jetVars
			}
		}

		if v := ctx.Values().Get(s.jetDataContextKey); v != nil {
			if bindingData == nil {
				// if bindingData is nil, try to fill them by context key (a middleware can set data).
				bindingData = v
			} else if m, ok := bindingData.(context.Map); ok {
				// else if bindingData are passed to App/Context.View
				// and it's map try to fill with the new values passed from a middleware.
				if mv, ok := v.(context.Map); ok {
					for key, value := range mv {
						m[key] = value
					}
				}
			}
		}
	}

	if bindingData == nil {
		return tmpl.Execute(w, vars, nil)
	}

	if vars == nil {
		vars = make(JetRuntimeVars)
	}

	/* fixed on jet v4.0.0, so no need of this:
	if m, ok := bindingData.(context.Map); ok {
		var jetData interface{}
		for k, v := range m {
			if k == s.jetDataContextKey {
				jetData = v
				continue
			}

			if value, ok := v.(reflect.Value); ok {
				vars[k] = value
			} else {
				vars[k] = reflect.ValueOf(v)
			}
		}

		if jetData != nil {
			bindingData = jetData
		}
	}*/

	return tmpl.Execute(w, vars, bindingData)
}


text:
<?php
declare(strict_types=1);

namespace PerFi\Application\Repository;

use PerFi\Domain\Equity\OpeningBalance;
use PerFi\Domain\Equity\OpeningBalanceRepository;
use PerFi\Domain\MoneyFactory;

class InMemoryOpeningBalanceRepository implements OpeningBalanceRepository
{
    /**
     * @var array
     */
    private $openingBalances;

    /**
     * {@inheritdoc}
     */
    public function save(OpeningBalance $openingBalance)
    {
        $currency = $openingBalance->currency();

        $this->openingBalances[$currency][(string) $openingBalance->id()] = $openingBalance;
    }

    /**
     * {@inheritdoc}
     */
    public function getAll() : array
    {
        return $this->openingBalances;
    }

    /**
     * Get the totals for all the balances in the repository
     *
     * @return array
     */
    public function getTotals() : array
    {
        $totals = [];

        foreach ($this->getAll() as $currency => $balances) {
            $total = MoneyFactory::amountInCurrency('0', $currency);

            foreach ($balances as $openingBalance) {
                if ($currency === $openingBalance->currency()) {
                    $total = $total->add($openingBalance->amount());
                }
            }

            $totals[$currency] = $total;
        }

        return $totals;
    }
}


text:
exports.view = function(req, res) {

	res.render('welcome');

}


text:
module DataKit
  module Converters
    class Boolean
      class << self
        def convert(value)
          downcased = value.downcase
          downcased == 'true' || downcased == 't'
        end

        def match?(value)
          (value =~ /\A(true|t|false|f)\z/i) == 0
        end
      end
    end
  end
end


text:
<?php

namespace Elastica\Query;
use Elastica\Param;

/**
 * Abstract query object. Should be extended by all query types.
 *
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
abstract class AbstractQuery extends Param
{
}


text:
from server import app, init
import json

from services import load_credentials, get_database, get_watson_service

import pytest

app.config['CACHEDB'] = 'testcache'
app.config['VISITDB'] = 'visitcache'
app.config['TESTING'] = True

testapp = app.test_client()

init()

@pytest.fixture(scope="module")
def cacheDB():
    db, client = get_database(app.config['CACHEDB'])
    yield db

@pytest.fixture(scope="module")
def visitDB():
    db, client = get_database(app.config['VISITDB'])
    yield db
    db.delete()

@pytest.fixture(scope="module")
def text_request():
    response = testapp.post('/api/analyze-text',
                            data=json.dumps({'text': "Nada"}),
                            content_type='application/json'
                            )
    yield response

@pytest.fixture(scope="module")
def image_request():
    image_url = "http://jinja.pocoo.org/docs/2.9/_static/jinja-small.png"
    response = testapp.post('/api/analyze-image',
                            data=json.dumps({'text': image_url}),
                            content_type='application/json'
                            )
    yield response

def test_service_connection():
    load_credentials()
    get_watson_service('language_translator')
    get_watson_service('text_to_speech')
    get_watson_service('speech_to_text')
    get_watson_service('natural-language-understanding')
    get_watson_service('watson_vision_combined')

def test_index():
    response = testapp.get('/')
    assert response.status_code == 200
    assert b'Erittely' in response.data

def test_analyze_text(text_request, cacheDB):

    assert text_request.status_code == 200
    response_json = json.loads(text_request.data.decode())
    assert 'url' in response_json
    query_id = response_json['url'][len('/text/'):]
    print(query_id)
    assert query_id in [doc['id'] for doc in cacheDB]

def test_analyze_image(image_request, cacheDB):

    assert image_request.status_code == 200
    response_json = json.loads(image_request.data.decode())
    assert 'url' in response_json
    query_id = response_json['url'][len('/image/'):]
    print(query_id)
    assert query_id in [doc['id'] for doc in cacheDB]

def test_analyze_text_output(text_request):
    response_json = json.loads(text_request.data.decode())
    url = response_json['url']

    response = testapp.get(url, follow_redirects=True)
    print(response.data)
    assert response.status_code == 200

    assert b'Spanish' in response.data
    assert b'Nothing' in response.data
    assert b'Tristeza' in response.data

def test_analyze_image_output(image_request):
    response_json = json.loads(image_request.data.decode())
    url = response_json['url']

    response = testapp.get(url, follow_redirects=True)
    print(response.data)
    assert response.status_code == 200

    assert b'Framework' in response.data

def test_history(text_request, visitDB):
    response = testapp.get('/api/recent')
    assert response.status_code == 200

    response_json = json.loads(text_request.data.decode())
    url = response_json['url']

    response = testapp.get(url, follow_redirects=True)

    response = testapp.get('/api/recent')
    assert response.status_code == 200
    assert b'Nada' in response.data


text:
<?php

namespace Nella;

use Nette\Environment;

/**
 * Doctrine cache use Nette\Cache
 *
 * @copyright  Copyright (c) 2006, 2010 Patrik Votoček
 * @package    Nella
 */
class NetteDoctrineCache extends \Doctrine\Common\Cache\AbstractCache
{

	/**
	 * @var array $data
	 */
	private $data = array();

	public function __construct()
	{
		$this->data = Environment::getCache('Doctrine');
	}

	/**
	 * {@inheritdoc}
	 */
	public function getIds()
	{
		return array_keys($this->data);
	}

	/**
	 * {@inheritdoc}
	 */
	protected function _doFetch($id)
	{
		if (isset($this->data[$id])) {
			return $this->data[$id];
		}
		return FALSE;
	}

	/**
	 * {@inheritdoc}
	 */
	protected function _doContains($id)
	{
		return isset($this->data[$id]);
	}

	/**
	 * {@inheritdoc}
	 */
	protected function _doSave($id, $data, $lifeTime = 0)
	{
		if ($lifeTime != 0)
			$this->data->save($id, $data, array('expire' => time() + $lifeTime));
		else
			$this->data->save($id, $data);
		return TRUE;
	}

	/**
	 * {@inheritdoc}
	 */
	protected function _doDelete($id)
	{
		unset($this->data[$id]);
		return TRUE;
	}

}


text:
package de.tudresden.inf.lat.wikihtml.renderer.global;

import java.util.ArrayList;
import java.util.List;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import de.tudresden.inf.lat.wikihtml.renderer.common.ConversionToken;
import de.tudresden.inf.lat.wikihtml.renderer.common.Renderer;
import de.tudresden.inf.lat.wikihtml.renderer.common.WikiLineToken;

/**
 *
 * @author Julian Mendez
 *
 */
public class NowikiRendererTest {

	@Test
	public void testTextWithIgnoredFormat() {
		Renderer renderer = new NowikiRenderer();
		ConversionToken input = new WikiLineToken("<nowiki>'''text with ignored format'''</nowiki>");
		List<ConversionToken> expected = new ArrayList<>();
		expected.add(new WikiLineToken("'''text with ignored format'''"));
		List<ConversionToken> output = renderer.render(input);
		Assertions.assertEquals(expected, output);
	}

	@Test
	public void testTextWithManyLines() {
		Renderer renderer = new NowikiRenderer();
		ConversionToken input1 = new WikiLineToken("<nowiki>text with spaces");
		ConversionToken input2 = new WikiLineToken("and '''new''' lines");
		ConversionToken input3 = new WikiLineToken(" as well</nowiki>");
		List<ConversionToken> expected = new ArrayList<>();
		expected.add(new WikiLineToken("text with spaces"));
		expected.add(new WikiLineToken("and '''new''' lines"));
		expected.add(new WikiLineToken(" as well"));
		List<ConversionToken> output = new ArrayList<>();
		output.addAll(renderer.render(input1));
		output.addAll(renderer.render(input2));
		output.addAll(renderer.render(input3));
		Assertions.assertEquals(expected, output);
	}

	@Test
	public void testTextWithNewLines() {
		Renderer renderer = new NowikiRenderer();
		ConversionToken input = new WikiLineToken("<nowiki>text with spaces\nand new lines\n as well</nowiki>");
		List<ConversionToken> expected = new ArrayList<>();
		expected.add(new WikiLineToken("text with spaces\nand new lines\n as well"));
		List<ConversionToken> output = renderer.render(input);
		Assertions.assertEquals(expected, output);
	}

	@Test
	public void testTextWithSpaces() {
		Renderer renderer = new NowikiRenderer();
		ConversionToken input = new WikiLineToken("<nowiki>text with spaces</nowiki>");
		List<ConversionToken> expected = new ArrayList<>();
		expected.add(new WikiLineToken("text with spaces"));
		List<ConversionToken> output = renderer.render(input);
		Assertions.assertEquals(expected, output);
	}

}