text:
'use strict';

const puppeteer = require('puppeteer');

(async() => {

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', request => {
  if (request.resourceType === 'image')
    request.abort();
  else
    request.continue();
});
await page.goto('https://news.google.com/news/');
await page.screenshot({path: 'news.png', fullPage: true});

await browser.close();

})();


text:
#pragma once

#include <string>
#include <ckm/ckm-type.h>
#include <ckm/ckm-raw-buffer.h>
#include <db-row.h>
#include <permission.h>
#include <generic-socket-manager.h>

namespace CKM {

class AccessControl {
public:
    /**
     * return true if client uid is from the system services uid space
     */
    bool isSystemService(const uid_t uid) const;
    bool isSystemService(const CKM::Credentials &cred) const;

    /**
     * check if given data can be saved by current accessor
     * @return CKM_API_SUCCESS if access is allowed, otherwise negative error code
     */
    int canSave(const CKM::Credentials &accessorCred,
                const Label & ownerLabel) const;

    /**
     * check if given label can be modified by accessor
     * @return CKM_API_SUCCESS if access is allowed, otherwise negative error code
     */
    int canModify(const CKM::Credentials &accessorCred,
                  const Label & ownerLabel) const;

    /**
     * check if given row can be read (for internal use)
     * @return CKM_API_SUCCESS if access is allowed, otherwise negative error code
     */
    int canRead(const CKM::Credentials &accessorCred,
                const PermissionForLabel & permissionLabel) const;

    /**
     * check if given row can be exported (data provided to the client)
     * @return CKM_API_SUCCESS if access is allowed, otherwise negative error code
     */
    int canExport(const CKM::Credentials &accessorCred,
                  const DB::Row & row,
                  const PermissionForLabel & permissionLabel) const;

    /**
     * check if given accessor can delete ownerLabel's items.
     * @return CKM_API_SUCCESS if access is allowed, otherwise negative error code
     */
    int canDelete(const CKM::Credentials &accessorCred,
                  const PermissionForLabel & permissionLabel) const;

    void updateCCMode();
    bool isCCMode() const;

private:
    bool m_ccMode;
};

} // namespace CKM

redpajama_set_name: RedPajamaGithub


text:
package org.wtb.qcloudapi.base;

public class BasePageResp extends BaseResp {

    private int totalCount;

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }
}


text:
package datadog_test

import (
	"encoding/json"
	"testing"

	"github.com/stretchr/testify/assert"
	dd "github.com/zorkian/go-datadog-api"
)

func TestAPPKeySerialization(t *testing.T) {

	raw := `
	{
		"owner": "john@example.com",
		"name": "myCoolKey",
		"hash": "31111111111111111111aaaaaaaaaaaaaaaaaaaa"
	}`

	var appkey dd.APPKey
	err := json.Unmarshal([]byte(raw), &appkey)
	assert.Equal(t, err, nil)
	assert.Equal(t, *appkey.Name, "myCoolKey")
	assert.Equal(t, *appkey.Owner, "john@example.com")
	assert.Equal(t, *appkey.Hash, "31111111111111111111aaaaaaaaaaaaaaaaaaaa")
}


text:
package com.amazonaws.services.codepipeline.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *

 * Represents the input of a PutThirdPartyJobSuccessResult action.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PutThirdPartyJobSuccessResultRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The ID of the job that successfully completed. This is the same ID returned from
     * PollForThirdPartyJobs.
     *

     */
    private String jobId;
    /**
     *

     * The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed
     * access to the job and its details.
     *

     */
    private String clientToken;
    /**
     *

     * Represents information about a current revision.
     *

     */
    private CurrentRevision currentRevision;
    /**
     *

     * A token generated by a job worker, such as an AWS CodeDeploy deployment ID, that a successful job provides to
     * identify a partner action in progress. Future jobs use this token to identify the running instance of the action.
     * It can be reused to return more information about the progress of the partner action. When the action is
     * complete, no continuation token should be supplied.
     *

     */
    private String continuationToken;
    /**
     *

     * The details of the actions taken and results produced on an artifact as it passes through stages in the pipeline.
     *

     */
    private ExecutionDetails executionDetails;

    /**
     *

     * The ID of the job that successfully completed. This is the same ID returned from
     * PollForThirdPartyJobs.
     *

     *
     * @param jobId
     *        The ID of the job that successfully completed. This is the same ID returned from
     *        PollForThirdPartyJobs.
     */

    public void setJobId(String jobId) {
        this.jobId = jobId;
    }

    /**
     *

     * The ID of the job that successfully completed. This is the same ID returned from
     * PollForThirdPartyJobs.
     *

     *
     * @return The ID of the job that successfully completed. This is the same ID returned from
     *         PollForThirdPartyJobs.
     */

    public String getJobId() {
        return this.jobId;
    }

    /**
     *

     * The ID of the job that successfully completed. This is the same ID returned from
     * PollForThirdPartyJobs.
     *

     *
     * @param jobId
     *        The ID of the job that successfully completed. This is the same ID returned from
     *        PollForThirdPartyJobs.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutThirdPartyJobSuccessResultRequest withJobId(String jobId) {
        setJobId(jobId);
        return this;
    }

    /**
     *

     * The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed
     * access to the job and its details.
     *

     *
     * @param clientToken
     *        The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is
     *        allowed access to the job and its details.
     */

    public void setClientToken(String clientToken) {
        this.clientToken = clientToken;
    }

    /**
     *

     * The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed
     * access to the job and its details.
     *

     *
     * @return The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is
     *         allowed access to the job and its details.
     */

    public String getClientToken() {
        return this.clientToken;
    }

    /**
     *

     * The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed
     * access to the job and its details.
     *

     *
     * @param clientToken
     *        The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is
     *        allowed access to the job and its details.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutThirdPartyJobSuccessResultRequest withClientToken(String clientToken) {
        setClientToken(clientToken);
        return this;
    }

    /**
     *

     * Represents information about a current revision.
     *

     *
     * @param currentRevision
     *        Represents information about a current revision.
     */

    public void setCurrentRevision(CurrentRevision currentRevision) {
        this.currentRevision = currentRevision;
    }

    /**
     *

     * Represents information about a current revision.
     *

     *
     * @return Represents information about a current revision.
     */

    public CurrentRevision getCurrentRevision() {
        return this.currentRevision;
    }

    /**
     *

     * Represents information about a current revision.
     *

     *
     * @param currentRevision
     *        Represents information about a current revision.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutThirdPartyJobSuccessResultRequest withCurrentRevision(CurrentRevision currentRevision) {
        setCurrentRevision(currentRevision);
        return this;
    }

    /**
     *

     * A token generated by a job worker, such as an AWS CodeDeploy deployment ID, that a successful job provides to
     * identify a partner action in progress. Future jobs use this token to identify the running instance of the action.
     * It can be reused to return more information about the progress of the partner action. When the action is
     * complete, no continuation token should be supplied.
     *

     *
     * @param continuationToken
     *        A token generated by a job worker, such as an AWS CodeDeploy deployment ID, that a successful job provides
     *        to identify a partner action in progress. Future jobs use this token to identify the running instance of
     *        the action. It can be reused to return more information about the progress of the partner action. When the
     *        action is complete, no continuation token should be supplied.
     */

    public void setContinuationToken(String continuationToken) {
        this.continuationToken = continuationToken;
    }

    /**
     *

     * A token generated by a job worker, such as an AWS CodeDeploy deployment ID, that a successful job provides to
     * identify a partner action in progress. Future jobs use this token to identify the running instance of the action.
     * It can be reused to return more information about the progress of the partner action. When the action is
     * complete, no continuation token should be supplied.
     *

     *
     * @return A token generated by a job worker, such as an AWS CodeDeploy deployment ID, that a successful job
     *         provides to identify a partner action in progress. Future jobs use this token to identify the running
     *         instance of the action. It can be reused to return more information about the progress of the partner
     *         action. When the action is complete, no continuation token should be supplied.
     */

    public String getContinuationToken() {
        return this.continuationToken;
    }

    /**
     *

     * A token generated by a job worker, such as an AWS CodeDeploy deployment ID, that a successful job provides to
     * identify a partner action in progress. Future jobs use this token to identify the running instance of the action.
     * It can be reused to return more information about the progress of the partner action. When the action is
     * complete, no continuation token should be supplied.
     *

     *
     * @param continuationToken
     *        A token generated by a job worker, such as an AWS CodeDeploy deployment ID, that a successful job provides
     *        to identify a partner action in progress. Future jobs use this token to identify the running instance of
     *        the action. It can be reused to return more information about the progress of the partner action. When the
     *        action is complete, no continuation token should be supplied.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutThirdPartyJobSuccessResultRequest withContinuationToken(String continuationToken) {
        setContinuationToken(continuationToken);
        return this;
    }

    /**
     *

     * The details of the actions taken and results produced on an artifact as it passes through stages in the pipeline.
     *

     *
     * @param executionDetails
     *        The details of the actions taken and results produced on an artifact as it passes through stages in the
     *        pipeline.
     */

    public void setExecutionDetails(ExecutionDetails executionDetails) {
        this.executionDetails = executionDetails;
    }

    /**
     *

     * The details of the actions taken and results produced on an artifact as it passes through stages in the pipeline.
     *

     *
     * @return The details of the actions taken and results produced on an artifact as it passes through stages in the
     *         pipeline.
     */

    public ExecutionDetails getExecutionDetails() {
        return this.executionDetails;
    }

    /**
     *

     * The details of the actions taken and results produced on an artifact as it passes through stages in the pipeline.
     *

     *
     * @param executionDetails
     *        The details of the actions taken and results produced on an artifact as it passes through stages in the
     *        pipeline.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutThirdPartyJobSuccessResultRequest withExecutionDetails(ExecutionDetails executionDetails) {
        setExecutionDetails(executionDetails);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getJobId() != null)
            sb.append("JobId: ").append(getJobId()).append(",");
        if (getClientToken() != null)
            sb.append("ClientToken: ").append(getClientToken()).append(",");
        if (getCurrentRevision() != null)
            sb.append("CurrentRevision: ").append(getCurrentRevision()).append(",");
        if (getContinuationToken() != null)
            sb.append("ContinuationToken: ").append(getContinuationToken()).append(",");
        if (getExecutionDetails() != null)
            sb.append("ExecutionDetails: ").append(getExecutionDetails());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof PutThirdPartyJobSuccessResultRequest == false)
            return false;
        PutThirdPartyJobSuccessResultRequest other = (PutThirdPartyJobSuccessResultRequest) obj;
        if (other.getJobId() == null ^ this.getJobId() == null)
            return false;
        if (other.getJobId() != null && other.getJobId().equals(this.getJobId()) == false)
            return false;
        if (other.getClientToken() == null ^ this.getClientToken() == null)
            return false;
        if (other.getClientToken() != null && other.getClientToken().equals(this.getClientToken()) == false)
            return false;
        if (other.getCurrentRevision() == null ^ this.getCurrentRevision() == null)
            return false;
        if (other.getCurrentRevision() != null && other.getCurrentRevision().equals(this.getCurrentRevision()) == false)
            return false;
        if (other.getContinuationToken() == null ^ this.getContinuationToken() == null)
            return false;
        if (other.getContinuationToken() != null && other.getContinuationToken().equals(this.getContinuationToken()) == false)
            return false;
        if (other.getExecutionDetails() == null ^ this.getExecutionDetails() == null)
            return false;
        if (other.getExecutionDetails() != null && other.getExecutionDetails().equals(this.getExecutionDetails()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getJobId() == null) ? 0 : getJobId().hashCode());
        hashCode = prime * hashCode + ((getClientToken() == null) ? 0 : getClientToken().hashCode());
        hashCode = prime * hashCode + ((getCurrentRevision() == null) ? 0 : getCurrentRevision().hashCode());
        hashCode = prime * hashCode + ((getContinuationToken() == null) ? 0 : getContinuationToken().hashCode());
        hashCode = prime * hashCode + ((getExecutionDetails() == null) ? 0 : getExecutionDetails().hashCode());
        return hashCode;
    }

    @Override
    public PutThirdPartyJobSuccessResultRequest clone() {
        return (PutThirdPartyJobSuccessResultRequest) super.clone();
    }

}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Oidium erysiphoides f. lagerstraemiae J.M. Yen

### Remarks
null


text:
using MyTested.AspNetCore.Mvc;
using PaderbornUniversity.SILab.Hip.CmsApi.Controllers;
using PaderbornUniversity.SILab.Hip.CmsApi.Models.AnnotationAnalytics;
using System.Collections.Generic;
using System.Linq;
using Xunit;

namespace PaderbornUniversity.SILab.Hip.CmsApi.Tests.ControllerTests
{
    public class TopicsControllerAnalyticsTest
    {
        private ControllerTester<TopicsController> _tester;
        public TopicsControllerAnalyticsTest()
        {
            _tester = new ControllerTester<TopicsController>();
        }

        #region GET Analytics

        /// <summary>
        /// Returns ok if tag frequency analytics are retrieved
        /// </summary>
        [Fact]
        public void GetTagFrequencyAnalyticsTest()
        {
            var expectedTagFrequencyList = new List<TagFrequency>();
            var tagFrequency = new TagFrequency(_tester.Tag1.Id, null, 1);
            expectedTagFrequencyList.Add(tagFrequency);
            var result = new TagFrequencyAnalyticsResult
            {
                TagFrequency = expectedTagFrequencyList
            };

            _tester.TestControllerWithMockData()
                .Calling(c => c.GetTagFrequencyAnalyticsAsync(_tester.TopicOne.Id))
                .ShouldReturn()
                .Ok()
                .WithModelOfType<TagFrequencyAnalyticsResult>()
                .Passing(actual => actual.TagFrequency.Count() == result.TagFrequency.Count());
        }

        /// <summary>
        /// Returns 404 if frequency analytics are not found
        /// </summary>
        [Fact]
        public void GetTagFrequencyAnalyticsTest404()
        {
            _tester.TestController()
                .Calling(c => c.GetTagFrequencyAnalyticsAsync(_tester.TopicOne.Id))
                .ShouldReturn()
                .NotFound();
        }

        /// <summary>
        /// Returns 404 if frequency analytics are not found
        /// </summary>
        [Fact]
        public void GetTagFrequencyAnalyticsTest404ForDifferentTopic()
        {
            _tester.TestControllerWithMockData()
                .Calling(c => c.GetTagFrequencyAnalyticsAsync(_tester.TopicTwo.Id))
                .ShouldReturn()
                .NotFound();
        }

        /// <summary>
        /// Returns 403 if a non-attached user tries to get the analytics
        /// </summary>
        [Fact]
        public void GetTagFrequencyAnalyticsTest403()
        {
            _tester.TestControllerWithMockData(_tester.Student.Id) // Student not attached to topic two
                .Calling(c => c.GetTagFrequencyAnalyticsAsync(_tester.TopicTwo.Id))
                .ShouldReturn()
                .StatusCode(403);
        }

        #endregion
    }
}


text:
package org.antlr.mojo.antlr4;

import io.takari.maven.testing.TestMavenRuntime;
import io.takari.maven.testing.TestResources;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class Antlr4MojoTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Rule
    public final TestResources resources = new TestResources();

    @Rule
    public final TestMavenRuntime maven = new TestMavenRuntime();

    @Test
    public void importTokens() throws Exception {
        Path baseDir = resources.getBasedir("importTokens").toPath();
        Path antlrDir = baseDir.resolve("src/main/antlr4");
        Path generatedSources = baseDir.resolve("target/generated-sources/antlr4");

        Path genParser = generatedSources.resolve("test/SimpleParser.java");
        Path tokens = antlrDir.resolve("imports/SimpleLexer.tokens");

        MavenProject project = maven.readMavenProject(baseDir.toFile());
        MavenSession session = maven.newMavenSession(project);
        MojoExecution exec = maven.newMojoExecution("antlr4");

        ////////////////////////////////////////////////////////////////////////
        // 1st - all grammars have to be processed
        ////////////////////////////////////////////////////////////////////////

        assertFalse(Files.exists(genParser));

        maven.executeMojo(session, project, exec);

        assertTrue(Files.exists(genParser));

        ////////////////////////////////////////////////////////////////////////
        // 2nd - nothing has been modified, no grammars have to be processed
        ////////////////////////////////////////////////////////////////////////

        {
            byte[] sum = checksum(genParser);

            maven.executeMojo(session, project, exec);

            assertTrue(Arrays.equals(sum, checksum(genParser)));
        }

        ////////////////////////////////////////////////////////////////////////
        // 3rd - the imported grammar changed, every dependency has to be processed
        ////////////////////////////////////////////////////////////////////////

        try(Change change = Change.of(tokens, "DOT=4")) {
            byte[] sum = checksum(genParser);

            maven.executeMojo(session, project, exec);

            assertFalse(Arrays.equals(sum, checksum(genParser)));
        }
    }

    @Test
    public void importsCustomLayout() throws Exception {
        Path baseDir = resources.getBasedir("importsCustom").toPath();
        Path antlrDir = baseDir.resolve("src/main/antlr4");
        Path generatedSources = baseDir.resolve("src/main/java");

        Path genTestLexer = generatedSources.resolve("foo/TestLexer.java");
        Path genTestParser = generatedSources.resolve("foo/TestParser.java");
        Path genHello = generatedSources.resolve("foo/HelloParser.java");

        Path baseGrammar = antlrDir.resolve("imports/TestBaseLexer.g4");
        Path lexerGrammar = antlrDir.resolve("TestLexer.g4");
        Path parserGrammar = antlrDir.resolve("TestParser.g4");

        Xpp3Dom outputDirectory = TestMavenRuntime.newParameter("outputDirectory",
                "src/main/java/foo");
        Xpp3Dom arguments = new Xpp3Dom("arguments");
        arguments.addChild(TestMavenRuntime.newParameter("argument", "-package"));
        arguments.addChild(TestMavenRuntime.newParameter("argument", "foo"));

        MavenProject project = maven.readMavenProject(baseDir.toFile());
        MavenSession session = maven.newMavenSession(project);
        MojoExecution exec = maven.newMojoExecution("antlr4", outputDirectory, arguments);

        ////////////////////////////////////////////////////////////////////////
        // 1st - all grammars have to be processed
        ////////////////////////////////////////////////////////////////////////

        assertFalse(Files.exists(genHello));
        assertFalse(Files.exists(genTestParser));
        assertFalse(Files.exists(genTestLexer));

        maven.executeMojo(session, project, exec);

        assertTrue(Files.exists(genHello));
        assertTrue(Files.exists(genTestParser));
        assertTrue(Files.exists(genTestLexer));

        ////////////////////////////////////////////////////////////////////////
        // 2nd - nothing has been modified, no grammars have to be processed
        ////////////////////////////////////////////////////////////////////////

        {
            byte[] testLexerSum = checksum(genTestLexer);
            byte[] testParserSum = checksum(genTestParser);
            byte[] helloSum = checksum(genHello);

            maven.executeMojo(session, project, exec);

            assertTrue(Arrays.equals(testLexerSum, checksum(genTestLexer)));
            assertTrue(Arrays.equals(testParserSum, checksum(genTestParser)));
            assertTrue(Arrays.equals(helloSum, checksum(genHello)));
        }

        ////////////////////////////////////////////////////////////////////////
        // 3rd - the imported grammar changed, every dependency has to be processed
        ////////////////////////////////////////////////////////////////////////

        // modify the grammar to make checksum comparison detect a change
        try(Change change = Change.of(baseGrammar, "DOT: '.' ;")) {
            byte[] testLexerSum = checksum(genTestLexer);
            byte[] testParserSum = checksum(genTestParser);
            byte[] helloSum = checksum(genHello);

            maven.executeMojo(session, project, exec);

            assertFalse(Arrays.equals(testLexerSum, checksum(genTestLexer)));
            assertFalse(Arrays.equals(testParserSum, checksum(genTestParser)));
            assertTrue(Arrays.equals(helloSum, checksum(genHello)));
        }

        ////////////////////////////////////////////////////////////////////////
        // 4th - the lexer grammar changed, the parser grammar has to be processed as well
        ////////////////////////////////////////////////////////////////////////

        // modify the grammar to make checksum comparison detect a change
        try(Change change = Change.of(lexerGrammar, "fragment DOT : '.';")) {
            byte[] testLexerSum = checksum(genTestLexer);
            byte[] testParserSum = checksum(genTestParser);
            byte[] helloSum = checksum(genHello);

            maven.executeMojo(session, project, exec);

            assertFalse(Arrays.equals(testLexerSum, checksum(genTestLexer)));
            assertFalse(Arrays.equals(testParserSum, checksum(genTestParser)));
            assertTrue(Arrays.equals(helloSum, checksum(genHello)));
        }

        ////////////////////////////////////////////////////////////////////////
        // 5th - the parser grammar changed, no other grammars have to be processed
        ////////////////////////////////////////////////////////////////////////

        // modify the grammar to make checksum comparison detect a change
        try(Change change = Change.of(parserGrammar, " t : WS* ;")) {
            byte[] testLexerSum = checksum(genTestLexer);
            byte[] testParserSum = checksum(genTestParser);
            byte[] helloSum = checksum(genHello);

            maven.executeMojo(session, project, exec);

            assertTrue(Arrays.equals(testLexerSum, checksum(genTestLexer)));
            assertFalse(Arrays.equals(testParserSum, checksum(genTestParser)));
            assertTrue(Arrays.equals(helloSum, checksum(genHello)));
        }
    }

    @Test
    public void importsStandardLayout() throws Exception {
        Path baseDir = resources.getBasedir("importsStandard").toPath();
        Path antlrDir = baseDir.resolve("src/main/antlr4");
        Path generatedSources = baseDir.resolve("target/generated-sources/antlr4");

        Path genTestLexer = generatedSources.resolve("test/TestLexer.java");
        Path genTestParser = generatedSources.resolve("test/TestParser.java");
        Path genHello = generatedSources.resolve("test/HelloParser.java");

        Path baseGrammar = antlrDir.resolve("imports/TestBaseLexer.g4");
        Path baseGrammar2 = antlrDir.resolve("imports/TestBaseLexer2.g4");
        Path lexerGrammar = antlrDir.resolve("test/TestLexer.g4");
        Path parserGrammar = antlrDir.resolve("test/TestParser.g4");

        MavenProject project = maven.readMavenProject(baseDir.toFile());
        MavenSession session = maven.newMavenSession(project);
        MojoExecution exec = maven.newMojoExecution("antlr4");

        ////////////////////////////////////////////////////////////////////////
        // 1st - all grammars have to be processed
        ////////////////////////////////////////////////////////////////////////

        assertFalse(Files.exists(genHello));
        assertFalse(Files.exists(genTestParser));
        assertFalse(Files.exists(genTestLexer));

        maven.executeMojo(session, project, exec);

        assertTrue(Files.exists(genHello));
        assertTrue(Files.exists(genTestParser));
        assertTrue(Files.exists(genTestLexer));
        byte[] origTestLexerSum = checksum(genTestLexer);
        byte[] origTestParserSum = checksum(genTestParser);
        byte[] origHelloSum = checksum(genHello);

        ////////////////////////////////////////////////////////////////////////
        // 2nd - nothing has been modified, no grammars have to be processed
        ////////////////////////////////////////////////////////////////////////

        {
            maven.executeMojo(session, project, exec);

            assertTrue(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));
            assertTrue(Arrays.equals(origTestParserSum, checksum(genTestParser)));
            assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));
        }

        ////////////////////////////////////////////////////////////////////////
        // 3rd - the imported grammar changed, every dependency has to be processed
        ////////////////////////////////////////////////////////////////////////

        // modify the grammar to make checksum comparison detect a change
        try(Change change = Change.of(baseGrammar, "DOT: '.' ;")) {
            maven.executeMojo(session, project, exec);

            assertFalse(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));
            assertFalse(Arrays.equals(origTestParserSum, checksum(genTestParser)));
            assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));
        }
        // Restore file and confirm it was restored.
        maven.executeMojo(session, project, exec);
        assertTrue(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));
        assertTrue(Arrays.equals(origTestParserSum, checksum(genTestParser)));
        assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));

        ////////////////////////////////////////////////////////////////////////
        // 4th - the second imported grammar changed, every dependency has to be processed
        ////////////////////////////////////////////////////////////////////////

        // modify the grammar to make checksum comparison detect a change
        try(Change change = Change.of(baseGrammar2, "BANG: '!' ;")) {
            maven.executeMojo(session, project, exec);

            assertFalse(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));
            assertFalse(Arrays.equals(origTestParserSum, checksum(genTestParser)));
            assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));
        }
        // Restore file and confirm it was restored.
        maven.executeMojo(session, project, exec);
        assertTrue(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));
        assertTrue(Arrays.equals(origTestParserSum, checksum(genTestParser)));
        assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));

        ////////////////////////////////////////////////////////////////////////
        // 5th - the lexer grammar changed, the parser grammar has to be processed as well
        ////////////////////////////////////////////////////////////////////////

        // modify the grammar to make checksum comparison detect a change
        try(Change change = Change.of(lexerGrammar, "FOO: 'foo' ;")) {
            maven.executeMojo(session, project, exec);

            assertFalse(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));
            assertFalse(Arrays.equals(origTestParserSum, checksum(genTestParser)));
            assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));
        }
        // Restore file and confirm it was restored.
        maven.executeMojo(session, project, exec);
        assertTrue(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));
        assertTrue(Arrays.equals(origTestParserSum, checksum(genTestParser)));
        assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));

        ////////////////////////////////////////////////////////////////////////
        // 6th - the parser grammar changed, no other grammars have to be processed
        ////////////////////////////////////////////////////////////////////////

        // modify the grammar to make checksum comparison detect a change
        try(Change change = Change.of(parserGrammar, " t : WS* ;")) {
            maven.executeMojo(session, project, exec);

            assertTrue(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));
            assertFalse(Arrays.equals(origTestParserSum, checksum(genTestParser)));
            assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));
        }
        // Restore file and confirm it was restored.
        maven.executeMojo(session, project, exec);
        assertTrue(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));
        assertTrue(Arrays.equals(origTestParserSum, checksum(genTestParser)));
        assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));
    }

    @Test
    public void processWhenDependencyRemoved() throws Exception {
        Path baseDir = resources.getBasedir("dependencyRemoved").toPath();
        Path antlrDir = baseDir.resolve("src/main/antlr4");

        Path baseGrammar = antlrDir.resolve("imports/HelloBase.g4");

        MavenProject project = maven.readMavenProject(baseDir.toFile());
        MavenSession session = maven.newMavenSession(project);
        MojoExecution exec = maven.newMojoExecution("antlr4");

        maven.executeMojo(session, project, exec);

        try(Change temp = Change.of(baseGrammar)) {
            // if the base grammar no longer exists, processing must be performed
            Files.delete(baseGrammar);

            thrown.expect(MojoExecutionException.class);
            thrown.expectMessage("ANTLR 4 caught 1 build errors.");

            maven.executeMojo(session, project, exec);
        }
    }

    private byte[] checksum(Path path) throws IOException {
        return MojoUtils.checksum(path.toFile());
    }

    private static class Change implements AutoCloseable {
        final Path file;
        final byte[] original;

        public Change(Path file, String change) {
            this.file = file;

            try {
                original = Files.readAllBytes(file);
            } catch (IOException ex) {
                throw new RuntimeException("Could not read file " + file);
            }

            String text = new String(original, StandardCharsets.UTF_8) + change;

            write(file, text.getBytes(StandardCharsets.UTF_8));
        }

        private void write(Path file, byte[] data) {
            try {
                Files.write(file, data);
            } catch (IOException ex) {
                throw new RuntimeException("Could not write file " + file);
            }
        }

        public static Change of(Path file, String change) {
            return new Change(file, change);
        }

        public static Change of(Path file) {
            return new Change(file, "\n");
        }

        @Override
        public void close() {
            write(file, original);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:background="@android:color/transparent"
    android:layout_width="80.0dip"
    android:layout_height="80.0dip"
    android:orientation="vertical"
    android:gravity="center"
  	xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageView
        android:id="@+id/ewan_social_shareboard_image"
        android:layout_width="60.0dip"
        android:layout_height="60.0dip"
        android:layout_marginTop="15.0dip"
        android:src="@drawable/ewan_social_tx_on"
        android:scaleType="fitXY"
        android:layout_centerHorizontal="true" />
    <TextView
        android:textSize="13.0sp"
        android:gravity="center"
        android:id="@+id/ewan_social_shareboard_pltform_name"
        android:layout_width="wrap_content"
        android:layout_height="20.0dip"
        android:layout_marginLeft="2.0dip"
        android:layout_marginRight="2.0dip"
        android:layout_marginBottom="4.0dip"
        android:singleLine="true"
        android:textColor="@color/ewan_social_black"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />
</LinearLayout>


text:
![Bitwise](https://s9.postimg.org/7lk98rhpb/logo.png)

A programming language that only uses binary operations.

## Bitwise in a nutshell

*Are you fed up with normal programming languages?*

*Are you sick of normal arithmetical operators?*

*Do you long for a programming language that takes 15 lines of code to add up 2 numbers?*
#### Then Bitwise is the language for you!

## Features

Bitwise consists of a few logical operators (`^`,`!`,`&`, etc.), some basic input/output, a few variables, and some control structures. And that's about it. Apart from input and output, all calculation must be done with binary. View the docs at [docs/main.md](docs/main.md).

## Running files

Running Bitwise files depends on whether you are using the python source version, or the compiled release.

### Release

The installer in the release gives the option to associate the `.bit` extension with bitwise.
However, if this option was not checked, if the portable version is being used,
or if you simply prefer the command line,
this command should be used:

    bitwise run PROGRAM

`PROGRAM` should be replaced with the path or name of the bitwise program you wish to run.
If `bitwise` is not a recognised command, replace it with the path of `bitwise.exe`.

### Python Source

To run a bitwise file with python, use this command:

    python bitwise.py PROGRAM

If not run from the bitwise folder, replace `bitwise.py` with the full (or relative path of the `bitwise.py` file).

Equally, if python is not in your `%PATH%` (i.e. not a valid command), replace `python` with the path of your `python.exe`.

`PROGRAM` should be replaced with the path or name of the bitwise program you wish to run.

## Copyright notice - Icons

Icons made by [Freepik](http://www.freepik.com) from [www.flaticon.com](http://www.flaticon.com) are licensed by [CC 3.0 BY](http://creativecommons.org/licenses/by/3.0/)


text:
<?php

/**
 * Gateway URL config field backend model
 *
 * @category    Mage
 * @package     Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Adminhtml_Model_System_Config_Backend_Gatewayurl extends  Mage_Core_Model_Config_Data
{
    /**
     * Before save processing
     *
     * @throws Mage_Core_Exception
     * @return Mage_Adminhtml_Model_System_Config_Backend_Gatewayurl
     */
    protected function _beforeSave()
    {
        if ($this->getValue()) {
            $parsed = parse_url($this->getValue());
            if (!isset($parsed['scheme']) || (('https' != $parsed['scheme']) && ('http' != $parsed['scheme']))) {
                Mage::throwException(Mage::helper('core')->__('Invalid URL scheme.'));
            }
        }

        return $this;
    }
}


