text:
module Bitsy
  class BuildSendManyHashForTransaction

    include LightService::Action
    expects :payment_transaction, :amount_for_splitting, :total_amount
    promises :transaction_send_many_hash

    executed do |ctx|
      tax_amount = tax_amount_from(ctx)
      owner_amount = owner_amount_from(ctx)

      payment_depot = ctx.payment_transaction.payment_depot

      ctx.transaction_send_many_hash = {
        payment_depot.tax_address => tax_amount,
        payment_depot.owner_address => owner_amount,
      }
    end

    private

    def self.tax_amount_from(ctx)
      fee_less_share_for_transaction_fee(
        ctx.payment_transaction.forward_tax_fee,
        ctx.amount_for_splitting,
        ctx.total_amount,
      )
    end

    def self.owner_amount_from(ctx)
      fee_less_share_for_transaction_fee(
        ctx.payment_transaction.owner_fee,
        ctx.amount_for_splitting,
        ctx.total_amount,
      )
    end

    def self.fee_less_share_for_transaction_fee(fee, amount_for_splitting, total_amount)
      percent_of_total = fee / total_amount
      (percent_of_total * 100_000_000 * amount_for_splitting).to_i
    end

  end
end


text:
package mskubilov.notifywait;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;

/**
 * //курс Петра Арсентьева job4j.ru.
 *
 * @author Maksim Skubilov skubilov89@yandex.ru
 * @version 1.0
 * @since 05.06.17
 */
public class MyReentrantLockTest {

    /**
     * My Lock.
     */
    private MyReentrantLock lock = new MyReentrantLock();

    /**
     * Variable for test.
     */
    private int count = 0;

    /**
     * Method calls to lock and another method calls to lock too.
     */
    private void count() {
        System.out.printf("%s trying to lock count()\n", Thread.currentThread().getName());
        lock.lock();
        System.out.printf("%s has locked count()\n", Thread.currentThread().getName());
        increment();
        System.out.printf("%s unlocks count()\n", Thread.currentThread().getName());
        lock.unlock();
    }

    /**
     * Method calls to lock and increments count.
     */
    private void increment() {
        System.out.printf("%s trying to lock increment()\n", Thread.currentThread().getName());
        lock.lock();
        System.out.printf("%s locks increment()\n", Thread.currentThread().getName());
        count++;
        System.out.printf("%s unlocks increment()\n", Thread.currentThread().getName());
        lock.unlock();
    }

    /**
     * @return this.count variable.
     */
    public int getCount() {
        return this.count;
    }

    /**
     * @return runnable that runs count().
     */
    public Runnable getRunnableCount() {
        return new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    count();
                }
            }
        };
    }

    /**
     * @return runnable that runs increment()
     */
    public Runnable getRunnableGenerate() {
        return new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    increment();
                }
            }
        };
    }

    /**
     * Test of my Lock.
     */
    @Test
    public void testMyReentrantLock() {
        MyReentrantLockTest lockTest = new MyReentrantLockTest();
        Thread t1 = new Thread(lockTest.getRunnableCount());
        Thread t2 = new Thread(lockTest.getRunnableGenerate());
        t2.start();
        t1.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        assertThat(lockTest.getCount(), is(20));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.boot.actuate.endpoint.mvc;

import com.google.common.net.HttpHeaders;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.MinimalActuatorHypermediaApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Integration tests for {@link HalBrowserMvcEndpoint}
 *
 * @author Dave Syer
 * @author Andy Wilkinson
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(properties = "management.security.enabled=false")
@DirtiesContext
public class HalBrowserMvcEndpointDisabledIntegrationTests {

	@Autowired
	private WebApplicationContext context;

	@Autowired
	private MvcEndpoints mvcEndpoints;

	private MockMvc mockMvc;

	@Before
	public void setUp() {
		this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
	}

	@Test
	public void linksOnActuator() throws Exception {
		this.mockMvc.perform(get("/application").accept(MediaType.APPLICATION_JSON))
				.andExpect(status().isOk()).andExpect(jsonPath("$._links").exists())
				.andExpect(header().doesNotExist("cache-control"));
	}

	@Test
	public void browserRedirect() throws Exception {
		this.mockMvc.perform(get("/application/").accept(MediaType.TEXT_HTML))
				.andExpect(status().isFound()).andExpect(header().string(
						HttpHeaders.LOCATION, "http://localhost/application/browser.html"));
	}

	@Test
	public void endpointsDoNotHaveLinks() throws Exception {
		for (MvcEndpoint endpoint : this.mvcEndpoints.getEndpoints()) {
			String path = endpoint.getPath();
			if ("".equals(path) || endpoint instanceof HeapdumpMvcEndpoint) {
				continue;
			}
			path = "/application" + (path.length() > 0 ? path : "/");
			MockHttpServletRequestBuilder requestBuilder = get(path);
			if (endpoint instanceof AuditEventsMvcEndpoint) {
				requestBuilder.param("after", "2016-01-01T12:00:00+00:00");
			}
			this.mockMvc.perform(requestBuilder.accept(MediaType.APPLICATION_JSON))
					.andExpect(status().isOk())
					.andExpect(jsonPath("$._links").doesNotExist());
		}
	}

	@MinimalActuatorHypermediaApplication
	@Configuration
	public static class SpringBootHypermediaApplication {

		public static void main(String[] args) {
			SpringApplication.run(SpringBootHypermediaApplication.class,
					"--endpoints.hypermedia.enabled=false");
		}

	}

}


text:
package org.brackit.server.node.index.name.impl;

import java.util.Map;
import java.util.Set;

import org.brackit.xquery.util.log.Logger;
import org.brackit.server.io.buffer.PageID;
import org.brackit.server.node.index.cas.impl.CASIndexListener;
import org.brackit.server.node.index.definition.Cluster;
import org.brackit.server.node.index.definition.IndexDef;
import org.brackit.server.node.index.name.impl.NameDirectoryEncoderImpl.QVocID;
import org.brackit.server.node.txnode.IndexEncoder;
import org.brackit.server.node.txnode.IndexEncoderHelper;
import org.brackit.server.node.txnode.TXNode;
import org.brackit.server.store.index.Index;
import org.brackit.server.store.index.IndexAccessException;
import org.brackit.server.tx.Tx;
import org.brackit.xquery.atomic.QNm;
import org.brackit.xquery.node.parser.DefaultListener;
import org.brackit.xquery.node.parser.ListenMode;
import org.brackit.xquery.node.parser.SubtreeListener;
import org.brackit.xquery.xdm.DocumentException;

/**
 * @author Sebastian Baechle
 *
 */
public class NameIndexListener<E extends TXNode<E>> extends
		DefaultListener<E> implements SubtreeListener<E> {
	private static final Logger log = Logger.getLogger(CASIndexListener.class);

	protected final Tx tx;
	protected final Index index;
	protected final IndexDef indexDef;
	private final ListenMode mode;
	private final PageID indexNo;
	private final NameDirectoryEncoder nameDirectoryEncoder;
	protected final IndexEncoderHelper<E> helper;

	private final Map<QNm, Cluster> includes;

	private final Set<QNm> excludes;

	public NameIndexListener(Tx tx, Index index,
			IndexEncoderHelper<E> helper, IndexDef indexDef, ListenMode mode) {
		this.tx = tx;
		this.index = index;
		this.indexDef = indexDef;
		this.mode = mode;
		this.helper = helper;

		this.indexNo = new PageID(indexDef.getID());
		this.nameDirectoryEncoder = new NameDirectoryEncoderImpl();
		this.includes = indexDef.getIncluded();
		this.excludes = indexDef.getExcluded();
	}

	@Override
	public <T extends E> void startElement(T node) throws DocumentException {
		switch (mode) {
		case INSERT:
			insertElement(node);
			break;
		case DELETE:
			deleteElement(node);
			break;
		default:
			// ignore text
		}
	}

	public <T extends E> void attribute(T node) throws DocumentException {
		// TODO Listen for attributes and handle them appropriately
	}

	protected <T extends E> void insertElement(T node) throws DocumentException {
		QNm name = node.getName();
		boolean included = (includes.isEmpty() || includes.containsKey(name));
		boolean excluded = (!excludes.isEmpty() && excludes.contains(name));
		if (!included || excluded) {
			return;
		}

		QVocID qVocID = QVocID.fromQNm(tx, helper.getDictionary(), name);
		try {
			PageID nodePageID;
			IndexEncoder<E> encoder = helper.getNameIndexEncoder();
			byte[] nameDirectoryKey = nameDirectoryEncoder.encodeKey(qVocID);
			byte[] nameDirectoryValue = index.read(tx, indexNo,
					nameDirectoryKey);

			if (nameDirectoryValue == null) {
				if (log.isDebugEnabled()) {
					log.debug(String.format("Creating new node reference " +
						"index for qVocID %s in index %s.", qVocID, indexNo));
				}

				nodePageID = index.createIndex(tx, indexNo.getContainerNo(),
						encoder.getKeyType(), encoder.getValueType(), true,
						true);

				index.insert(tx, indexNo, nameDirectoryKey,
						nameDirectoryEncoder.encodeValue(nodePageID));
			} else {
				nodePageID = nameDirectoryEncoder
						.decodePageID(nameDirectoryValue);
			}

			if (log.isDebugEnabled()) {
				log.debug(String.format("Inserting (%s, %s) in name " +
						"index %s.", qVocID, node.getDeweyID(), indexNo));
			}

			byte[] key = encoder.encodeKey(node);
			byte[] value = encoder.encodeValue(node);
			index.insert(tx, nodePageID, key, value);
		} catch (IndexAccessException e) {
			throw new DocumentException(e);
		}
	}

	protected <T extends E> void deleteElement(T node) throws DocumentException {
		QNm name = node.getName();
		boolean included = (includes.isEmpty() || includes.containsKey(name));
		boolean excluded = (!excludes.isEmpty() && excludes.contains(name));
		if (!included || excluded) {
			return;
		}

		QVocID qVocID = QVocID.fromQNm(tx, helper.getDictionary(), name);
		try {
			PageID nodePageID;
			IndexEncoder<E> encoder = helper.getNameIndexEncoder();
			byte[] nameDirectoryKey = nameDirectoryEncoder.encodeKey(qVocID);
			byte[] nameDirectoryValue = index.read(tx, indexNo,
					nameDirectoryKey);

			if (nameDirectoryValue == null) {
				if (log.isInfoEnabled()) {
					log.warn(String.format("No valid node reference index " +
						"for qVocID %s in index %s found.", qVocID, indexNo));
				}
			} else {
				nodePageID = nameDirectoryEncoder
						.decodePageID(nameDirectoryValue);
				if (log.isDebugEnabled()) {
					log.debug(String.format("Deleting (%s, %s) from name " +
							"index %s.", qVocID, node.getDeweyID(), indexNo));
				}
				byte[] key = encoder.encodeKey(node);
				byte[] value = encoder.encodeValue(node);
				index.delete(tx, nodePageID, key, value);
			}
		} catch (IndexAccessException e) {
			throw new DocumentException(e);
		}
	}
}


text:
<?php

namespace Oro\Bundle\ApiBundle\Processor\Shared;

use Oro\Bundle\ApiBundle\Metadata\EntityMetadata;

/**
 * Removes records with key "_" from to-many associations of a result item.
 * Such records contain an additional information about a collection, e.g. "has_more" flag
 * in such record indicates whether a collection has more records than it was requested.
 * All removed records are stored in the context for further usage.
 */
class RemoveInfoRecordsForSingleItem extends RemoveInfoRecords
{
    /**
     * {@inheritdoc}
     */
    protected function processData(array &$data, EntityMetadata $metadata): array
    {
        return $this->processEntity($data, $metadata, '');
    }
}


text:
package com.azure.resourcemanager.synapse.implementation;

import com.azure.core.management.Region;
import com.azure.core.util.Context;
import com.azure.resourcemanager.synapse.fluent.models.DataMaskingPolicyInner;
import com.azure.resourcemanager.synapse.models.DataMaskingPolicy;
import com.azure.resourcemanager.synapse.models.DataMaskingState;

public final class DataMaskingPolicyImpl
    implements DataMaskingPolicy, DataMaskingPolicy.Definition, DataMaskingPolicy.Update {
    private DataMaskingPolicyInner innerObject;

    private final com.azure.resourcemanager.synapse.SynapseManager serviceManager;

    public String id() {
        return this.innerModel().id();
    }

    public String name() {
        return this.innerModel().name();
    }

    public String type() {
        return this.innerModel().type();
    }

    public String location() {
        return this.innerModel().location();
    }

    public String kind() {
        return this.innerModel().kind();
    }

    public String managedBy() {
        return this.innerModel().managedBy();
    }

    public DataMaskingState dataMaskingState() {
        return this.innerModel().dataMaskingState();
    }

    public String exemptPrincipals() {
        return this.innerModel().exemptPrincipals();
    }

    public String applicationPrincipals() {
        return this.innerModel().applicationPrincipals();
    }

    public String maskingLevel() {
        return this.innerModel().maskingLevel();
    }

    public Region region() {
        return Region.fromName(this.regionName());
    }

    public String regionName() {
        return this.location();
    }

    public DataMaskingPolicyInner innerModel() {
        return this.innerObject;
    }

    private com.azure.resourcemanager.synapse.SynapseManager manager() {
        return this.serviceManager;
    }

    private String resourceGroupName;

    private String workspaceName;

    private String sqlPoolName;

    public DataMaskingPolicyImpl withExistingSqlPool(
        String resourceGroupName, String workspaceName, String sqlPoolName) {
        this.resourceGroupName = resourceGroupName;
        this.workspaceName = workspaceName;
        this.sqlPoolName = sqlPoolName;
        return this;
    }

    public DataMaskingPolicy create() {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getDataMaskingPolicies()
                .createOrUpdateWithResponse(
                    resourceGroupName, workspaceName, sqlPoolName, this.innerModel(), Context.NONE)
                .getValue();
        return this;
    }

    public DataMaskingPolicy create(Context context) {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getDataMaskingPolicies()
                .createOrUpdateWithResponse(resourceGroupName, workspaceName, sqlPoolName, this.innerModel(), context)
                .getValue();
        return this;
    }

    DataMaskingPolicyImpl(com.azure.resourcemanager.synapse.SynapseManager serviceManager) {
        this.innerObject = new DataMaskingPolicyInner();
        this.serviceManager = serviceManager;
    }

    public DataMaskingPolicyImpl update() {
        return this;
    }

    public DataMaskingPolicy apply() {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getDataMaskingPolicies()
                .createOrUpdateWithResponse(
                    resourceGroupName, workspaceName, sqlPoolName, this.innerModel(), Context.NONE)
                .getValue();
        return this;
    }

    public DataMaskingPolicy apply(Context context) {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getDataMaskingPolicies()
                .createOrUpdateWithResponse(resourceGroupName, workspaceName, sqlPoolName, this.innerModel(), context)
                .getValue();
        return this;
    }

    DataMaskingPolicyImpl(
        DataMaskingPolicyInner innerObject, com.azure.resourcemanager.synapse.SynapseManager serviceManager) {
        this.innerObject = innerObject;
        this.serviceManager = serviceManager;
        this.resourceGroupName = Utils.getValueFromIdByName(innerObject.id(), "resourceGroups");
        this.workspaceName = Utils.getValueFromIdByName(innerObject.id(), "workspaces");
        this.sqlPoolName = Utils.getValueFromIdByName(innerObject.id(), "sqlPools");
    }

    public DataMaskingPolicy refresh() {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getDataMaskingPolicies()
                .getWithResponse(resourceGroupName, workspaceName, sqlPoolName, Context.NONE)
                .getValue();
        return this;
    }

    public DataMaskingPolicy refresh(Context context) {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getDataMaskingPolicies()
                .getWithResponse(resourceGroupName, workspaceName, sqlPoolName, context)
                .getValue();
        return this;
    }

    public DataMaskingPolicyImpl withDataMaskingState(DataMaskingState dataMaskingState) {
        this.innerModel().withDataMaskingState(dataMaskingState);
        return this;
    }

    public DataMaskingPolicyImpl withExemptPrincipals(String exemptPrincipals) {
        this.innerModel().withExemptPrincipals(exemptPrincipals);
        return this;
    }
}


text:
"use strict";

var access = require('./access');

module.exports = {
  // errorStatus and errorMessage define the HTTP status and message returned when access is denied
  // It is recommended to use 403 (forbidden) when a failure message is available or 404 (not found)
  // when errorMessage is left empty in case server does not wish to provide more info about failure
  errorStatus: 403,
  errorMessage: "Access denied",
  // getACL is called to extract the granted ACL from the framework specific arguments
  getAcl: function(req) {
    // this = required ACL
    //console.log(arguments.length);
    return req ? req.acl : null;
  },
  // setACL is called to assign the granted ACL to the framework specific arguments
  setAcl: function(req) {
    // this = granted ACL
    req.acl = this;
  },
  // cont is called with the 'access.required' middleware function to continue
  // processing by subsequent middleware since access has been granted
  cont: function(req,res,next) {
    // this == required ACL
    next();
  },
  // halt is called with the 'access.required' middleware function to halt
  // further processing since access has been denied
  halt: function(req,res,next) {
    // this == required ACL
    denied(req,res);
  },
  // accept is called with 'access.requiredFor' when access has been granted and
  // target function is about to be invoked. No processing required for Express
  accept: function(req,res,next) {
    // this == required ACL
  },
  // reject is called with 'access.requiredFor' to perform framework specific
  // processing when access to the target function has been denied
  reject: function(req,res,next) {
    // this == required ACL
    denied(req,res);
  }
};

function denied(req,res) {
  if (access.options.errorMessage)
    res.status(access.options.errorStatus).send(access.options.errorMessage);
  else
    res.status(access.options.errorStatus).end();
}


text:
package org.openengsb.core.api.security.service;

/**
 * Generic UserManagementException. It serves as baseclass for other Checked UserManagementExceptions
 *
 * If this class is used itself, this can mean that something went wrong in the persistence-backend.
 */
public class UserManagementException extends Exception {

    private static final long serialVersionUID = 269605012169642052L;

    public UserManagementException() {
    }

    public UserManagementException(String message) {
        super(message);
    }

    public UserManagementException(Throwable cause) {
        super(cause);
    }

    public UserManagementException(String message, Throwable cause) {
        super(message, cause);
    }

}


text:
package com.edgar.core.repository;

import com.edgar.core.cache.CacheProviderFactory;
import com.edgar.core.repository.transaction.Transaction;
import com.edgar.core.repository.transaction.TransactionConfig;
import com.edgar.core.repository.transaction.TransactionFactory;
import com.edgar.module.sys.repository.domain.TestTable;
import com.edgar.module.sys.repository.querydsl.QTestTable;
import com.mysema.query.sql.Configuration;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/applicationContext.xml"})
@TransactionConfiguration(defaultRollback = true)
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
        TransactionalTestExecutionListener.class})