text: package prebuild


text:
<?xml version="1.0"?>
<System name="Not">
  <Has name="server" value="/"/>
  <Has name="title" value="Not"/>
  <Has name="version" value="0.0.0"/>
  <Function name="POST_not">
    <Has name="operation" value="POST"/>
    <Has name="path" value="/not"/>
    <Input type="query">
      <VarSet name="param0">
        <Has name="paramName" value="param0"/>
        <Var name="Defined">
          <Has name="style" value="form"/>
          <Value name="Yes" property="param0"/>
          <Value name="No"/>
        </Var>
        <Var name="Type" when="param0">
          <Value name="boolean" property="param0Value"/>
          <Value name="null" failure="true"/>
          <Value name="Not boolean" failure="true"/>
        </Var>
        <Var name="Value" when="param0Value">
          <Value name="true" failure="true"/>
          <Value name="false"/>
        </Var>
      </VarSet>
    </Input>
  </Function>
</System>


text:
<#
	.Synopsis
	Restarts a windows service, with settings for wait-time for verification and repeated retries.

	.Example
	Restart-MonitoredService.ps1 -ServiceName "spooler"

	.Example
	Restart-MonitoredService.ps1 -ServiceName "spooler" -Delay 30

	.Example
	Restart-MonitoredService.ps1 -ServiceName "spooler" -Delay 30 -MaxRepeatCount 3 -RepeatIntervalSeconds 10
#>
param(
	# Name of service (not display name)
	[Parameter(Mandatory=$true)][string] $ServiceName,
	[int] $Delay = 0,
	[int] $MaxRepeatCount = 0,
	[int] $RepeatIntervalSeconds = 10,
	[string] $omAlertId,
	[switch] $Debuglogging
)

function Get-TimeStamp
{
	[string] $timeStamp = Get-Date -Format o
	Return $timeStamp
}

function Write-SCOMEvent
{
	param(
		[Parameter(Mandatory=$true)][string] $LogMessage,
		[ValidateSet(0,1,2)][int] $LogSeverity,
		[ValidateRange(0,20000)][int] $LogEventId
	)

	[string] $ScriptName = "Restart-MonitoredService.ps1"

	$omApi = New-Object -ComObject "MOM.ScriptAPI"
	$omApi.LogScriptEvent($ScriptName,$LogEventId,$LogSeverity,$LogMessage)
	$omApi = $null
}

function Test-ServiceExist ($ServiceName) {
	if (!(Get-Service -Name $ServiceName)) {
		return $false
	} else {
		return $true
	}
}

function Start-ServiceAndWait ([string] $ServiceName, [int] $WaitSeconds)
{
	Write-SCOMTaskLog -Message "Attempting to restart $ServiceName" -ElapsedSeconds $timer.Elapsed.TotalSeconds
	Write-SCOMEvent -LogMessage "Attempting to restart $ServiceName" -LogSeverity 0 -LogEventId 10101
	Restart-Service -Name $ServiceName
	Write-SCOMTaskLog -Message "Waiting for $WaitSeconds seconds to verify service state..." -ElapsedSeconds $timer.Elapsed.TotalSeconds
	Write-SCOMEvent -LogMessage "Waiting for $WaitSeconds seconds to verify `"$ServiceName`" state..." -LogSeverity 0 -LogEventId 10101
	Start-Sleep -Seconds $WaitSeconds
	$serviceObject = Get-Service -Name $ServiceName
	return [string] $serviceObject.Status
}

function Restart-ServiceWithRepeats ([int] $MaxRepeatCount, [int] $RepeatIntervalSeconds) {
	if ($MaxRepeatCount -gt 0) {
		for ($i = 1; $i -le $MaxRepeatCount; $i++) {
			Write-SCOMTaskLog -Message "Trying again ($i of $MaxRepeatCount)" -ElapsedSeconds $timer.Elapsed.TotalSeconds
			Write-SCOMEvent -LogMessage "Trying to restart `'$ServiceName`' again ($i of $MaxRepeatCount)" -LogSeverity 0 -LogEventId 10101
			[string] $serviceStatus = Start-ServiceAndWait -ServiceName $ServiceName -WaitSeconds $Delay

			if ($serviceStatus -ne "Running") {
				if ($i -eq $MaxRepeatCount) {
					Write-SCOMTaskLog -Message "$ServiceName is still not running. This was the last attempt!" -ElapsedSeconds $timer.Elapsed.TotalSeconds
					Write-SCOMEvent -LogMessage "`'$ServiceName`' is still not running. This was the last attempt!" -LogSeverity 0 -LogEventId 10101
					Write-SCOMEvent -LogMessage "Failed to recover service `'$ServiceName`' after $MaxRepeatCount attempts!" -LogSeverity 1 -LogEventId 10100
				} else {
					Write-SCOMTaskLog -Message "$ServiceName is still not running, waiting $RepeatIntervalSeconds before next try..." -ElapsedSeconds $timer.Elapsed.TotalSeconds
					Write-SCOMEvent -LogMessage "`'$ServiceName`' is still not running, waiting $RepeatIntervalSeconds before next try..." -LogSeverity 0 -LogEventId 10101
				}
				Start-Sleep -Seconds $RepeatIntervalSeconds
			} else {
				# Service has started and has been running for $Delay seconds
				$i = $MaxRepeatCount
				Write-SCOMTaskLog -Message "$ServiceName is now running..." -ElapsedSeconds $timer.Elapsed.TotalSeconds
				Write-SCOMEvent -LogMessage "`'$ServiceName`' is now running!" -LogSeverity 0 -LogEventId 10101
			}
		}
	}
}

function Write-SCOMTaskLog ([string]$Message, [single]$ElapsedSeconds = 0)
{
     Write-Host ("{0}`t{1:N2}`t{2}" -f (Get-TimeStamp),$ElapsedSeconds,$Message)
}

function Main () {
	Write-SCOMTaskLog -Message "Starting Advanced Recovery Script" -ElapsedSeconds 0
	$timer = [System.Diagnostics.Stopwatch]::StartNew()

	if ((Test-ServiceExist -ServiceName $ServiceName) -eq $false) {
		Write-SCOMTaskLog -Message "$ServiceName - No such service exists on the system." -ElapsedSeconds $timer.Elapsed.TotalSeconds
	} else {
		[string] $serviceStatus = Start-ServiceAndWait $ServiceName -WaitSeconds $Delay

		if ($serviceStatus -ne "Running") {
			Write-SCOMTaskLog -Message "$ServiceName is not running..." -ElapsedSeconds $timer.Elapsed.TotalSeconds
			Restart-ServiceWithRepeats -MaxRepeatCount $MaxRepeatCount -RepeatIntervalSeconds $RepeatIntervalSeconds
		} else {
			Write-SCOMTaskLog -Message "$ServiceName is running..." -ElapsedSeconds $timer.Elapsed.TotalSeconds
		}
	}
	$timer.Stop()
}

Main


text:
package org.apache.druid.indexer.partitions;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import org.apache.druid.jackson.DefaultObjectMapper;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.timeline.partition.HashPartitionFunction;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;

import java.util.Collections;
import java.util.List;
import java.util.Map;

public class HashedPartitionsSpecTest
{
  private static final ObjectMapper JSON_MAPPER = new DefaultObjectMapper();

  @Test
  public void testDefaultValues()
  {
    final HashedPartitionsSpec defaultSpec = HashedPartitionsSpec.defaultSpec();
    Assert.assertEquals(Collections.emptyList(), defaultSpec.getPartitionDimensions());
    Assert.assertEquals(HashPartitionFunction.MURMUR3_32_ABS, defaultSpec.getPartitionFunction());
    Assert.assertNull(defaultSpec.getNumShards());
    Assert.assertEquals(PartitionsSpec.DEFAULT_MAX_ROWS_PER_SEGMENT, defaultSpec.getMaxRowsPerSegment().intValue());
  }

  @Test
  public void havingTargetRowsPerSegmentOnly()
  {
    final HashedPartitionsSpec hadoopHashedPartitionsSpec = jsonReadWriteRead(
        "{"
        + "   \"targetRowsPerSegment\":100,"
        + "   \"type\":\"hashed\""
        + "}"
    );

    Assert.assertTrue("isDeterminingPartitions", hadoopHashedPartitionsSpec.needsDeterminePartitions(true));

    Assert.assertNotNull(hadoopHashedPartitionsSpec.getMaxRowsPerSegment());
    Assert.assertEquals(
        "getMaxRowsPerSegment",
        100,
        hadoopHashedPartitionsSpec.getMaxRowsPerSegment().intValue()
    );
    Assert.assertNull(hadoopHashedPartitionsSpec.getNumShards());
    Assert.assertEquals(
        "getPartitionDimensions",
        ImmutableList.of(),
        hadoopHashedPartitionsSpec.getPartitionDimensions()
    );
  }

  @Test
  public void havingNumShardsOnly()
  {
    final HashedPartitionsSpec hadoopHashedPartitionsSpec = jsonReadWriteRead(
        "{"
        + "   \"type\":\"hashed\","
        + "   \"numShards\":2"
        + "}"
    );

    Assert.assertFalse("isDeterminingPartitions", hadoopHashedPartitionsSpec.needsDeterminePartitions(true));

    Assert.assertNull(
        "getMaxRowsPerSegment",
        hadoopHashedPartitionsSpec.getMaxRowsPerSegment()
    );

    Assert.assertNotNull(hadoopHashedPartitionsSpec.getNumShards());
    Assert.assertEquals(
        "shardCount",
        2,
        hadoopHashedPartitionsSpec.getNumShards().intValue()
    );

    Assert.assertEquals(
        "getPartitionDimensions",
        ImmutableList.of(),
        hadoopHashedPartitionsSpec.getPartitionDimensions()
    );
  }

  @Test
  public void havingIncompatiblePropertiesIsForbidden()
  {
    final String targetRowsPerSegment = DimensionBasedPartitionsSpec.TARGET_ROWS_PER_SEGMENT;
    final String targetPartitionSize = DimensionBasedPartitionsSpec.TARGET_PARTITION_SIZE;
    final String maxRowsPerSegment = PartitionsSpec.MAX_ROWS_PER_SEGMENT;
    final String numShards = HashedPartitionsSpec.NUM_SHARDS;

    Multimap<String, String> incompatiblePairs = ImmutableMultimap.<String, String>builder()
        .put(targetRowsPerSegment, targetPartitionSize)
        .put(targetRowsPerSegment, maxRowsPerSegment)
        .put(targetRowsPerSegment, numShards)
        .put(targetPartitionSize, maxRowsPerSegment)
        .put(targetPartitionSize, numShards)
        .put(maxRowsPerSegment, numShards)
        .build();

    for (Map.Entry<String, String> test : incompatiblePairs.entries()) {
      String first = test.getKey();
      String second = test.getValue();
      String reasonPrefix = first + "/" + second;

      String json = "{"
                    + "\"type\":\"hashed\""
                    + ",\"" + first + "\":100"
                    + ",\"" + second + "\":100"
                    + "}";
      try {
        jsonReadWriteRead(json);
        Assert.fail(reasonPrefix + " did not throw exception");
      }
      catch (RuntimeException e) {
        final String expectedMessage = StringUtils.format(
            "At most one of [Property{name='%s', value=100}] or [Property{name='%s', value=100}] must be present",
            first,
            second
        );
        Assert.assertThat(
            reasonPrefix + " has wrong failure message",
            e.getMessage(),
            CoreMatchers.containsString(expectedMessage)
        );
      }
    }
  }

  @Test
  public void defaults()
  {
    final HashedPartitionsSpec spec = jsonReadWriteRead("{\"type\":\"hashed\"}");
    Assert.assertNotNull(spec.getMaxRowsPerSegment());
    Assert.assertEquals(PartitionsSpec.DEFAULT_MAX_ROWS_PER_SEGMENT, spec.getMaxRowsPerSegment().intValue());
    Assert.assertNull(spec.getNumShards());
    Assert.assertEquals(Collections.emptyList(), spec.getPartitionDimensions());
  }

  @Test
  public void handlesHistoricalNull()
  {
    String json = "{"
                  + "\"type\":\"hashed\""
                  + ",\"targetRowsPerSegment\":" + PartitionsSpec.HISTORICAL_NULL
                  + ",\"numShards\":" + PartitionsSpec.HISTORICAL_NULL
                  + "}";
    final HashedPartitionsSpec spec = jsonReadWriteRead(json);
    Assert.assertNotNull(spec.getMaxRowsPerSegment());
    Assert.assertEquals(PartitionsSpec.DEFAULT_MAX_ROWS_PER_SEGMENT, spec.getMaxRowsPerSegment().intValue());
    Assert.assertNull(spec.getNumShards());
    Assert.assertEquals(Collections.emptyList(), spec.getPartitionDimensions());
  }

  @Test
  public void failsIfNotPositive()
  {
    List<String> properties = ImmutableList.of(
        DimensionBasedPartitionsSpec.TARGET_ROWS_PER_SEGMENT,
        DimensionBasedPartitionsSpec.TARGET_PARTITION_SIZE,
        PartitionsSpec.MAX_ROWS_PER_SEGMENT,
        HashedPartitionsSpec.NUM_SHARDS
    );

    for (String property : properties) {
      String json = "{"
                    + "\"type\":\"hashed\""
                    + ",\"" + property + "\":0"
                    + "}";
      try {
        jsonReadWriteRead(json);
        Assert.fail(property + " did not throw exception");
      }
      catch (RuntimeException e) {
        String expectedMessage = property + "[0] should be positive";
        Assert.assertThat(
            property + " has wrong failure message",
            e.getMessage(),
            CoreMatchers.containsString(expectedMessage)
        );
      }
    }
  }

  @Test
  public void backwardCompatibleWithTargetPartitionSize()
  {
    String json = "{"
                  + "\"type\":\"hashed\""
                  + ",\"targetPartitionSize\":100"
                  + "}";
    HashedPartitionsSpec hadoopHashedPartitionsSpec = jsonReadWriteRead(json);

    Assert.assertNotNull(hadoopHashedPartitionsSpec.getMaxRowsPerSegment());
    Assert.assertEquals(
        "getMaxRowsPerSegment",
        100,
        hadoopHashedPartitionsSpec.getMaxRowsPerSegment().intValue()
    );
  }

  @Test
  public void backwardCompatibleWithMaxRowsPerSegment()
  {
    String json = "{"
                  + "\"type\":\"hashed\""
                  + ",\"maxRowsPerSegment\":100"
                  + "}";
    HashedPartitionsSpec hadoopHashedPartitionsSpec = jsonReadWriteRead(json);

    Assert.assertNotNull(hadoopHashedPartitionsSpec.getMaxRowsPerSegment());
    Assert.assertEquals(
        "getMaxRowsPerSegment",
        100,
        hadoopHashedPartitionsSpec.getMaxRowsPerSegment().intValue()
    );
  }

  private static HashedPartitionsSpec jsonReadWriteRead(String s)
  {
    try {
      byte[] jsonBytes = JSON_MAPPER.writeValueAsBytes(JSON_MAPPER.readValue(s, PartitionsSpec.class));
      PartitionsSpec partitionsSpec = JSON_MAPPER.readValue(jsonBytes, PartitionsSpec.class);
      Assert.assertTrue("partitionsSpec", partitionsSpec instanceof HashedPartitionsSpec);
      return (HashedPartitionsSpec) partitionsSpec;
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}


text:
<!doctype>

Tree removal test

Content


text:
/*
 * Curves.h
 *
 *  Created on: 2 Jun 2015
 *      Author: jeremy
 */

#ifndef SOURCE_DRUMKIT_CURVES_H_
#define SOURCE_DRUMKIT_CURVES_H_

#include <vector>
#include <algorithm>
#include <numeric>
#include <map>
#include <cmath>

namespace DrumKit
{

	class Curves
	{

	public:

		static void Linear(std::vector<float>& curve);
		static void Exponential(std::vector<float>& curve);

		static const size_t numSamples = 2048;

	private:

		Curves(){};
		virtual ~Curves(){};

		static void Normalise(std::vector<float>& curve);

	};

}

#endif /* SOURCE_DRUMKIT_CURVES_H_ */


text:
package org.jasig.cas;

import org.jasig.cas.authentication.AuthenticationManager;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;

/**
 * @author Scott Battaglia

 * @since 3.0
 */
@ContextConfiguration(locations = {
    "/core-context.xml"
})
public abstract class AbstractCentralAuthenticationServiceTest extends AbstractJUnit4SpringContextTests {

    @Autowired(required = true)
    private CentralAuthenticationService centralAuthenticationService;

    @Autowired(required = true)
    private TicketRegistry ticketRegistry;

    @Autowired(required = true)
    private AuthenticationManager authenticationManager;

    public AuthenticationManager getAuthenticationManager() {
        return this.authenticationManager;
    }

    public CentralAuthenticationService getCentralAuthenticationService() {
        return this.centralAuthenticationService;
    }

    public void setCentralAuthenticationService(final CentralAuthenticationService centralAuthenticationService) {
        this.centralAuthenticationService = centralAuthenticationService;
    }

    public TicketRegistry getTicketRegistry() {
        return this.ticketRegistry;
    }

}


text:
<?php

namespace Doctrine\Tests\ODM\PHPCR\Functional;

use Doctrine\ODM\PHPCR\DocumentRepository;
use Doctrine\ODM\PHPCR\Mapping\Annotations as PHPCRODM;
use Doctrine\Common\Proxy\Proxy;
use Doctrine\Tests\ODM\PHPCR\PHPCRFunctionalTestCase;
use Doctrine\Tests\Models\Blog\User as BlogUser;
use Doctrine\Tests\Models\Blog\Post;
use Doctrine\Tests\Models\Blog\Comment;
use PHPCR\Util\PathHelper;
use PHPCR\Util\NodeHelper;

/**
 * @group functional
 */
class QueryBuilderTest extends PHPCRFunctionalTestCase
{
    /**
     * @var \Doctrine\ODM\PHPCR\DocumentManager
     */
    protected $dm;

    /**
     * @var \PHPCR\NodeInterface
     */
    protected $node;

    public function setUp()
    {
        $this->dm = $this->createDocumentManager();
        $this->node = $this->resetFunctionalNode($this->dm);
        $session = $this->dm->getPhpcrSession();

        // comment
        // post
        // user
        NodeHelper::createPath($session, '/functional/user');
        NodeHelper::createPath($session, '/functional/post');

        $user = new BlogUser;
        $user->id = '/functional/user/dtl';
        $user->name = 'daniel';
        $user->username = 'dtl';
        $user->status = 'query_builder';
        $this->dm->persist($user);

        $user = new BlogUser;
        $user->id = '/functional/user/js';
        $user->username = 'js';
        $user->name = 'johnsmith';
        $user->status = 'query_builder';
        $this->dm->persist($user);

        $user = new BlogUser;
        $user->id = '/functional/user/js2';
        $user->name = 'johnsmith';
        $user->username = 'js2';
        $user->status = 'another_johnsmith';
        $this->dm->persist($user);

        $post = new Post;
        $post->id = '/functional/post/post_1';
        $post->title = 'Post 2';
        $post->username = 'dtl';
        $this->dm->persist($post);

        $comment1 = new Comment;
        $comment1->id = '/functional/post/post_1/comment_1';
        $comment1->title = 'Comment 1';
        $this->dm->persist($comment1);

        $comment2 = new Comment;
        $comment2->id = '/functional/post/post_1/comment_2';
        $comment2->title = 'Comment 1';
        $this->dm->persist($comment2);

        $reply1 = new Comment;
        $reply1->id = '/functional/post/post_1/comment_1/reply_1';
        $reply1->title = 'Reply to Comment 1';
        $this->dm->persist($reply1);

        $post = new Post;
        $post->id = '/functional/post/post_2';
        $post->title = 'Post 2';
        $post->username = 'dtl';
        $this->dm->persist($post);

        $comment3 = new Comment;
        $comment3->id = '/functional/post/post_2/comment_3';
        $comment3->title = 'Comment 3';
        $this->dm->persist($comment3);

        $post3 = new Post;
        $post3->id = '/functional/post/post_3';
        $post3->title = 'Post 3';
        $post3->username = 'js';
        $this->dm->persist($post3);

        $this->dm->flush();
    }

    protected function createQb()
    {
        $qb = $this->dm->createQueryBuilder();
        return $qb;
    }

    public function testFrom()
    {
        $qb = $this->createQb();
        $qb->from()->document('Doctrine\Tests\Models\Blog\User', 'a');

        // add where to stop rouge documents that havn't been stored in /functional/ from appearing.
        $qb->where()->eq()->field('a.status')->literal('query_builder')->end();

        $res = $qb->getQuery()->execute();
        $this->assertCount(2, $res);
    }

    /**
     * @depends testFrom
     */
    public function testComparison()
    {
        $qb = $this->createQb();
        $qb->from()->document('Doctrine\Tests\Models\Blog\User', 'a');
        $qb->where()
            ->eq()
                ->field('a.username')
                ->literal('Not Exist')
            ->end();

        $res = $qb->getQuery()->execute();
        $this->assertCount(0, $res);

        $qb = $this->createQb();
        $qb->from()->document('Doctrine\Tests\Models\Blog\User', 'a');
        $qb->where()
            ->eq()
                ->field('a.username')
                ->literal('dtl')
            ->end();

        $res = $qb->getQuery()->execute();
        $this->assertCount(1, $res);
    }

    /**
     */
    public function testComposite()
    {
        $qb = $this->createQb();
        $qb->from()->document('Doctrine\Tests\Models\Blog\User', 'a');
        $qb->where()
            ->orX()
                ->eq()->field('a.username')->literal('dtl')->end()
                ->eq()->field('a.username')->literal('js')->end()
            ->end();

        $res = $qb->getQuery()->execute();

        switch ($qb->getQuery()->getLanguage()) {
            case 'JCR-SQL2':
                $query = "SELECT * FROM [nt:unstructured] AS a WHERE ((a.username = 'dtl' OR a.username = 'js') AND (a.[phpcr:class] = 'Doctrine\Tests\Models\Blog\User' OR a.[phpcr:classparents] = 'Doctrine\Tests\Models\Blog\User'))";
                break;
            case 'sql':
                $query = "SELECT s FROM nt:unstructured AS a WHERE (a.username = 'dtl' OR a,username = 'js')";
                break;
            default:
                $this->fail('Unexpected query language:'.$qb->getQuery()->getLanguage());
        }

        $this->assertEquals($query, $qb->__toString());
        $this->assertCount(2, $res);

        $qb->andWhere()
            ->eq()->field('a.name')->literal('foobar');

        switch ($qb->getQuery()->getLanguage()) {
            case 'JCR-SQL2':
                $query = "SELECT * FROM [nt:unstructured] AS a WHERE (((a.username = 'dtl' OR a.username = 'js') AND a.name = 'foobar') AND (a.[phpcr:class] = 'Doctrine\Tests\Models\Blog\User' OR a.[phpcr:classparents] = 'Doctrine\Tests\Models\Blog\User'))";
                break;
            case 'sql':
                $this->markTestIncomplete('Not testing SQL for sql query language');
                break;
            default:
                $this->fail('Unexpected query language:'.$qb->getQuery()->getLanguage());
        }
        $this->assertEquals($query, $qb->__toString());
        $res = $qb->getQuery()->execute();
        $this->assertCount(0, $res);

        $qb->orWhere()
            ->eq()->field('a.name')->literal('johnsmith');

        $res = $qb->getQuery()->execute();

        switch ($qb->getQuery()->getLanguage()) {
            case 'JCR-SQL2':
                $query = "SELECT * FROM [nt:unstructured] AS a WHERE ((((a.username = 'dtl' OR a.username = 'js') AND a.name = 'foobar') OR a.name = 'johnsmith') AND (a.[phpcr:class] = 'Doctrine\Tests\Models\Blog\User' OR a.[phpcr:classparents] = 'Doctrine\Tests\Models\Blog\User'))";
                break;
            case 'sql':
                $this->markTestIncomplete('Not testing SQL for sql query language');
                break;
            default:
                $this->fail('Unexpected query language:'.$qb->getQuery()->getLanguage());
        }

        $this->assertEquals($query, $qb->__toString());
        $this->assertCount(2, $res);
    }

    /**
     * @depends testFrom
     */
    public function testOrderBy()
    {
        $qb = $this->createQb();
        $qb->from()->document('Doctrine\Tests\Models\Blog\User', 'a');
        $qb->where()->eq()->field('a.status')->literal('query_builder')->end();
        $qb->orderBy()->asc()->field('a.username')->end();

        $res = $qb->getQuery()->execute();
        $this->assertCount(2, $res);
        $this->assertEquals('dtl', $res->first()->username);

        $qb->orderBy()->desc()->field('a.username')->end();

        $res = $qb->getQuery()->execute();
        $this->assertCount(2, $res);
        $this->assertEquals('js', $res->first()->username);
    }

    /**
     * Removes jcr:primaryType from row values,
     * Jackrabbit does not return this, but doctrinedbal does.
     */
    protected function cleanValues($values)
    {
        if (isset($values['a.jcr:primaryType'])) {
            unset($values['a.jcr:primaryType']);
        }

        return $values;
    }

    public function testSelect()
    {
        // select one property
        $qb = $this->createQb();
        $qb->from()->document('Doctrine\Tests\Models\Blog\User', 'a');
        $qb->select()->field('a.username');
        $qb->where()
            ->eq()
                ->field('a.username')
                ->literal('dtl')
            ->end();

        $result = $qb->getQuery()->getPhpcrNodeResult();
        $rows = $result->getRows();
        $values = $rows->current()->getValues('a');
        $values = $this->cleanValues($values);

        $this->assertEquals(1, $rows->count());

        switch ($qb->getQuery()->getLanguage()) {
        case 'JCR-SQL2':
                $this->assertEquals(array('a'), $result->getSelectorNames());
                $this->assertEquals(array('a.username' => 'dtl'), $values);
                break;
            case 'sql':
                $this->markTestIncomplete('Not testing SQL for sql query language');
                break;
            default:
                $this->fail('Unexpected query language:'.$qb->getQuery()->getLanguage());
        }

        $qb->addSelect()->field('a.name');

        $result = $qb->getQuery()->getPhpcrNodeResult();
        $rows = $result->getRows();
        $values = $rows->current()->getValues('a');
        $values = $this->cleanValues($values);

        switch ($qb->getQuery()->getLanguage()) {
            case 'JCR-SQL2':
                $this->assertEquals(array('a'), $result->getSelectorNames());
                $this->assertEquals(array(
                    'a.username' => 'dtl',
                    'a.name' => 'daniel',
                ), $values);
                break;
            case 'sql':
                $this->markTestIncomplete('Not testing SQL for sql query language');
                break;
            default:
                $this->fail('Unexpected query language:'.$qb->getQuery()->getLanguage());
        }

        // select overwrite
        $qb->select()->field('a.status');
        $rows = $qb->getQuery()->getPhpcrNodeResult()->getRows();
        $values = $rows->current()->getValues();
        $values = $this->cleanValues($values);

        switch ($qb->getQuery()->getLanguage()) {
            case 'JCR-SQL2':
                $this->assertEquals(array(
                    'a.status' => 'query_builder',
                ), $values);
                break;
            case 'sql':
                $this->markTestIncomplete('Not testing SQL for sql query language');
                break;
            default:
                $this->fail('Unexpected query language:'.$qb->getQuery()->getLanguage());
        }
    }

    /**
     * @depends testFrom
     */
    public function getTextSearches()
    {
        return array(
            array('name', 'johnsmith', 2),
            array('username', 'dtl', 1),
        );
    }

    /**
     * @dataProvider getTextSearches
     */
    public function testTextSearch($field, $search, $resCount)
    {
        $qb = $this->createQb();
        $qb->from()->document('Doctrine\Tests\Models\Blog\User', 'a');
        $qb->where()->fullTextSearch('a.'.$field, $search);
        $q = $qb->getQuery();

        $res = $q->execute();

        $this->assertCount($resCount, $res);
    }

    /**
     * @depends testFrom
     */
    public function testDescendant()
    {
        $qb = $this->createQb();
        $qb->from()->document('Doctrine\Tests\Models\Blog\User', 'a');
        $qb->where()->descendant('/functional', 'a')->end();
        $q = $qb->getQuery();
        $res = $q->execute();
        $this->assertCount(3, $res);
    }

    /**
     * @depends testFrom
     */
    public function testSameNode()
    {
        $qb = $this->createQb();
        $qb->from()->document('Doctrine\Tests\Models\Blog\User', 'a');
        $qb->where()->same('/functional/user/dtl', 'a');
        $q = $qb->getQuery();
        $res = $q->execute();

        $this->assertCount(1, $res);
    }

    public function testJoinChildInner()
    {
        $this->setExpectedException('Doctrine\ODM\PHPCR\PHPCRBadMethodCallException', 'not supported yet');

        $qb = $this->createQb();
        $qb->from()
            ->joinInner()
                ->left()->document('Doctrine\Tests\Models\Blog\Comment', 'comment')->end()
                ->right()->document('Doctrine\Tests\Models\Blog\Post', 'post')->end()
                ->condition()->child('comment', 'post')->end()
                ->end();

        $q = $qb->getQuery();
        $res = $q->getPhpcrNodeResult();
        $nodes = $res->getNodes();

        $this->assertCount(3, $nodes);
        $this->assertEquals('/functional/post/post_1/comment_1', $nodes->current()->getPath());
    }

    public function testJoinChildInnerAdd()
    {
        $this->setExpectedException('Doctrine\ODM\PHPCR\PHPCRBadMethodCallException', 'not supported yet');

        $qb = $this->createQb();
        $qb->fromDocument('Doctrine\Tests\Models\Blog\Comment', 'comment');
        $qb->addJoinInner()
            ->right()->document('Doctrine\Tests\Models\Blog\Post', 'post')->end()
            ->condition()->child('comment', 'post');

        $q = $qb->getQuery();
        $res = $q->getPhpcrNodeResult();
        $nodes = $res->getNodes();

        $this->assertCount(3, $nodes);
        $this->assertEquals('/functional/post/post_1/comment_1', $nodes->current()->getPath());
    }

    /**
     * @todo: Not sure how to conclusively test this in difference to testJoinInner
     */
    public function testJoinChildOuterLeft()
    {
        $this->setExpectedException('Doctrine\ODM\PHPCR\PHPCRBadMethodCallException', 'not supported yet');

        $qb = $this->createQb();
        $qb->fromDocument('Doctrine\Tests\Models\Blog\Comment', 'comment');
        $qb->addJoinLeftOuter()
            ->right()->document('Doctrine\Tests\Models\Blog\Post', 'post')->end()
            ->condition()->child('comment', 'post');

        $q = $qb->getQuery();
        $res = $q->getPhpcrNodeResult();
        $nodes = $res->getNodes();

        $this->assertCount(3, $nodes);
        $this->assertEquals('/functional/post/post_1/comment_1', $nodes->current()->getPath());
        $this->assertInstanceOf('Doctrine\Tests\Models\Blog\Comment', $res->current());
    }

    /**
     * @todo: Not sure how to conclusively test this in difference to testJoinInner
     */
    public function testJoinChildOuterRight()
    {
        $this->setExpectedException('Doctrine\ODM\PHPCR\PHPCRBadMethodCallException', 'not supported yet');

        $qb = $this->createQb();
        $qb->fromDocument('Doctrine\Tests\Models\Blog\Comment', 'comment');
        $qb->addJoinRightOuter()
            ->right()->document('Doctrine\Tests\Models\Blog\Post', 'post')->end()
            ->condition()->child('comment', 'post');

        $q = $qb->getQuery();
        $res = $q->execute();

        $this->assertCount(1, $res);
        $this->assertEquals('/functional/post/post_1/comment_1', $res->current()->id);
        $this->assertInstanceOf('Doctrine\Tests\Models\Blog\Comment', $res->current());
    }

    public function testJoinEqui()
    {
        $this->setExpectedException('Doctrine\ODM\PHPCR\PHPCRBadMethodCallException', 'not supported yet');

        $qb = $this->createQb();
        $qb->fromDocument('Doctrine\Tests\Models\Blog\Post', 'post');
        $qb->addJoinInner()
            ->right()->document('Doctrine\Tests\Models\Blog\User', 'user')->end()
            ->condition()->equi('post.username', 'user.username');

        $qb->where()->eq()->field('user.name')->literal('daniel');

        $q = $qb->getQuery();
        $res = $q->execute();

        $this->assertCount(1, $res);
        $this->assertInstanceOf('Doctrine\Tests\Models\Blog\Post', $res->current());
    }
}


text:
package ca.corefacility.bioinformatics.irida.ria.web.users.dto;

/**
 * Data transfer object for creating a new user account.
 */
public class UserCreateRequest {
	private String username;
	private String firstName;
	private String lastName;
	private String email;
	private String phoneNumber;
	private String role;
	private String locale;
	private boolean activate;
	private String password;

	public UserCreateRequest(String username, String firstName, String lastName, String email, String phoneNumber,
			String role, String locale, boolean activate, String password) {
		this.username = username;
		this.firstName = firstName;
		this.lastName = lastName;
		this.email = email;
		this.phoneNumber = phoneNumber;
		this.role = role;
		this.locale = locale;
		this.activate = activate;
		this.password = password;
	}

	public String getUsername() {
		return username;
	}

	public String getFirstName() {
		return firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public String getEmail() {
		return email;
	}

	public String getPhoneNumber() {
		return phoneNumber;
	}

	public String getRole() {
		return role;
	}

	public String getLocale() {
		return locale;
	}

	public boolean getActivate() {
		return activate;
	}

	public String getPassword() {
		return password;
	}

}


text:
import qualified SDL.Mixer as Mix
import qualified SDL

import Control.Monad      (when)
import Data.Default.Class (def)
import System.Environment (getArgs)
import System.Exit        (exitFailure)

main :: IO ()
main = do
  -- read arguments
  fileName <- do
    args <- getArgs
    case args of
      (arg:_) -> return arg
      _ -> do
        putStrLn "Usage: cabal run sdl2-mixer-basic <sound filename>"
        exitFailure

  -- initialize libraries
  SDL.initialize [SDL.InitAudio]
  Mix.initialize [Mix.InitMP3]

  -- open device
  Mix.openAudio def 256

  -- open file
  sound <- Mix.load fileName

  -- play file
  Mix.play sound

  -- wait until finished
  whileTrueM $ Mix.playing Mix.AllChannels

 -- free resources
  Mix.free sound

  -- close device
  Mix.closeAudio

  -- quit
  Mix.quit
  SDL.quit

whileTrueM :: Monad m => m Bool -> m ()
whileTrueM cond = do
  loop <- cond
  when loop $ whileTrueM cond


text:
layout: page
title: Spencer Angel Industries Conference
date: 2016-05-24
author: Scott Stewart
tags: weekly links, java
status: published
summary: Nunc felis massa, varius quis est eu, sagittis.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 04/26/2019
  endDate: 04/29/2019
  ctyhocn: LRDTXHX
  groupCode: SAIC
published: true
---
Nulla sit amet felis tellus. Mauris tristique nisl elit, sed tristique orci rutrum at. Pellentesque maximus vel dolor commodo porta. Ut gravida mi ac orci ultricies semper. Integer bibendum tortor et vulputate imperdiet. Aenean volutpat, diam sit amet maximus tristique, quam arcu blandit ante, eget ullamcorper felis risus et mi. Vestibulum sed molestie justo. Nullam sed ultricies leo. Cras vel quam fermentum, lobortis quam vitae, molestie dolor. Aliquam erat volutpat. Suspendisse nec elit gravida, varius magna ac, consequat turpis.

1 Vivamus pretium velit quis tellus fermentum pretium
1 Aenean pellentesque sem in metus posuere faucibus.

Nam sed felis et lacus aliquam vestibulum. Mauris condimentum ullamcorper sapien, nec cursus turpis vulputate vel. Phasellus vulputate quam non dignissim vestibulum. Nam sodales varius tellus, eu dapibus arcu varius at. In vestibulum nec risus nec faucibus. Phasellus non blandit lacus. Nunc eleifend velit et ex ultrices, sit amet consequat risus pharetra. Proin et tellus sapien. Praesent pharetra ex at lacinia facilisis. Donec eu nisl imperdiet, vulputate neque at, tristique enim. Nulla faucibus, velit vitae imperdiet mollis, mauris lacus laoreet ante, at commodo urna dui id purus.


text:
package com.kafka.scala;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;

/**
 * The Class KafkaMailConsumer.
 *
 * @author Abhishek Sharma
 */
public class KafkaConsumer extends Thread {
    private final ConsumerConnector consumer;
    private final String topic;

    public KafkaConsumer(String topic) {
        consumer = kafka.consumer.Consumer.createJavaConsumerConnector(createConsumerConfig());
        this.topic = topic;
    }

    /**
     * Creates the consumer config.
     *
     * @return the consumer config
     */
    private static ConsumerConfig createConsumerConfig() {
        Properties props = new Properties();
        props.put("zookeeper.connect", KafkaProperties.zkConnect);
        props.put("group.id", KafkaProperties.groupId);
        props.put("zookeeper.session.timeout.ms", "400");
        props.put("zookeeper.sync.time.ms", "200");
        props.put("auto.commit.interval.ms", "1000");

        return new ConsumerConfig(props);

    }

    public void run() {
        Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
        topicCountMap.put(topic, new Integer(1));
        Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumer.createMessageStreams(topicCountMap);
        KafkaStream<byte[], byte[]> stream = consumerMap.get(topic).get(0);
        ConsumerIterator<byte[], byte[]> it = stream.iterator();
        while (it.hasNext())
            System.out.println(new String(it.next().message()));
    }

    public static void main(String[] args) {
        KafkaConsumer consumer = new KafkaConsumer(KafkaProperties.topic);
        consumer.start();
    }
}


text:
<?php

/**
 * Unit test objek DistribusiRecord.
 *
 * @author Andi Malik <andi.malik.notifications@gmail.com>
 */
class DistribusiRecordUnitTest extends PHPUnit_Framework_TestCase {

    private $object = NULL;

    public function setUp() {
        parent::setUp();
        $this->object = new DistribusiRecord;
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::setId()
     * @covers DistribusiRecord::getId()
     * @covers DistribusiRecord::unsetId()
     */
    public function testSetGetUnsetId() {
        $this->assertNull($this->object->getId());

        $this->object->setId(1);
        $this->assertEquals(1, $this->object->getId());

        $this->object->unsetId();
        $this->assertNull($this->object->getId());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::setIdAlokasi()
     * @covers DistribusiRecord::getIdAlokasi()
     * @covers DistribusiRecord::unsetIdAlokasi()
     */
    public function testSetGetUnsetIdAlokasi() {
        $this->assertNull($this->object->getIdAlokasi());

        $this->object->setIdAlokasi(1);
        $this->assertEquals(1, $this->object->getIdAlokasi());

        $this->object->unsetIdAlokasi();
        $this->assertNull($this->object->getIdAlokasi());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::setIdTagihan()
     * @covers DistribusiRecord::getIdTagihan()
     * @covers DistribusiRecord::unsetIdTagihan()
     */
    public function testSetGetUnsetIdTagihan() {
        $this->assertNull($this->object->getIdTagihan());

        $this->object->setIdTagihan(1);
        $this->assertEquals(1, $this->object->getIdTagihan());

        $this->object->unsetIdTagihan();
        $this->assertNull($this->object->getIdTagihan());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::setNilai()
     * @covers DistribusiRecord::getNilai()
     * @covers DistribusiRecord::unsetNilai()
     */
    public function testSetGetUnsetNilai() {
        $this->assertNull($this->object->getNilai());

        $this->object->setNilai(1);
        $this->assertEquals(1, $this->object->getNilai());

        $this->object->unsetNilai();
        $this->assertNull($this->object->getNilai());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::setPDO()
     * @covers DistribusiRecord::getPDO()
     * @covers DistribusiRecord::unsetPDO()
     */
    public function testSetGetUnsetPdo() {
        $mockPDO = $this->getMock("MockPDO");
        $this->assertNull($this->object->getPDO());

        $this->object->setPDO($mockPDO);
        $this->assertSame($mockPDO, $this->object->getPDO());

        $this->object->unsetPDO();
        $this->assertNull($this->object->getPDO());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::persist()
     */
    public function testPersistReturnFalseJikaPdoTidakTerpasang() {
        $this->object->unsetPDO();
        $this->_setProperties();
        $this->object->unsetId();

        $this->assertFalse($this->object->persist());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::persist()
     */
    public function testPersistReturnFalseJikaSetAttributePdoGagal() {
        $mockPDO = $this->getMock("MockPDO", array("setAttribute", "errorInfo"));
        $mockPDO->expects($this->any())->method("setAttribute")->with($this->equalTo(PDO::ATTR_ERRMODE), $this->equalTo(PDO::ERRMODE_EXCEPTION))->will($this->returnValue(FALSE));

        $this->object->setPDO($mockPDO);
        $this->_setProperties();
        $this->object->unsetId();

        $this->assertFalse($this->object->persist());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::persist()
     */
    public function testPersistReturnFalseJikaPrepareStatementGagal() {
        $mockPDO = $this->getMock("MockPDO", array("setAttribute", "errorInfo", "prepare"));
        $mockPDO->expects($this->any())->method("setAttribute")->with($this->equalTo(PDO::ATTR_ERRMODE), $this->equalTo(PDO::ERRMODE_EXCEPTION))->will($this->returnValue(TRUE));
        $mockPDO->expects($this->any())->method("prepare")->with($this->isType("string"))->will($this->returnValue(FALSE));

        $this->object->setPDO($mockPDO);
        $this->_setProperties();
        $this->object->unsetId();

        $this->assertFalse($this->object->persist());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::persist()
     */
    public function testPersistReturnFalseJikaEksekusiStatementGagal() {
        $mockPDOStatement = $this->getMock("PDOStatement", array("execute", "closeCursor"));
        $mockPDO = $this->getMock("MockPDO", array("setAttribute", "errorInfo", "prepare"));

        $mockPDOStatement->expects($this->any())->method("execute")->with($this->isType("array"))->will($this->returnValue(FALSE));
        $mockPDO->expects($this->any())->method("setAttribute")->with($this->equalTo(PDO::ATTR_ERRMODE), $this->equalTo(PDO::ERRMODE_EXCEPTION))->will($this->returnValue(TRUE));
        $mockPDO->expects($this->any())->method("prepare")->with($this->isType("string"))->will($this->returnValue($mockPDOStatement));

        $this->object->setPDO($mockPDO);
        $this->_setProperties();
        $this->object->unsetId();

        $this->assertFalse($this->object->persist());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::persist()
     */
    public function testPersistReturnFalseJikaCloseCursorGagal() {
        $mockPDOStatement = $this->getMock("PDOStatement", array("execute", "closeCursor"));
        $mockPDO = $this->getMock("MockPDO", array("setAttribute", "errorInfo", "prepare", "lastInsertId"));

        $mockPDOStatement->expects($this->any())->method("execute")->with($this->isType("array"))->will($this->returnValue(TRUE));
        $mockPDOStatement->expects($this->any())->method("closeCursor")->will($this->returnValue(FALSE));

        $mockPDO->expects($this->any())->method("setAttribute")->with($this->equalTo(PDO::ATTR_ERRMODE), $this->equalTo(PDO::ERRMODE_EXCEPTION))->will($this->returnValue(TRUE));
        $mockPDO->expects($this->any())->method("prepare")->with($this->isType("string"))->will($this->returnValue($mockPDOStatement));

        $this->object->setPDO($mockPDO);
        $this->_setProperties();
        $this->object->unsetId();

        $this->assertFalse($this->object->persist());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::persist()
     */
    public function testPersistReturnFalseJikaLastInsertIdReturn0() {
        $mockPDOStatement = $this->getMock("PDOStatement", array("execute", "closeCursor"));
        $mockPDO = $this->getMock("MockPDO", array("setAttribute", "errorInfo", "prepare", "lastInsertId"));

        $mockPDOStatement->expects($this->any())->method("execute")->with($this->isType("array"))->will($this->returnValue(TRUE));
        $mockPDOStatement->expects($this->any())->method("closeCursor")->will($this->returnValue(TRUE));

        $mockPDO->expects($this->any())->method("setAttribute")->with($this->equalTo(PDO::ATTR_ERRMODE), $this->equalTo(PDO::ERRMODE_EXCEPTION))->will($this->returnValue(TRUE));
        $mockPDO->expects($this->any())->method("prepare")->with($this->isType("string"))->will($this->returnValue($mockPDOStatement));
        $mockPDO->expects($this->any())->method("lastInsertId")->will($this->returnValue("0"));

        $this->object->setPDO($mockPDO);
        $this->_setProperties();
        $this->object->unsetId();

        $this->assertFalse($this->object->persist());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::persist()
     */
    public function testOperasiPersistSukses() {
        $mockPDOStatement = $this->getMock("PDOStatement", array("execute", "closeCursor"));
        $mockPDO = $this->getMock("MockPDO", array("setAttribute", "errorInfo", "prepare", "lastInsertId"));

        $mockPDOStatement->expects($this->any())->method("execute")->with($this->isType("array"))->will($this->returnValue(TRUE));
        $mockPDOStatement->expects($this->any())->method("closeCursor")->will($this->returnValue(TRUE));

        $mockPDO->expects($this->any())->method("setAttribute")->with($this->equalTo(PDO::ATTR_ERRMODE), $this->equalTo(PDO::ERRMODE_EXCEPTION))->will($this->returnValue(TRUE));
        $mockPDO->expects($this->any())->method("prepare")->with($this->isType("string"))->will($this->returnValue($mockPDOStatement));
        $mockPDO->expects($this->any())->method("lastInsertId")->will($this->returnValue("1"));

        $this->object->setPDO($mockPDO);
        $this->_setProperties();
        $this->object->unsetId();

        $this->assertTrue($this->object->persist());
        $this->assertEquals("1", $this->object->getId());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::retrieve()
     */
    public function testRetrieveReturnFalseJikaPdoTidakTerpasang() {
        $this->object->unsetPDO();
        $this->object->setId(1);

        $this->assertFalse($this->object->retrieve());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::retrieve()
     */
    public function testRetrieveReturnFalseJikaSetAttributePdoGagal() {
        $mockPDO = $this->getMock("MockPDO", array("setAttribute", "errorInfo"));
        $mockPDO->expects($this->any())->method("setAttribute")->with($this->equalTo(PDO::ATTR_ERRMODE), $this->equalTo(PDO::ERRMODE_EXCEPTION))->will($this->returnValue(FALSE));

        $this->object->setPDO($mockPDO);
        $this->object->setId(1);

        $this->assertFalse($this->object->retrieve());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::retrieve()
     */
    public function testRetrieveReturnFalseJikaPrepareStatementGagal() {
        $mockPDO = $this->getMock("MockPDO", array("setAttribute", "errorInfo", "prepare"));
        $mockPDO->expects($this->any())->method("setAttribute")->with($this->equalTo(PDO::ATTR_ERRMODE), $this->equalTo(PDO::ERRMODE_EXCEPTION))->will($this->returnValue(TRUE));
        $mockPDO->expects($this->any())->method("prepare")->with($this->isType("string"))->will($this->returnValue(FALSE));

        $this->object->setPDO($mockPDO);
        $this->object->setId(1);

        $this->assertFalse($this->object->retrieve());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::retrieve()
     */
    public function testRetrieveReturnFalseJikaEksekusiStatementGagal() {
        $mockPDOStatement = $this->getMock("PDOStatement", array("execute", "closeCursor"));
        $mockPDO = $this->getMock("MockPDO", array("setAttribute", "errorInfo", "prepare"));

        $mockPDOStatement->expects($this->any())->method("execute")->with($this->isType("array"))->will($this->returnValue(FALSE));
        $mockPDO->expects($this->any())->method("setAttribute")->with($this->equalTo(PDO::ATTR_ERRMODE), $this->equalTo(PDO::ERRMODE_EXCEPTION))->will($this->returnValue(TRUE));
        $mockPDO->expects($this->any())->method("prepare")->with($this->isType("string"))->will($this->returnValue($mockPDOStatement));

        $this->object->setPDO($mockPDO);
        $this->object->setId(1);

        $this->assertFalse($this->object->retrieve());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::retrieve()
     */
    public function testRetrieveReturnFalseJikaFetchGagal() {
        $mockPDOStatement = $this->getMock("PDOStatement", array("execute", "closeCursor", "fetch"));
        $mockPDO = $this->getMock("MockPDO", array("setAttribute", "errorInfo", "prepare"));

        $mockPDOStatement->expects($this->any())->method("execute")->with($this->isType("array"))->will($this->returnValue(TRUE));
        $mockPDOStatement->expects($this->any())->method("fetch")->with($this->equalTo(PDO::FETCH_ASSOC))->will($this->returnValue(FALSE));

        $mockPDO->expects($this->any())->method("setAttribute")->with($this->equalTo(PDO::ATTR_ERRMODE), $this->equalTo(PDO::ERRMODE_EXCEPTION))->will($this->returnValue(TRUE));
        $mockPDO->expects($this->any())->method("prepare")->with($this->isType("string"))->will($this->returnValue($mockPDOStatement));

        $this->object->setPDO($mockPDO);
        $this->object->setId(1);

        $this->assertFalse($this->object->retrieve());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::retrieve()
     */
    public function testRetrieveReturnFalseJikaCloseCursorGagal() {
        $mockPDOStatement = $this->getMock("PDOStatement", array("execute", "closeCursor", "fetch"));
        $mockPDO = $this->getMock("MockPDO", array("setAttribute", "errorInfo", "prepare", "lastInsertId"));

        $mockPDOStatement->expects($this->any())->method("execute")->with($this->isType("array"))->will($this->returnValue(TRUE));
        $mockPDOStatement->expects($this->any())->method("fetch")->with($this->equalTo(PDO::FETCH_ASSOC))->will($this->returnValue(array("id" => 1, "id_alokasi" => 1, "id_tagihan" => 1, "nilai" => 1)));

        $mockPDOStatement->expects($this->any())->method("closeCursor")->will($this->returnValue(FALSE));

        $mockPDO->expects($this->any())->method("setAttribute")->with($this->equalTo(PDO::ATTR_ERRMODE), $this->equalTo(PDO::ERRMODE_EXCEPTION))->will($this->returnValue(TRUE));
        $mockPDO->expects($this->any())->method("prepare")->with($this->isType("string"))->will($this->returnValue($mockPDOStatement));

        $this->object->setPDO($mockPDO);
        $this->object->setId(1);

        $this->assertFalse($this->object->retrieve());
    }

    /**
     * @group unitTest
     * @group recordObject
     * @covers DistribusiRecord::retrieve()
     */
    public function testOperasiRetrieveSukses() {
        $fetchReturnValue = array("id" => 1, "id_alokasi" => 1, "id_tagihan" => 1, "nilai" => 1);

        $mockPDOStatement = $this->getMock("PDOStatement", array("execute", "closeCursor", "fetch"));
        $mockPDO = $this->getMock("MockPDO", array("setAttribute", "errorInfo", "prepare", "lastInsertId"));

        $mockPDOStatement->expects($this->any())->method("execute")->with($this->isType("array"))->will($this->returnValue(TRUE));
        $mockPDOStatement->expects($this->any())->method("fetch")->with($this->equalTo(PDO::FETCH_ASSOC))->will($this->returnValue($fetchReturnValue));

        $mockPDOStatement->expects($this->any())->method("closeCursor")->will($this->returnValue(TRUE));

        $mockPDO->expects($this->any())->method("setAttribute")->with($this->equalTo(PDO::ATTR_ERRMODE), $this->equalTo(PDO::ERRMODE_EXCEPTION))->will($this->returnValue(TRUE));
        $mockPDO->expects($this->any())->method("prepare")->with($this->isType("string"))->will($this->returnValue($mockPDOStatement));

        $this->object->setPDO($mockPDO);
        $this->object->setId(1);

        $this->assertTrue($this->object->retrieve());
        $this->_assertPropertiesValue($fetchReturnValue);
    }

    private function _setProperties() {
        $this->object->setId(1);
        $this->object->setIdAlokasi(1);
        $this->object->setIdTagihan(1);
        $this->object->setNilai(1);
    }

    private function _unsetProperties() {
        $this->object->unsetId();
        $this->object->unsetIdAlokasi();
        $this->object->unsetIdTagihan();
        $this->object->unsetNilai();
    }

    private function _assertPropertiesValue($expectedValues) {
        $this->assertEquals($expectedValues["id"], $this->object->getId());
        $this->assertEquals($expectedValues["id_alokasi"], $this->object->getIdAlokasi());
        $this->assertEquals($expectedValues["id_tagihan"], $this->object->getIdTagihan());
        $this->assertEquals($expectedValues["nilai"], $this->object->getNilai());
    }

}


text:
exports.Observer = require('./observer');
exports.stmt = require('./stmt');

exports.statement = function(query)
{
    return exports.stmt.parse(query);
}