public class QueryTransactionTest {

    @Autowired
    private CacheProviderFactory cacheProviderFactory;

    @Autowired
    private DataSource dataSource;

    private Configuration configuration = ConfigurationFactory.createConfiguration(Constants.DEFAULT);

    private TransactionConfig config;

    private RowMapper<TestTable> rowMapper = BeanPropertyRowMapper.newInstance(TestTable.class);

    @Before
    public void setUp() {
        config = new TransactionConfig(dataSource, configuration, QTestTable.testTable);
        List<TestTable> testTables = new ArrayList<TestTable>();
        for (int i = 0; i < 10; i++) {
            TestTable testTable = new TestTable();
            testTable.setTestCode("000" + i);
            testTable.setDictName("000" + i);
            testTable.setParentCode("-1");
            testTable.setSorted(9999);
            testTables.add(testTable);
        }

        Transaction transaction = TransactionFactory.createDefaultBatchInsertTransaction(config, testTables);
        transaction.execute();
    }

    @After
    public void tearDown() {
        cacheProviderFactory.createCacheWrapper("TestTableCache").removeAll();
        cacheProviderFactory.createCacheWrapper("Test2TableCache").removeAll();
    }

    @Transactional
    @Test
    public void testQuery() {
        QueryExample example = QueryExample.newInstance();
        example = QueryExample.newInstance();
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(10, testTables.size());

        example.limit(10);
        transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        testTables = transaction.execute();
        Assert.assertEquals(10, testTables.size());
        example.equalsTo("testCode", "0001");
        transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        testTables = transaction.execute();
        Assert.assertEquals(1, testTables.size());

        example.clear();
        example.limit(10);
        example.greaterThan("test_code", "0001");
        example.asc("sorted");
        example.desc("testCode");
        transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        testTables = transaction.execute();
        Assert.assertEquals(8, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryReturnField() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        example.addField("testCode");

        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(10, testTables.size());
        for (TestTable TestTable : testTables) {
            Assert.assertNotNull(TestTable.getTestCode());
            Assert.assertNull(TestTable.getDictName());
        }
        example.clear();
        example.limit(10);
        example.addField("testCodeew");
        transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        testTables = transaction.execute();
        Assert.assertEquals(10, testTables.size());
        for (TestTable TestTable : testTables) {
            Assert.assertNotNull(TestTable.getTestCode());
            Assert.assertNotNull(TestTable.getDictName());
        }
    }

    @Transactional
    @Test
    public void testQueryNotEquals() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        example.notEqualsTo("testCode", "0001");
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(9, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryGreatThan() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        example.greaterThan("testCode", "0001");
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(8, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryGreatThanAndEqulas() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        example.greaterThanOrEqualTo("testCode", "0001");
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(9, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryLessThan() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        example.lessThan("testCode", "0004");
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(4, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryLessThanAndEqulas() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        example.lessThanOrEqualTo("testCode", "0004");
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(5, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryLike() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        example.like("testCode", "000%");
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(10, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryNotLike() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        example.notLike("testCode", "0000001%");
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(10, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryBeginWith() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        example.beginWtih("testCode", "000");
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(10, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryNotBeginWith() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        example.notBeginWith("testCode", "000");
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(0, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryContain() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        example.contain("testCode", "00");
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(10, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryNotContain() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        example.notContain("testCode", "00");
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(0, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryIsNull() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        example.isNull("testCode");
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(0, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryIsNotNull() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        example.isNotNull("testCode");
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(10, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryBetween() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        example.between("testCode", "0001", "0002");
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(2, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryNotBetween() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        example.notBetween("testCode", "0001", "0002");
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(8, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryIn() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        List<Object> in = new ArrayList<Object>();
        in.add("0001");
        in.add("0002");
        example.in("testCode", in);
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(2, testTables.size());
    }

    @Transactional
    @Test
    public void testQueryNotIn() {
        QueryExample example = QueryExample.newInstance();
        example.limit(10);
        List<Object> in = new ArrayList<Object>();
        in.add("0001");
        in.add("0002");
        example.notIn("testCode", in);
        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        List<TestTable> testTables = transaction.execute();
        Assert.assertEquals(8, testTables.size());
    }

    @Transactional
    @Test
    public void testQuerySingleColumn() {
        QueryExample example = QueryExample.newInstance();
        example.equalsTo("testCode", "0001");
        example.addField("testCode");

        Transaction transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);

        List<String> testTables = transaction.execute();
        Assert.assertEquals(1, testTables.size());
        example.addField("dictName");
        transaction = TransactionFactory.createQueryTransaction(config, example, rowMapper);
        try {
            testTables = transaction.execute();
            ;
            Assert.assertEquals(1, testTables.size());
        } catch (Exception e) {

        }
    }
}


text:
module Pronto
  module GometalinterVersion
    VERSION = '0.1.0'.freeze
  end
end


text:
'use strict';

import { AuthError, getBasicAuthHeaders, getSessionUrl, wrapError } from './utils';

import ajaxCore from 'pouchdb-ajax';
import { assign, toPromise } from 'pouchdb-utils';

var logIn = toPromise(function (username, password, opts, callback) {
  var db = this;
  if (typeof callback === 'undefined') {
    callback = opts;
    opts = {};
  }
  if (['http', 'https'].indexOf(db.type()) === -1) {
    return callback(new AuthError('this plugin only works for the http/https adapter'));
  }

  if (!username) {
    return callback(new AuthError('you must provide a username'));
  } else if (!password) {
    return callback(new AuthError('you must provide a password'));
  }

  var ajaxOpts = assign({
    method: 'POST',
    url: getSessionUrl(db),
    headers: assign({'Content-Type': 'application/json'}, getBasicAuthHeaders(db)),
    body: {name: username, password: password},
  }, opts.ajax || {});
  ajaxCore(ajaxOpts, wrapError(callback));
});

var logOut = toPromise(function (opts, callback) {
  var db = this;
  if (typeof callback === 'undefined') {
    callback = opts;
    opts = {};
  }
  var ajaxOpts = assign({
    method: 'DELETE',
    url: getSessionUrl(db),
    headers: getBasicAuthHeaders(db),
  }, opts.ajax || {});
  ajaxCore(ajaxOpts, wrapError(callback));
});

var getSession = toPromise(function (opts, callback) {
  var db = this;
  if (typeof callback === 'undefined') {
    callback = opts;
    opts = {};
  }
  var url = getSessionUrl(db);

  var ajaxOpts = assign({
    method: 'GET',
    url: url,
    headers: getBasicAuthHeaders(db),
  }, opts.ajax || {});
  ajaxCore(ajaxOpts, wrapError(callback));
});

export { logIn, logOut, getSession };


text:
theme("plain")

    -- the success status
    set_text("success", "$ok")
    set_color("success", "")

    -- the failure status
    set_text("failure", "failed")
    set_color("failure", "")

    -- the nothing status
    set_text("nothing", "no")
    set_color("nothing", "")

    -- the error info
    set_text("error", "error")
    set_color("error", "")

    -- the warning info
    set_text("warning", "$warning")
    set_color("warning", "")

    -- the building progress
    set_text("build.progress_format", "[%3d%%]")
    set_color("build.progress", "")

    -- the building object file
    set_color("build.object", "")

    -- the building target file
    set_color("build.target", "")


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_04.c
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml
Template File: sources-sink-04.tmpl.c
*/
/*
 * @description
 * CWE: 122 Heap Based Buffer Overflow
 * BadSource:  Allocate using malloc() and set data pointer to a small buffer
 * GoodSource: Allocate using malloc() and set data pointer to a large buffer
 * Sink: memcpy
 *    BadSink : Copy int64_t array to data using memcpy
 * Flow Variant: 04 Control flow: if(STATIC_CONST_TRUE) and if(STATIC_CONST_FALSE)
 *
 * */

#include "std_testcase.h"

/* The two variables below are declared "const", so a tool should
 * be able to identify that reads of these will always return their
 * initialized values.
 */
static const int STATIC_CONST_TRUE = 1; /* true */
static const int STATIC_CONST_FALSE = 0; /* false */

#ifndef OMITBAD

void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_04_bad()
{
    int64_t * data;
    data = NULL;
    if(STATIC_CONST_TRUE)
    {
        /* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */
        data = (int64_t *)malloc(50*sizeof(int64_t));
    }
    {
        int64_t source[100] = {0}; /* fill with 0's */
        /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
        memcpy(data, source, 100*sizeof(int64_t));
        printLongLongLine(data[0]);
        free(data);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B1() - use goodsource and badsink by changing the STATIC_CONST_TRUE to STATIC_CONST_FALSE */
static void goodG2B1()
{
    int64_t * data;
    data = NULL;
    if(STATIC_CONST_FALSE)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */
        data = (int64_t *)malloc(100*sizeof(int64_t));
    }
    {
        int64_t source[100] = {0}; /* fill with 0's */
        /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
        memcpy(data, source, 100*sizeof(int64_t));
        printLongLongLine(data[0]);
        free(data);
    }
}

/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
    int64_t * data;
    data = NULL;
    if(STATIC_CONST_TRUE)
    {
        /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */
        data = (int64_t *)malloc(100*sizeof(int64_t));
    }
    {
        int64_t source[100] = {0}; /* fill with 0's */
        /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
        memcpy(data, source, 100*sizeof(int64_t));
        printLongLongLine(data[0]);
        free(data);
    }
}

void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_04_good()
{
    goodG2B1();
    goodG2B2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_04_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_04_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif