text:
"""
Unlike configuration.py, this file is meant for static, entire project
encompassing settings, like memoization and caching file directories.
"""
__title__ = 'newspaper'
__author__ = 'Lucas Ou-Yang'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014, Lucas Ou-Yang'

import logging
import os

from cookielib import CookieJar as cj

from .version import __version__

log = logging.getLogger(__name__)

PARENT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))

POPULAR_URLS = os.path.join(
    PARENT_DIRECTORY, 'resources/misc/popular_sources.txt')
USERAGENTS = os.path.join(PARENT_DIRECTORY, 'resources/misc/useragents.txt')

STOPWORDS_DIR = os.path.join(PARENT_DIRECTORY, 'resources/text')

# NLP stopwords are != regular stopwords for now...
NLP_STOPWORDS_EN = os.path.join(
    PARENT_DIRECTORY, 'resources/misc/stopwords-nlp-en.txt')

DATA_DIRECTORY = '.newspaper_scraper'

TOP_DIRECTORY = os.path.join(os.path.expanduser("~"), DATA_DIRECTORY)
if not os.path.exists(TOP_DIRECTORY):
    os.mkdir(TOP_DIRECTORY)

# Error log
LOGFILE = os.path.join(TOP_DIRECTORY, 'newspaper_errors_%s.log' % __version__)
MONITOR_LOGFILE = os.path.join(
    TOP_DIRECTORY, 'newspaper_monitors_%s.log' % __version__)

# Memo directory (same for all concur crawlers)
MEMO_FILE = 'memoized'
MEMO_DIR = os.path.join(TOP_DIRECTORY, MEMO_FILE)

if not os.path.exists(MEMO_DIR):
    os.mkdir(MEMO_DIR)

# category and feed cache
CF_CACHE_DIRECTORY = 'feed_category_cache'
ANCHOR_DIRECTORY = os.path.join(TOP_DIRECTORY, CF_CACHE_DIRECTORY)

if not os.path.exists(ANCHOR_DIRECTORY):
    os.mkdir(ANCHOR_DIRECTORY)

TRENDING_URL = 'http://www.google.com/trends/hottrends/atom/feed?pn=p1'


text:
#if defined(_MSC_VER)
#pragma warning( disable : 4250 ) // Disable: 'class1' : inherits 'class2::member' via dominance
#pragma warning( disable : 4355 ) // The this pointer is valid only within nonstatic member functions. It cannot be used in the initializer list for a base class.ck(16)
#endif

#include <tut/tut.hpp>
#include <tut_reporter.h>
#include <PureMVC/PureMVC.hpp>

#include "FacadeTestCommand.hpp"
#include "FacadeTestInheritance.hpp"

namespace data
{
    struct FacadeTest
    { };
}

namespace testgroup
{
    typedef tut::test_group<data::FacadeTest> itearator_test_t;
    typedef itearator_test_t::object object;
    itearator_test_t facade_test("FacadeTest");
}

namespace tut
{
    using namespace testgroup;

    using PureMVC::Interfaces::IFacade;
    using PureMVC::Interfaces::IProxy;
    using PureMVC::Interfaces::IMediator;
    using PureMVC::Interfaces::IAggregate;
    using PureMVC::Interfaces::IIterator;
    using PureMVC::Patterns::Facade;
    using PureMVC::Patterns::Proxy;
    using PureMVC::Patterns::Mediator;

    template<> template<>
    void object::test<1>(void)
    {
        set_test_name("testGetInstanceAndGetMulitonKey");

        // Test Factory Method
        IFacade &facade = Facade::getInstance("FacadeTestKey1");

        ensure( "Expecting instance not null", &facade != NULL);
        // Because C++ doesn't provide operator cast 'as'
        // so that I use dynamic_cast to make sure that facade is Facade
        ensure( "Expecting instance implements IFacade", dynamic_cast<Facade*>(&facade) != NULL);

        ensure_equals("Expecting facade.getMultitonKey() == FacadeTestKey1",
            facade.getMultitonKey(), "FacadeTestKey1");
    }

    template<> template<>
    void object::test<2>(void)
    {
        set_test_name("testRegisterCommandAndGetMultitonKeyAndSendNotification");

        // Create the Facade, register the FacadeTestCommand to
        // handle 'FacadeTest' notifications
        IFacade &facade = Facade::getInstance("FacadeTestKey2");
        data::FacadeTestCommand facade_command;
        facade.registerCommand("FacadeTestNote", &facade_command);

        ensure_equals("Expecting facade_command.getMultitonKey()== FacadeTestKey2",
            facade_command.getMultitonKey(), "FacadeTestKey2");

        // Send notification. The Command associated with the event
        // (FacadeTestCommand) will be invoked, and will multiply
        // the vo.input value by 2 and set the result on vo.result
        data::FacadeTestVO vo(32);
        facade.sendNotification("FacadeTestNote", &vo );

        // test assertions
        ensure_equals("Expecting vo.result == 64", vo.result, 64);
    }

    template<> template<>
    void object::test<3>(void)
    {
        set_test_name("testRegisterAndRemoveCommandAndSendNotification");

        // Create the Facade, register the FacadeTestCommand to
        // handle 'FacadeTest' events
        IFacade &facade = Facade::getInstance("FacadeTestKey3");
        data::FacadeTestCommand facade_command;
        facade.registerCommand("FacadeTestNote", &facade_command);
        facade.removeCommand("FacadeTestNote");

        // Send notification. The Command associated with the event
        // (FacadeTestCommand) will NOT be invoked, and will NOT multiply
        // the vo.input value by 2
        data::FacadeTestVO vo(32);
        facade.sendNotification("FacadeTestNote", &vo );

        // test assertions
        ensure( "Expecting vo.result != 64", vo.result != 64 );
    }

    template<> template<>
    void object::test<4>(void)
    {
        set_test_name("testRegisterAndGetMultitionKeyAndRetrieveProxy");

        // Create the Facade, register the FacadeTestCommand to
        // handle 'FacadeTest' events
        IFacade &facade = Facade::getInstance("FacadeTestKey4");

        Proxy proxy_local("colors");
        std::vector<std::string> data_local;
        data_local.push_back("red");
        data_local.push_back("green");
        data_local.push_back("blue");
        proxy_local.setData(&data_local);

        facade.registerProxy(&proxy_local);

        ensure_equals("Expecting proxy_local.getMultitonKey()== FacadeTestKey4",
            proxy_local.getMultitonKey(), "FacadeTestKey4");

        IProxy* proxy = NULL;
        try
        {
            proxy = &facade.retrieveProxy("colors");
        }
        catch (...)
        { }
        // test assertions
        ensure( "Expecting proxy is IProxy", dynamic_cast<Proxy*>(proxy) != NULL);

        // retrieve data from proxy
        std::vector<std::string>* data = (std::vector<std::string>*)proxy->getData();

        // test assertions
        ensure( "Expecting data not null", data != NULL);
        ensure_equals( "Expecting data is Array", typeid(data).name(), typeid(std::vector<std::string>*).name() );
        ensure_equals("Expecting data.length == 3", data->size(), 3);
        ensure_equals("Expecting data[0] == 'red'", (*data)[0], "red");
        ensure_equals("Expecting data[1] == 'green'", (*data)[1], "green");
        ensure_equals("Expecting data[2] == 'blue'", (*data)[2], "blue");
    }

    template<> template<>
    void object::test<5>(void)
    {
        set_test_name("testRegisterAndRemoveProxy");

        IFacade &facade = Facade::getInstance("FacadeTestKey5");

        Proxy proxy_local("sizes");
        std::vector<std::string> data_local;
        data_local.push_back("7");
        data_local.push_back("13");
        data_local.push_back("21");
        proxy_local.setData(&data_local);

        // register a proxy, remove it, then try to retrieve it
        facade.registerProxy(&proxy_local);

        // remove the proxy
        IProxy* removedProxy= facade.removeProxy("sizes");

        // assert that we removed the appropriate proxy
        ensure_equals( "Expecting removedProxy.getProxyName() == 'sizes'",
            removedProxy->getProxyName(), "sizes");

        IProxy* proxy = NULL;
        try
        {
            // make sure we can no longer retrieve the proxy from the model
            proxy = &facade.retrieveProxy("sizes");
        }
        catch(...)
        { }
        // test assertions
        ensure("Expecting proxy is null", proxy == NULL );
    }

    template<> template<>
    void object::test<6>(void)
    {
        set_test_name("testRegisterRetrieveAndRemoveMediator");

        // register a mediator, remove it, then try to retrieve it
        IFacade &facade = Facade::getInstance("FacadeTestKey6");
        std::string str("Sprite");
        Mediator mediator_local(Mediator::NAME, &str);
        facade.registerMediator(&mediator_local);

        ensure_equals("Expecting mediator_local.getMultitonKey()== FacadeTestKey6",
            mediator_local.getMultitonKey(), "FacadeTestKey6");

        IMediator* mediator = NULL;
        try
        {
            mediator = &facade.retrieveMediator(Mediator::NAME);
        }
        catch (...)
        { }
        // retrieve the mediator
        ensure( "Expecting mediator is not null", mediator != NULL);

        // remove the mediator
        IMediator* removedMediator = facade.removeMediator(Mediator::NAME);

        // assert that we have removed the appropriate mediator
        ensure_equals("Expecting removedMediator.getMediatorName() == Mediator.NAME",
                      removedMediator->getMediatorName(), Mediator::NAME);

        mediator= NULL;
        try
        {
            // assert that the mediator is no longer retrievable
            mediator = &facade.retrieveMediator(Mediator::NAME);
        }
        catch (...)
        { }
        ensure( "Expecting facade.retrieveMediator( Mediator.NAME ) == null )", mediator == NULL);
    }

    template<> template<>
    void object::test<7>(void)
    {
        set_test_name("testHasProxy");

        // register a mediator, remove it, then try to retrieve it
        IFacade &facade = Facade::getInstance("FacadeTestKey7");

        std::vector<std::string> data_local;
        data_local.push_back("1");
        data_local.push_back("2");
        data_local.push_back("3");
        Proxy proxy_local("hasProxyTest", &data_local);

        facade.registerProxy( &proxy_local );

        // assert that the model.hasProxy method returns true
        // for that proxy name
        ensure( "Expecting facade.hasProxy('hasProxyTest') == true", facade.hasProxy("hasProxyTest"));
    }

    template<> template<>
    void object::test<8>(void)
    {
        set_test_name("testHasMediator");

        IFacade &facade = Facade::getInstance("FacadeTestKey8");
        std::string str("Sprite");
        Mediator mediator_local("facadeHasMediatorTest", &str);

        // register a Mediator
        facade.registerMediator(&mediator_local);

        // assert that the facade.hasMediator method returns true
        // for that mediator name
        ensure( "Expecting facade.hasMediator('facadeHasMediatorTest') == true",
                 facade.hasMediator("facadeHasMediatorTest"));

        facade.removeMediator("facadeHasMediatorTest");

        // assert that the facade.hasMediator method returns false
        // for that mediator name
        ensure("Expecting facade.hasMediator('facadeHasMediatorTest') == false",
                facade.hasMediator("facadeHasMediatorTest") == false);
    }

    template<> template<>
    void object::test<9>(void)
    {
        set_test_name("testHasCommand");

        // register the ControllerTestCommand to handle 'hasCommandTest' notes
        IFacade &facade = Facade::getInstance("FacadeTestKey9");
        data::FacadeTestCommand facade_command;
        facade.registerCommand("facadeHasCommandTest", &facade_command);

        // test that hasCommand returns true for hasCommandTest notifications
        ensure( "Expecting facade.hasCommand('facadeHasCommandTest') == true",
               facade.hasCommand("facadeHasCommandTest"));

        // Remove the Command from the Controller
        facade.removeCommand("facadeHasCommandTest");

        // test that hasCommand returns false for hasCommandTest notifications
        ensure("Expecting facade.hasCommand('facadeHasCommandTest') == false",
              facade.hasCommand("facadeHasCommandTest") == false );
    }

    template<> template<>
    void object::test<10>(void)
    {
        set_test_name("testHasCoreAndRemoveCore");

        // assert that the Facade.hasCore method returns false first
        ensure("Expecting facade.hasCore('FacadeTestKey10') == false",
               Facade::hasCore("FacadeTestKey10") == false);

        // register a Core
        IFacade& facade = Facade::getInstance("FacadeTestKey10");

        // assert that the Facade.hasCore method returns true now that a Core is registered
        ensure("Expecting facade.hasCore('FacadeTestKey10') == true",
                Facade::hasCore("FacadeTestKey10"));

        // remove the Core
        Facade::removeCore("FacadeTestKey10");

        // assert that the Facade.hasCore method returns false now that the core has been removed.
        ensure("Expecting facade.hasCore('FacadeTestKey10') == false",
               Facade::hasCore("FacadeTestKey10") == false);
    }

    template<> template<>
    void object::test<11>(void)
    {
        set_test_name("testListCores");

        Facade::CoreNames aggregate = Facade::listCores();
        do
        {
            Facade::CoreNames::element_type::Iterator iterator = aggregate->getIterator();

            std::size_t counter = 0;
            while(iterator->moveNext())
                ++counter;
            // assert that the Facade.hasCore method returns false first
            ensure_equals("Expecting facade.listCores() == 10", counter, 10);

            // Create new facade core
            Facade::getInstance("FacadeTestKey11");

        }while (false);

        do
        {
            std::size_t counter = 0;
            Facade::CoreNames::element_type::Iterator iterator = aggregate->getIterator();
#if defined(_DEBUG) || defined(DEBUG)
            std::cout << std::endl << "List of cores:" << std::endl;
#endif
            while(iterator->moveNext())
            {
                ++counter;
#if defined(_DEBUG) || defined(DEBUG)
                std::cout <<counter << "." << iterator->getCurrent() << std::endl;;
#endif
            }

            // assert that the Facade.hasCore method returns false first
            ensure_equals("Expecting facade.listCores() == 11", counter, 11);
        }while (false);
    }

    template<> template<>
    void object::test<12>(void)
    {
        set_test_name("testFacadeInheritance");

        // get Facade
        data::FacadeTestInheritance& facade = data::FacadeTestInheritance::getInstance();

        ensure_equals("Expecting facade.initializeNotifierCalled = Called!!!", *(facade.initializeNotifierCalled), "Called!!!");

        ensure_equals("Expecting facade.initializeFacadeCalled = Called!!!", (*facade.initializeFacadeCalled), "Called!!!");
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.security.crypto.password;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Test;

@SuppressWarnings("deprecation")
public class Md4PasswordEncoderTests {

	@Test
	public void testEncodeUnsaltedPassword() {
		Md4PasswordEncoder md4 = new Md4PasswordEncoder();
		md4.setEncodeHashAsBase64(true);
		assertThat(md4.matches("ww_uni123", "8zobtq72iAt0W6KNqavGwg==")).isTrue();
	}

	@Test
	public void testEncodeSaltedPassword() {
		Md4PasswordEncoder md4 = new Md4PasswordEncoder();
		md4.setEncodeHashAsBase64(true);
		assertThat(md4.matches("ww_uni123", "{Alan K Stewart}ZplT6P5Kv6Rlu6W4FIoYNA==")).isTrue();
	}

	@Test
	public void testEncodeNullPassword() {
		Md4PasswordEncoder md4 = new Md4PasswordEncoder();
		md4.setEncodeHashAsBase64(true);
		assertThat(md4.matches(null, "MdbP4NFq6TG3PFnX4MCJwA==")).isTrue();
	}

	@Test
	public void testEncodeEmptyPassword() {
		Md4PasswordEncoder md4 = new Md4PasswordEncoder();
		md4.setEncodeHashAsBase64(true);
		assertThat(md4.matches(null, "MdbP4NFq6TG3PFnX4MCJwA==")).isTrue();
	}

	@Test
	public void testNonAsciiPasswordHasCorrectHash() {
		Md4PasswordEncoder md4 = new Md4PasswordEncoder();
		assertThat(md4.matches("\u4F60\u597d", "a7f1196539fd1f85f754ffd185b16e6e")).isTrue();
	}

	@Test
	public void testEncodedMatches() {
		String rawPassword = "password";
		Md4PasswordEncoder md4 = new Md4PasswordEncoder();
		String encodedPassword = md4.encode(rawPassword);

		assertThat(md4.matches(rawPassword, encodedPassword)).isTrue();
	}

	@Test
	public void javadocWhenHasSaltThenMatches() {
		Md4PasswordEncoder encoder = new Md4PasswordEncoder();
		assertThat(encoder.matches("password", "{thisissalt}6cc7924dad12ade79dfb99e424f25260"));
	}
}


text:
import { SassyProjectPage } from './app.po';

describe('sassy-project App', function() {
  let page: SassyProjectPage;

  beforeEach(() => {
    page = new SassyProjectPage();
  });

  it('should display message saying app works', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('app works!');
  });
});


text:
package com.alipay.api.domain;

import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;

/**
 * 商户门店信息
 *
 * @author auto create
 * @since 1.0, 2017-06-20 21:12:59
 */
public class ShopQueryInfo extends AlipayObject {

	private static final long serialVersionUID = 8548794624517432679L;

	/**
	 * 门店地址
	 */
	@ApiField("address")
	private String address;

	/**
	 * 是否包含同mid下的其他pid的店铺
	 */
	@ApiField("is_include_cognate")
	private Boolean isIncludeCognate;

	/**
	 * 纬度
	 */
	@ApiField("latitude")
	private String latitude;

	/**
	 * 经度
	 */
	@ApiField("longitude")
	private String longitude;

	/**
	 * 门店名称
	 */
	@ApiField("name")
	private String name;

	/**
	 * 商户pid
	 */
	@ApiField("pid")
	private String pid;

	/**
	 * 内部门店ID
	 */
	@ApiField("shop_id")
	private String shopId;

	/**
	 * 门店类型
	 */
	@ApiField("shop_type")
	private String shopType;

	/**
	 * 外部门店ID
	 */
	@ApiField("store_id")
	private String storeId;

	public String getAddress() {
		return this.address;
	}
	public void setAddress(String address) {
		this.address = address;
	}

	public Boolean getIsIncludeCognate() {
		return this.isIncludeCognate;
	}
	public void setIsIncludeCognate(Boolean isIncludeCognate) {
		this.isIncludeCognate = isIncludeCognate;
	}

	public String getLatitude() {
		return this.latitude;
	}
	public void setLatitude(String latitude) {
		this.latitude = latitude;
	}

	public String getLongitude() {
		return this.longitude;
	}
	public void setLongitude(String longitude) {
		this.longitude = longitude;
	}

	public String getName() {
		return this.name;
	}
	public void setName(String name) {
		this.name = name;
	}

	public String getPid() {
		return this.pid;
	}
	public void setPid(String pid) {
		this.pid = pid;
	}

	public String getShopId() {
		return this.shopId;
	}
	public void setShopId(String shopId) {
		this.shopId = shopId;
	}

	public String getShopType() {
		return this.shopType;
	}
	public void setShopType(String shopType) {
		this.shopType = shopType;
	}

	public String getStoreId() {
		return this.storeId;
	}
	public void setStoreId(String storeId) {
		this.storeId = storeId;
	}

}


text:
import boto.rds2
import boto.regioninfo
from unittest import TestCase
from mock import patch, Mock
from monocyte.handler import rds2, Resource

SNAPSHOT_IDENTIFIER = "mySnapshotIdentifier"

INSTANCE_IDENTIFIER = "myInstanceIdentifier"

class RDSInstanceTest(TestCase):
    def setUp(self):
        self.rds2_mock = patch("monocyte.handler.rds2.rds2").start()
        self.instance_mock = self._given_instance_mock()

        self.positive_fake_region = Mock(boto.regioninfo.RegionInfo)
        self.positive_fake_region.name = "allowed_region"
        self.negative_fake_region = Mock(boto.regioninfo.RegionInfo)
        self.negative_fake_region.name = "forbidden_region"
        self.resource_type = "rds2 Instance"
        self.rds2_mock.regions.return_value = [self.positive_fake_region, self.negative_fake_region]
        self.logger_mock = patch("monocyte.handler.logging").start()
        self.rds_instance = rds2.Instance(lambda region_name: True)

    def tearDown(self):
        patch.stopall()

    def test_fetch_unwanted_resources_filtered_by_region(self):
        self.rds2_mock.connect_to_region.return_value.describe_db_instances.return_value = \
            self._given_db_instances_response()

        only_resource = list(self.rds_instance.fetch_unwanted_resources())[0]
        self.assertEqual(only_resource.wrapped, self.instance_mock)

    def test_fetch_unwanted_resources_filtered_by_ignored_resources(self):
        self.rds_instance.ignored_resources = [INSTANCE_IDENTIFIER]
        empty_list = list(self.rds_instance.fetch_unwanted_resources())
        self.assertEqual(empty_list, [])

    def test_to_string(self):
        self.rds2_mock.connect_to_region.return_value.describe_db_instances.return_value = \
            self._given_db_instances_response()

        only_resource = list(self.rds_instance.fetch_unwanted_resources())[0]
        resource_string = self.rds_instance.to_string(only_resource)

        self.assertTrue(self.instance_mock["DBInstanceIdentifier"] in resource_string)
        self.assertTrue(self.instance_mock["DBInstanceStatus"] in resource_string)

    def test_skip_deletion_in_dry_run(self):
        self.rds_instance.dry_run = True
        resource = Resource(self.instance_mock, self.resource_type, self.instance_mock["DBInstanceIdentifier"],
                            self.instance_mock["InstanceCreateTime"], self.negative_fake_region.name)

        deleted_resource = self.rds_instance.delete(resource)

        self.assertEqual(None, deleted_resource)

    def test_skip_deletion_if_already_deleted(self):
        self.rds_instance.dry_run = False
        self.instance_mock["DBInstanceStatus"] = rds2.DELETION_STATUS

        resource = Resource(self.instance_mock, self.resource_type, self.instance_mock["DBInstanceIdentifier"],
                            self.instance_mock["InstanceCreateTime"], self.negative_fake_region.name)

        self.assertRaises(Warning, self.rds_instance.delete, resource)

    def test_does_delete_if_not_dry_run(self):
        self.rds_instance.dry_run = False

        resource = Resource(self.instance_mock, self.resource_type, self.instance_mock["DBInstanceIdentifier"],
                            self.instance_mock["InstanceCreateTime"], self.negative_fake_region.name)

        self.rds2_mock.connect_to_region.return_value.delete_db_instance.return_value = \
            self._given_delete_db_instance_response()

        self.rds_instance.delete(resource)
        self.logger_mock.getLogger.return_value.info.assert_called_with(rds2.DELETION_STATEMENT %
                                                                        self.instance_mock["DBInstanceIdentifier"])

        self.assertEqual(self.instance_mock["DBInstanceIdentifier"], resource.wrapped["DBInstanceIdentifier"])

    def _given_db_instances_response(self):
        return {
            'DescribeDBInstancesResponse': {
                'DescribeDBInstancesResult': {
                    'DBInstances': [self.instance_mock]
                }
            }
        }

    def _given_instance_mock(self):
        return {
            "DBInstanceIdentifier": INSTANCE_IDENTIFIER,
            "DBInstanceStatus": "myStatus",
            "InstanceCreateTime": "01.01.2015"
        }

    def _given_delete_db_instance_response(self):
        return {
            "DeleteDBInstanceResponse": {
                "DeleteDBInstanceResult": {
                    "DBInstance": {
                        "DBInstanceStatus": "deleting",
                        "DBInstanceIdentifier": self.instance_mock["DBInstanceIdentifier"],
                        "InstanceCreateTime": self.instance_mock["InstanceCreateTime"]
                    }
                }
            }
        }

class RDSSnapshotTest(TestCase):
    def setUp(self):
        self.rds2_mock = patch("monocyte.handler.rds2.rds2").start()
        self.snapshot_mock = self._given_snapshot_mock()

        self.positive_fake_region = Mock(boto.regioninfo.RegionInfo)
        self.positive_fake_region.name = "allowed_region"
        self.negative_fake_region = Mock(boto.regioninfo.RegionInfo)
        self.negative_fake_region.name = "forbidden_region"
        self.resource_type = "rds2 Snapshot"
        self.rds2_mock.regions.return_value = [self.positive_fake_region, self.negative_fake_region]
        self.logger_mock = patch("monocyte.handler.logging").start()
        self.rds_snapshot = rds2.Snapshot(lambda region_name: True)

    def tearDown(self):
        patch.stopall()

    def test_fetch_unwanted_resources_filtered_by_region(self):
        self.rds2_mock.connect_to_region.return_value.describe_db_snapshots.return_value = \
            self._given_db_snapshot_response()

        only_resource = list(self.rds_snapshot.fetch_unwanted_resources())[0]
        self.assertEqual(only_resource.wrapped, self.snapshot_mock)

    def test_fetch_unwanted_resources_filtered_by_ignored_resources(self):
        self.rds_snapshot.ignored_resources = [SNAPSHOT_IDENTIFIER]
        empty_list = list(self.rds_snapshot.fetch_unwanted_resources())
        self.assertEqual(empty_list, [])

    def test_to_string(self):
        self.rds2_mock.connect_to_region.return_value.describe_db_snapshots.return_value = \
            self._given_db_snapshot_response()

        only_resource = list(self.rds_snapshot.fetch_unwanted_resources())[0]
        resource_string = self.rds_snapshot.to_string(only_resource)

        self.assertTrue(self.snapshot_mock["DBSnapshotIdentifier"] in resource_string)
        self.assertTrue(self.snapshot_mock["Status"] in resource_string)

    def test_skip_deletion_in_dry_run(self):
        self.rds_snapshot.dry_run = True
        resource = Resource(self.snapshot_mock, self.resource_type, self.snapshot_mock["DBSnapshotIdentifier"],
                            self.snapshot_mock["SnapshotCreateTime"], self.negative_fake_region.name)

        deleted_resource = self.rds_snapshot.delete(resource)

        self.assertEqual(None, deleted_resource)

    def test_skip_deletion_if_already_deleted(self):
        self.rds_snapshot.dry_run = False
        self.snapshot_mock["Status"] = rds2.DELETION_STATUS

        resource = Resource(self.snapshot_mock, self.resource_type, self.snapshot_mock["DBSnapshotIdentifier"],
                            self.snapshot_mock["SnapshotCreateTime"], self.negative_fake_region.name)

        self.assertRaises(Warning, self.rds_snapshot.delete, resource)

    def test_skip_deletion_if_autogenerated(self):
        self.rds_snapshot.dry_run = False
        self.snapshot_mock["SnapshotType"] = rds2.AUTOMATED_STATUS

        resource = Resource(self.snapshot_mock, self.resource_type, self.snapshot_mock["DBSnapshotIdentifier"],
                            self.snapshot_mock["SnapshotCreateTime"], self.negative_fake_region.name)

        self.assertRaises(Warning, self.rds_snapshot.delete, resource)

    def test_does_delete_if_not_dry_run(self):
        self.rds_snapshot.dry_run = False
        resource = Resource(self.snapshot_mock, self.resource_type, self.snapshot_mock["DBSnapshotIdentifier"],
                            self.snapshot_mock["SnapshotCreateTime"], self.negative_fake_region.name)

        self.rds2_mock.connect_to_region.return_value.delete_db_snapshot.return_value = \
            self._given_delete_db_snapshot_response()

        self.rds_snapshot.delete(resource)
        self.logger_mock.getLogger.return_value.info.assert_called_with(rds2.DELETION_STATEMENT %
                                                                        self.snapshot_mock["DBSnapshotIdentifier"])
        self.assertEqual(self.snapshot_mock["DBSnapshotIdentifier"], resource.wrapped["DBSnapshotIdentifier"])

    def _given_db_snapshot_response(self):
        return {
            "DescribeDBSnapshotsResponse": {
                "DescribeDBSnapshotsResult": {
                    "DBSnapshots": [self.snapshot_mock]
                }
            }
        }

    def _given_snapshot_mock(self):
        return {
            "DBSnapshotIdentifier": SNAPSHOT_IDENTIFIER,
            "Status": "myStatus",
            "SnapshotType": "manual",
            "SnapshotCreateTime": "01.01.2015"
        }

    def _given_delete_db_snapshot_response(self):
        return {
            "DeleteDBSnapshotResponse": {
                "DeleteDBSnapshotResult": {
                    "DBSnapshot": {
                        "Status": "deleted",
                        "DBSnapshotIdentifier": self.snapshot_mock["DBSnapshotIdentifier"],
                        "SnapshotCreateTime": self.snapshot_mock["SnapshotCreateTime"]
                    }
                }
            }
        }


text:
package com.twitter.heron.scheduler;

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

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import com.twitter.heron.api.HeronTopology;
import com.twitter.heron.api.bolt.BaseBasicBolt;
import com.twitter.heron.api.bolt.BasicOutputCollector;
import com.twitter.heron.api.generated.TopologyAPI;
import com.twitter.heron.api.spout.BaseRichSpout;
import com.twitter.heron.api.spout.SpoutOutputCollector;
import com.twitter.heron.api.topology.OutputFieldsDeclarer;
import com.twitter.heron.api.topology.TopologyBuilder;
import com.twitter.heron.api.topology.TopologyContext;
import com.twitter.heron.api.tuple.Tuple;
import com.twitter.heron.proto.system.ExecutionEnvironment;
import com.twitter.heron.proto.system.PackingPlans;
import com.twitter.heron.scheduler.utils.LauncherUtils;
import com.twitter.heron.scheduler.utils.Runtime;
import com.twitter.heron.spi.common.Config;
import com.twitter.heron.spi.common.Key;
import com.twitter.heron.spi.packing.IPacking;
import com.twitter.heron.spi.packing.PackingPlan;
import com.twitter.heron.spi.packing.PackingPlan.ContainerPlan;
import com.twitter.heron.spi.scheduler.ILauncher;
import com.twitter.heron.spi.scheduler.LauncherException;
import com.twitter.heron.spi.statemgr.SchedulerStateManagerAdaptor;
import com.twitter.heron.spi.utils.PackingTestUtils;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest(LauncherUtils.class)
public class LaunchRunnerTest {
  private static final String TOPOLOGY_NAME = "testTopology";
  private static final String CLUSTER = "testCluster";
  private static final String ROLE = "testRole";
  private static final String ENVIRON = "testEnviron";
  private static final String SUBMIT_USER = "testUser";
  private static final String BUILD_VERSION = "live";
  private static final String BUILD_USER = "user";

  public static TopologyAPI.Topology createTopology(com.twitter.heron.api.Config heronConfig) {
    TopologyBuilder builder = new TopologyBuilder();
    builder.setSpout("spout-1", new BaseRichSpout() {
      private static final long serialVersionUID = -762965195665496156L;

      public void declareOutputFields(OutputFieldsDeclarer declarer) {
      }

      public void open(
          Map<String, Object> conf,
          TopologyContext context,
          SpoutOutputCollector collector) {
      }

      public void nextTuple() {
      }
    }, 2);
    builder.setBolt("bolt-1", new BaseBasicBolt() {
      private static final long serialVersionUID = -5738458486388778812L;

      public void execute(Tuple input, BasicOutputCollector collector) {
      }

      public void declareOutputFields(OutputFieldsDeclarer declarer) {
      }
    }, 1);
    HeronTopology heronTopology = builder.createTopology();

    return heronTopology.
        setName(TOPOLOGY_NAME).
        setConfig(heronConfig).
        setState(TopologyAPI.TopologyState.RUNNING).
        getTopology();
  }

  private static Config createRunnerConfig() {
    Config config = mock(Config.class);
    when(config.getStringValue(Key.TOPOLOGY_NAME)).thenReturn(TOPOLOGY_NAME);
    when(config.getStringValue(Key.CLUSTER)).thenReturn(CLUSTER);
    when(config.getStringValue(Key.ROLE)).thenReturn(ROLE);
    when(config.getStringValue(Key.ENVIRON)).thenReturn(ENVIRON);
    when(config.getStringValue(Key.SUBMIT_USER)).thenReturn(SUBMIT_USER);
    when(config.getStringValue(Key.BUILD_VERSION)).thenReturn(BUILD_VERSION);
    when(config.getStringValue(Key.BUILD_USER)).thenReturn(BUILD_USER);

    return config;
  }

  private static Config createRunnerRuntime() throws Exception {
    return createRunnerRuntime(new com.twitter.heron.api.Config());
  }

  private static Config createRunnerRuntime(
      com.twitter.heron.api.Config topologyConfig) throws Exception {
    Config runtime = spy(Config.newBuilder().build());
    ILauncher launcher = mock(ILauncher.class);
    IPacking packing = mock(IPacking.class);
    SchedulerStateManagerAdaptor adaptor = mock(SchedulerStateManagerAdaptor.class);
    TopologyAPI.Topology topology = createTopology(topologyConfig);

    doReturn(launcher).when(runtime).get(Key.LAUNCHER_CLASS_INSTANCE);
    doReturn(adaptor).when(runtime).get(Key.SCHEDULER_STATE_MANAGER_ADAPTOR);
    doReturn(topology).when(runtime).get(Key.TOPOLOGY_DEFINITION);

    PackingPlan packingPlan = mock(PackingPlan.class);
    when(packingPlan.getContainers()).thenReturn(
        new HashSet<ContainerPlan>());
    when(packingPlan.getComponentRamDistribution()).thenReturn("ramdist");
    when(packingPlan.getId()).thenReturn("packing_plan_id");
    Set<ContainerPlan> containerPlans = new HashSet<>();
    containerPlans.add(PackingTestUtils.testContainerPlan(1)); // just need it to be of size 1
    when(packingPlan.getContainers()).thenReturn(containerPlans);
    when(packing.pack()).thenReturn(packingPlan);

    LauncherUtils mockLauncherUtils = mock(LauncherUtils.class);
    when(mockLauncherUtils.createPackingPlan(any(Config.class), any(Config.class)))
        .thenReturn(packingPlan);
    PowerMockito.spy(LauncherUtils.class);
    PowerMockito.doReturn(mockLauncherUtils).when(LauncherUtils.class, "getInstance");

    return runtime;
  }

  private static SchedulerStateManagerAdaptor createTestSchedulerStateManager(Config runtime) {
    SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime);
    when(statemgr.setTopology(any(TopologyAPI.Topology.class), eq(TOPOLOGY_NAME))).
        thenReturn(true);
    when(statemgr.setPackingPlan(any(PackingPlans.PackingPlan.class), eq(TOPOLOGY_NAME))).
        thenReturn(true);
    when(statemgr.setExecutionState(
        any(ExecutionEnvironment.ExecutionState.class), eq(TOPOLOGY_NAME))).
        thenReturn(true);
    return statemgr;
  }

  @Before
  public void setUp() throws Exception {
  }

  @Test
  public void testTrimTopology() throws Exception {
    LaunchRunner launchRunner = new LaunchRunner(createRunnerConfig(), createRunnerRuntime());
    TopologyAPI.Topology topologyBeforeTrimmed = createTopology(new com.twitter.heron.api.Config());
    TopologyAPI.Topology topologyAfterTrimmed = launchRunner.trimTopology(topologyBeforeTrimmed);

    for (TopologyAPI.Spout spout : topologyBeforeTrimmed.getSpoutsList()) {
      assertTrue(spout.getComp().hasSerializedObject());
    }

    for (TopologyAPI.Bolt bolt : topologyBeforeTrimmed.getBoltsList()) {
      assertTrue(bolt.getComp().hasSerializedObject());
    }

    for (TopologyAPI.Spout spout : topologyAfterTrimmed.getSpoutsList()) {
      assertFalse(spout.getComp().hasSerializedObject());
    }

    for (TopologyAPI.Bolt bolt : topologyAfterTrimmed.getBoltsList()) {
      assertFalse(bolt.getComp().hasSerializedObject());
    }
  }

  @Test
  public void testCreateExecutionState() throws Exception {
    LaunchRunner launchRunner = new LaunchRunner(createRunnerConfig(), createRunnerRuntime());
    ExecutionEnvironment.ExecutionState executionState = launchRunner.createExecutionState();

    assertTrue(executionState.isInitialized());

    assertEquals(TOPOLOGY_NAME, executionState.getTopologyName());
    assertEquals(CLUSTER, executionState.getCluster());
    assertEquals(ROLE, executionState.getRole());
    assertEquals(ENVIRON, executionState.getEnviron());
    assertEquals(SUBMIT_USER, executionState.getSubmissionUser());

    assertNotNull(executionState.getTopologyId());
    assertTrue(executionState.getSubmissionTime() <= (System.currentTimeMillis() / 1000));

    assertNotNull(executionState.getReleaseState());
    assertNotNull(executionState.getReleaseState().getReleaseVersion());
    assertNotNull(executionState.getReleaseState().getReleaseUsername());
  }

  @Test(expected = LauncherException.class)
  public void testSetExecutionStateFail() throws Exception {
    Config runtime = createRunnerRuntime();
    Config config = createRunnerConfig();
    ILauncher launcher = Runtime.launcherClassInstance(runtime);

    LaunchRunner launchRunner = new LaunchRunner(config, runtime);

    SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime);
    when(statemgr.setExecutionState(
        any(ExecutionEnvironment.ExecutionState.class), eq(TOPOLOGY_NAME))).
        thenReturn(false);

    try {
      launchRunner.call();
    } finally {
      verify(launcher, never()).launch(any(PackingPlan.class));
    }
  }

  @Test(expected = LauncherException.class)
  public void testSetTopologyFail() throws Exception {
    Config runtime = createRunnerRuntime();
    Config config = createRunnerConfig();
    ILauncher launcher = Runtime.launcherClassInstance(runtime);

    LaunchRunner launchRunner = new LaunchRunner(config, runtime);

    SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime);
    when(statemgr.setTopology(any(TopologyAPI.Topology.class), eq(TOPOLOGY_NAME)))
        .thenReturn(false);

    try {
      launchRunner.call();
    } finally {
      verify(launcher, never()).launch(any(PackingPlan.class));
    }
  }

  @Test(expected = LauncherException.class)
  public void testLaunchFailCleanUp() throws Exception {
    Config runtime = createRunnerRuntime();
    Config config = createRunnerConfig();
    ILauncher launcher = Runtime.launcherClassInstance(runtime);
    SchedulerStateManagerAdaptor statemgr = createTestSchedulerStateManager(runtime);

    LaunchRunner launchRunner = new LaunchRunner(config, runtime);
    when(launcher.launch(any(PackingPlan.class))).thenReturn(false);

    try {
      launchRunner.call();
    } finally {
      // Verify set && clean
      verify(statemgr).setTopology(any(TopologyAPI.Topology.class), eq(TOPOLOGY_NAME));
      verify(statemgr).setExecutionState(
          any(ExecutionEnvironment.ExecutionState.class), eq(TOPOLOGY_NAME));
      verify(statemgr).deleteExecutionState(eq(TOPOLOGY_NAME));
      verify(statemgr).deleteTopology(eq(TOPOLOGY_NAME));
    }
  }

  @Test
  public void testCallSuccess() throws Exception {
    doTestLaunch(new com.twitter.heron.api.Config());
  }

  @Test
  public void testCallSuccessWithDifferentNumContainers() throws Exception {
    com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config();
    topologyConfig.setNumStmgrs(2); // packing plan has only 1 container plan but numStmgrs is 2

    doTestLaunch(topologyConfig);
  }

  private void doTestLaunch(com.twitter.heron.api.Config topologyConfig) throws Exception {
    Config runtime = createRunnerRuntime(topologyConfig);
    Config config = createRunnerConfig();
    ILauncher launcher = Runtime.launcherClassInstance(runtime);
    SchedulerStateManagerAdaptor statemgr = createTestSchedulerStateManager(runtime);

    LaunchRunner launchRunner = new LaunchRunner(config, runtime);
    when(launcher.launch(any(PackingPlan.class))).thenReturn(true);

    launchRunner.call();

    // Verify set && clean
    verify(statemgr).setTopology(any(TopologyAPI.Topology.class), eq(TOPOLOGY_NAME));
    verify(statemgr).setExecutionState(
        any(ExecutionEnvironment.ExecutionState.class), eq(TOPOLOGY_NAME));
    verify(statemgr, never()).deleteExecutionState(eq(TOPOLOGY_NAME));
    verify(statemgr, never()).deleteTopology(eq(TOPOLOGY_NAME));
  }
}


text:
#ifndef ASTINT_H_
#define ASTINT_H_
#include "Expression.h"

class AstInt:public Expression
{
private:
  long int i;
  AstInt(long int i);
public:
  static AstInt* make(long int i);
  virtual string to_string(int d = 0);
  virtual string to_value();
  long int get_int();
  virtual Expression* substitute(Expression* e1,
	        		  Expression* e2);
  virtual bool operator==(const Expression& other);
};

#endif /* ASTINT_H_ */


text:
.. _developers-guidlines:

=============================
Internal Development Workflow
=============================

This is a brief document about the Neural Monkey development workflow. Its
primary aim is to describe the environment around the Github repository
(e.g. continuous integration tests, documentation), pull requests, code-review,
etc.

This document is written chronologically, from the point of view of a
contributor.

Creating an issue
-----------------

Everytime there is a need to change the codebase, the contributor should create
a corresponing issue on Github.

The name of the issue should be comprehensive, and should summarize the issue in
less than 10 words.  In the issue description, all the relevant information
should be mentioned, and, if applicable, a sketch of the solution should be
given so the fashion and method of the solution can be subject to further
discussion.

Labels
******

There is a number of label tags to use to provide an easier way to orient among
the issues. Here is an explanation of some of them, so they are not used
incorrectly (notably, there is a slight difference between "enhancement" and
"feature").

- bug: Use when there is something wrong in the current codebase that needs to
  be fixed. For example, "Random seeds are not working"
- documentation: Use when the main topic of the issue or pull request is to
  contribute to the documentation (be it a rst document or a request for more
  docstrings)
- tests: Similarly to documentation, use if the main topic of the issue is to
  write a test or to do changes to the testing process itself.
- feature: A request for implementing a feature regarding the training of the
  models or the models themselves, e.g. "Minimum risk training" or
  "Implementation of conditional GRU".
- enhancement: A request for implementing a feature to Neural Monkey aimed at
  improving the user experience with the package, e.g. "GPU profiling" or
  "Logging of config building".
- help wanted: Used as an additional label, which specify that solving the issue
  is suitable either for new contributors or for researchers who want to try out
  a feature, which would be otherwise implemented after a longer time.
- refactor: Refactor issues are requests for cleaning the codebase, using better
  ways to achieve the same results, conforming to a future API, etc. For
  example, "Rewrite decoder using decorators"

.. todo::
   Replace text with label pictures from Github

Selecting an issue to work on and assigning people
--------------------------------------------------

.. note:: If you want to start working on something and don't have a preference,
   check out the issues labeled "Help wanted"

When you decide to work on an issue, assign yourself to it and describe your
plans on how you will proceed (in case there is no solution sketch provided in
the issue description). This way, others may comment on your plans prior to the
work, which can save a lot of time.

Please make sure that you put all additional information as a comment to the
issue in case the issue has been discussed elsewhere.

Creating a branch
-----------------

Prior to writing code (or at least before the first commit), you should create a
branch for solution of the issue. This command creates a new branch called
``your_branch_name`` and switches your working copy to that branch:

.. code-block:: bash

   $ git checkout -b your_branch_name

Writing code
------------

On the new branch, you can make changes and commit, until your solution is done.

It is worth noting that we are trying to keep our code clean by enforcing some
code writing rules and guidelines. These are automatically check by Travis CI on
each push to the Github repository. Here is a list of tools used to check the
quality of the code:

* `pylint <https://www.pylint.org>`_
* `pycodestyle <http://pypi.python.org/pypi/pycodestyle>`_
* `mypy <http://mypy-lang.org>`_
* `markdownlint <https://github.com/mivok/markdownlint>`_

.. todo:: provide short description to the tools, check that markdownlint has
          correct URL

You can run the tests on your local machine by using scripts (and requirements)
from the ``tests/`` directory of this package,

This is a usual mantra that you can use for committing and pushing to the remote
branch in the repository:

.. code-block:: bash

   $ git add .
   $ git commit -m 'your commit message'
   $ git push origin your_branch_name

.. note:: If you are working on a branch with someone else, it is always a good
          idea to do a ``git pull --rebase`` before pushing. This command
          updates your branch with remote changes and apply your new commits on
          top of them.

.. warning:: If your commit message contains the string ``[ci skip]`` the
	     continuous integration tests are not run. However, try not to use
	     this feature unless you know what you're doing.

Creating a pull request
-----------------------

Whenever you want to add a feature or push a bugfix, you should make a new pull
request, which can be reviewed and merged by someone else. The typical workflow
should be as follows:

1. Create a new branch, make your changes and push them to the repository.

2. You should now see the new branch on the Github project page. When you open
   the branch page, click on "Create Pull request" button.

3. When the pull request is created, the continuous integration tests are run on
   Travis. You can see the status of the test run on the pull request
   page. There is also a link to Travis so you can inspect the results of the
   test run, and make additional changes in order to make the tests successful,
   if needed. Additionally to the code quality checking tools, unit and
   regression tests are run as well.

When you create a pull request, assign one or two people to do the review.

Code review and merging
-----------------------

Your pull requests should always be subject to code review. After you create the
pull request, select one or two contributors and assign them to make a review.

This phase consists of discussion about the introduced changes, suggestions, and
another requirements made by the reviewers. Anyone who wants to do a review can
contribute, the reviewer roles are not considered exclusive.

After all of the reviewers' comments have been addressed and the reviewers
approved the pull request, the pull request can be merged. It is usually a good
idea to rebase the code to the recent version of master. Assuming your working
copy is switched to the **master** branch, do:

.. code-block:: bash

   $ git pull --rebase
   $ git checkout your_branch_name
   $ git rebase master

These commands first update your local copy of master from the remote
repository, then switch your working copy to the ``your_branch_name`` branch,
and then rebases the branch on the updated master.

Rebasing is a process in which commits from a branch (``your_branch_name``) are
applied on a second branch (master), and the new HEAD is marked as the first
branch.

.. warning:: Rebasing is a process which overwrites history. Therefore be
             absolutely sure that you know what are you doing. Usually if you
             work on a branch alone, rebasing is a safe procedure.

When the branch is rebased, you have to force-push it to the repository:

.. code-block:: bash

   $ git push -f origin your_branch_name

This command overwrites the your branch in the remote repository with your local
branch (which is now rebased on master, and therefore, up-to-date)

.. note:: You can use rebasing also for updating your branch to work with newer
          versions of master instead of merging the master in the branch. Bear
          in mind though, that you should force-push these updates, so no-one
          works on the outdated version of the branch.

Finally, one more round of tests is run and if everything is OK, you can click
the "Merge pull request" button, which executes the merge. You can also click
another button to delete the ``your_branch_name`` branch from the repository
after the merge.

Documentation
-------------

Documentation related to GitHub is written in `Markdown
<https://daringfireball.net/projects/markdown/>`_ files, Python documentation
using `reStructuredText
<http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html>`_. This
concerns both the standalone documents (in ``/docs/``) and the docstrings in
source code.

Style of the Markdown files is automatically checked using `Markdownlint
<https://github.com/mivok/markdownlint>`_.


text:
package com.nrg.kelly.events.game;

import com.badlogic.gdx.ApplicationListener;

/**
 * Created by Andrew on 3/05/2015.
 */
public class PostBuildGameModuleEvent {

    private final ApplicationListener game;

    public PostBuildGameModuleEvent(ApplicationListener game) {
        this.game = game;
    }

    public ApplicationListener getGame() {
        return game;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/ingredient_detail_root"
    tools:ignore="MergeRootFrame"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/ingredient_detail_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        app:cardCornerRadius="4dp"
        app:cardElevation="24dp"
        app:cardUseCompatPadding="true">
        <fragment
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            class="com.github.st1hy.countthemcalories.activities.ingredientdetail.fragment.IngredientDetailFragment"
            tools:layout="@layout/ingredient_detail_content"
            android:tag="ingredient detail content"/>
    </android.support.v7.widget.CardView>
</FrameLayout>


text:
package octokit

import (
	"testing"
	"encoding/json"
	"github.com/stretchr/testify/assert"
)

func TestStatusesService_All(t *testing.T) {
	setup()
	defer tearDown()

	stubGet(t, "/repos/jingweno/gh/statuses/740211b9c6cd8e526a7124fe2b33115602fbc637", "statuses", nil)

	sha := "740211b9c6cd8e526a7124fe2b33115602fbc637"
	url, err := StatusesURL.Expand(M{"owner": "jingweno", "repo": "gh", "ref": sha})
	assert.NoError(t, err)

	statuses, err := client.Statuses(url).All()

	assert.Len(t, statuses, 2)
	firstStatus := statuses[0]
	assert.Equal(t, "pending", firstStatus.State)
	assert.Equal(t, "The Travis CI build is in progress", firstStatus.Description)
	assert.Equal(t, "https://travis-ci.org/jingweno/gh/builds/11911500", firstStatus.TargetURL)
}

func TestStatusesService_Create(t *testing.T) {
	setup()
	defer tearDown()

	sha := "740211b9c6cd8e526a7124fe2b33115602fbc637"
	url, err := StatusesURL.Expand(M{"owner": "jingweno", "repo": "gh", "ref": sha})
	assert.NoError(t, err)

	params := Status{
		State:       "success",
		TargetURL:   "https://example.com/build/status",
		Description: "The build succeeded!",
		Context:     "continuous-integration/jenkins",
	}
	wantReqBody, _ := json.Marshal(params)
	stubPost(t, "/repos/jingweno/gh/statuses/740211b9c6cd8e526a7124fe2b33115602fbc637",
		"create_status", nil, string(wantReqBody)+"\n", nil)

	status, result := client.Statuses(url).Create(params)

	assert.False(t, result.HasError())
	assert.Equal(t, "success", status.State)
	assert.Equal(t, "https://example.com/build/status", status.TargetURL)
	assert.Equal(t, "The build succeeded!", status.Description)
	assert.Equal(t, "continuous-integration/jenkins", status.Context)
}


text:
Final project for Visual Basic course

This project demonstrates a practical application of knowledge gained in programming using Visual Basic during the course including the basics of OOP, in particular encapsulation and inheritance.  The application is designed to help a small business to manage their customer records. The following features are present:
- adding, editing and deleting records;
- sorting records by different parameters;
- displaying records for certain time periods;
- generating and printing sales reports for chosen time period;
- generating and printing invoices to customers

## Class Diagram

![classdiagram](https://cloud.githubusercontent.com/assets/14193564/13039813/f79b732a-d39b-11e5-8a5d-9f35ed4cc502.png)

# Project Overview

![1](https://cloud.githubusercontent.com/assets/14193564/13062085/d692df36-d433-11e5-8c9c-f568a9360a2a.png)

Figure 1 Application Interface

# Usage Instructions

## Add Record

Pressing "Add Record" button will bring up a form where the information can be entered

![2](https://cloud.githubusercontent.com/assets/14193564/13062086/d69dd968-d433-11e5-9a66-7289cb040de6.png)

Figure 2 Adding a New Record

First name, surname and email address are required fields and if those are not entered a corresponding warning message will be displayed.

![3](https://cloud.githubusercontent.com/assets/14193564/13062087/d69f8f1a-d433-11e5-9881-c49bdafc3716.png)
![4](https://cloud.githubusercontent.com/assets/14193564/13062089/d6af89ce-d433-11e5-8cf9-f6b00d0c6eda.png)

Figure 3 Warning Message Examples

A product price is set according to the product name automatically thus the price field editing is disabled.

Expiry date is set automatically to be one year ahead of the payment date.

After all information had been filled and after pressing "OK" button the main window will be displayed again and the list of records will be updated to include the new record. The total number of customers and the total amount of sales will also be updated to reflect the changes made.

## Edit Record

In order to edit an existing record that record will need to be selected from the list first. If no record is being selected a warning message will appear.

![5](https://cloud.githubusercontent.com/assets/14193564/13062088/d6aef9d2-d433-11e5-86c6-a440b0812344.png)

Figure 4 Warning Message: Record needs to be selected

After selecting a record and pressing "Edit Record" button a form will be shown containing all the information for the selected record and any required editing can be performed.

Pressing "Cancel" button will discard any changes made. In order to save changes the user needs to press "OK" button. The main window will be displayed and the changes will be reflected in the records list.

## Delete Record

In order to delete a record that record needs to be selected first otherwise a warning message will be shown. After choosing a record to be deleted a confirmation message will be shown to ensure that the record is not being deleted by accident.

![6](https://cloud.githubusercontent.com/assets/14193564/13062090/d6b99c52-d433-11e5-8035-507feb9773ec.png)

Figure 5 Confirmation Message Upon Record Deletion

All changes including adding, editing and deleting records are saved in an XML file enabling to continue working with the list of records the next time the application is started and ensuring that the information is not lost. On application start up any records stored in the XML file are retrieved and displayed.

## Sort Records

The records can be sorted by customer's full name, country, email, product price and payment date by pressing buttons located above the aforementioned fields or from the menu Tools->Sort by.

![7](https://cloud.githubusercontent.com/assets/14193564/13062091/d6bc0578-d433-11e5-91d6-6fcf31f4d2c7.png)

Figure 6 Sorting Records

Records can also be sorted by certain month of a certain year by selecting the time period in the first date box located in the "Display Options" section. The month can be selected either by pressing left and right arrows or by clicking the month being displayed and selecting required month from the drop down list.

![8](https://cloud.githubusercontent.com/assets/14193564/13062092/d6c85bf2-d433-11e5-81c4-ef04fbb12522.png)

Figure 7 Selecting the Month

The year can be selected by clicking on the year field and pressing up and down arrows.
![9](https://cloud.githubusercontent.com/assets/14193564/13062079/d659672e-d433-11e5-9f4e-ec420e3626ed.png)

Figure 8 Selecting Year of the Month

It is also possible to display the records for the whole year by selecting the year from the second date box located in the "Display Options" section. The year can be chosen by pressing up and down arrows or by highlighting the year in the box and pressing up and down arrow buttons on the keyboard.

![10](https://cloud.githubusercontent.com/assets/14193564/13062081/d65fa512-d433-11e5-8c1c-a78fd3e40233.png)

Figure 9 Selecting the Year

The records for a selected time period can also be sorted by customer's name, country, email, product price and payment date the same way as mentioned earlier. Once the records for selected time period had been sorted by some value, a blue refresh button will appear. Clicking this button will restore unsorted order of the records for the currently selected time period. In order to display all the records (unsorted) contained in the list a green refresh button can be pressed. Alternatively this action can be performed from the menu Tools->Restore Records To Original State.

![11](https://cloud.githubusercontent.com/assets/14193564/13062080/d65e4140-d433-11e5-8bc3-3c7800633a74.png)

Figure 10 Restore Original Order of Records

## Printing

The sales reports for the selected time periods and the invoices for a selected record can be printed from the application by pressing the corresponding buttons located in the "Printing Options" section or from the menu File->Print.

![12](https://cloud.githubusercontent.com/assets/14193564/13062082/d661d9cc-d433-11e5-8925-1eb249fe27ba.png)

Figure 11 Printing and Pint Preview Options

The sales reports and the invoices for selected records can also be previewed before printing by pressing the corresponding buttons or from the menu File->Print Preview.

![13](https://cloud.githubusercontent.com/assets/14193564/13062083/d664f7d8-d433-11e5-9b2b-f7f27632cedb.png)
![14](https://cloud.githubusercontent.com/assets/14193564/13062084/d66f4f8a-d433-11e5-8939-31788a85a5fa.png)

Figure 12 Menu: Print and Print Preview


text:
package com.devbus.data;

public class Event {

	private String date;
	private String description;

	public Event(String date, String description) {
		super();
		this.date = date;
		this.description = description;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

}


text:
<!DOCTYPE html>

One

<marquee></marquee>


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * MS SQL Database Adapter Class
 *
 * Note: _DB is an extender class that the app controller
 * creates dynamically based on whether the query builder
 * class is being used or not.
 *
 * @package		CodeIgniter
 * @subpackage	Drivers
 * @category	Database
 * @author		EllisLab Dev Team
 * @link		https://codeigniter.com/user_guide/database/
 */
class CI_DB_mssql_driver extends CI_DB {

	/**
	 * Database driver
	 *
	 * @var	string
	 */
	public $dbdriver = 'mssql';

	// --------------------------------------------------------------------

	/**
	 * ORDER BY random keyword
	 *
	 * @var	array
	 */
	protected $_random_keyword = array('NEWID()', 'RAND(%d)');

	/**
	 * Quoted identifier flag
	 *
	 * Whether to use SQL-92 standard quoted identifier
	 * (double quotes) or brackets for identifier escaping.
	 *
	 * @var	bool
	 */
	protected $_quoted_identifier = TRUE;

	// --------------------------------------------------------------------

	/**
	 * Class constructor
	 *
	 * Appends the port number to the hostname, if needed.
	 *
	 * @param	array	$params
	 * @return	void
	 */
	public function __construct($params)
	{
		parent::__construct($params);

		if ( ! empty($this->port))
		{
			$this->hostname .= (DIRECTORY_SEPARATOR === '\\' ? ',' : ':').$this->port;
		}
	}

	// --------------------------------------------------------------------

	/**
	 * Non-persistent database connection
	 *
	 * @param	bool	$persistent
	 * @return	resource
	 */
	public function db_connect($persistent = FALSE)
	{
		$this->conn_id = ($persistent)
				? mssql_pconnect($this->hostname, $this->username, $this->password)
				: mssql_connect($this->hostname, $this->username, $this->password);

		if ( ! $this->conn_id)
		{
			return FALSE;
		}

		// ----------------------------------------------------------------

		// Select the DB... assuming a database name is specified in the config file
		if ($this->database !== '' && ! $this->db_select())
		{
			log_message('error', 'Unable to select database: '.$this->database);

			return ($this->db_debug === TRUE)
				? $this->display_error('db_unable_to_select', $this->database)
				: FALSE;
		}

		// Determine how identifiers are escaped
		$query = $this->query('SELECT CASE WHEN (@@OPTIONS | 256) = @@OPTIONS THEN 1 ELSE 0 END AS qi');
		$query = $query->row_array();
		$this->_quoted_identifier = empty($query) ? FALSE : (bool) $query['qi'];
		$this->_escape_char = ($this->_quoted_identifier) ? '"' : array('[', ']');

		return $this->conn_id;
	}

	// --------------------------------------------------------------------

	/**
	 * Select the database
	 *
	 * @param	string	$database
	 * @return	bool
	 */
	public function db_select($database = '')
	{
		if ($database === '')
		{
			$database = $this->database;
		}

		// Note: Escaping is required in the event that the DB name
		// contains reserved characters.
		if (mssql_select_db('['.$database.']', $this->conn_id))
		{
			$this->database = $database;
			$this->data_cache = array();
			return TRUE;
		}

		return FALSE;
	}

	// --------------------------------------------------------------------

	/**
	 * Execute the query
	 *
	 * @param	string	$sql	an SQL query
	 * @return	mixed	resource if rows are returned, bool otherwise
	 */
	protected function _execute($sql)
	{
		return mssql_query($sql, $this->conn_id);
	}

	// --------------------------------------------------------------------

	/**
	 * Begin Transaction
	 *
	 * @return	bool
	 */
	protected function _trans_begin()
	{
		return $this->simple_query('BEGIN TRAN');
	}

	// --------------------------------------------------------------------

	/**
	 * Commit Transaction
	 *
	 * @return	bool
	 */
	protected function _trans_commit()
	{
		return $this->simple_query('COMMIT TRAN');
	}

	// --------------------------------------------------------------------

	/**
	 * Rollback Transaction
	 *
	 * @return	bool
	 */
	protected function _trans_rollback()
	{
		return $this->simple_query('ROLLBACK TRAN');
	}

	// --------------------------------------------------------------------

	/**
	 * Affected Rows
	 *
	 * @return	int
	 */
	public function affected_rows()
	{
		return mssql_rows_affected($this->conn_id);
	}

	// --------------------------------------------------------------------

	/**
	 * Insert ID
	 *
	 * Returns the last id created in the Identity column.
	 *
	 * @return	string
	 */
	public function insert_id()
	{
		$query = version_compare($this->version(), '8', '>=')
			? 'SELECT SCOPE_IDENTITY() AS last_id'
			: 'SELECT @@IDENTITY AS last_id';

		$query = $this->query($query);
		$query = $query->row();
		return $query->last_id;
	}

	// --------------------------------------------------------------------

	/**
	 * Set client character set
	 *
	 * @param	string	$charset
	 * @return	bool
	 */
	protected function _db_set_charset($charset)
	{
		return (ini_set('mssql.charset', $charset) !== FALSE);
	}

	// --------------------------------------------------------------------

	/**
	 * Version number query string
	 *
	 * @return	string
	 */
	protected function _version()
	{
		return "SELECT SERVERPROPERTY('ProductVersion') AS ver";
	}

	// --------------------------------------------------------------------

	/**
	 * List table query
	 *
	 * Generates a platform-specific query string so that the table names can be fetched
	 *
	 * @param	bool	$prefix_limit
	 * @return	string
	 */
	protected function _list_tables($prefix_limit = FALSE)
	{
		$sql = 'SELECT '.$this->escape_identifiers('name')
			.' FROM '.$this->escape_identifiers('sysobjects')
			.' WHERE '.$this->escape_identifiers('type')." = 'U'";

		if ($prefix_limit !== FALSE && $this->dbprefix !== '')
		{
			$sql .= ' AND '.$this->escape_identifiers('name')." LIKE '".$this->escape_like_str($this->dbprefix)."%' "
				.sprintf($this->_like_escape_str, $this->_like_escape_chr);
		}

		return $sql.' ORDER BY '.$this->escape_identifiers('name');
	}

	// --------------------------------------------------------------------

	/**
	 * List column query
	 *
	 * Generates a platform-specific query string so that the column names can be fetched
	 *
	 * @param	string	$table
	 * @return	string
	 */
	protected function _list_columns($table = '')
	{
		return 'SELECT COLUMN_NAME
			FROM INFORMATION_SCHEMA.Columns
			WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table));
	}

	// --------------------------------------------------------------------

	/**
	 * Returns an object with field data
	 *
	 * @param	string	$table
	 * @return	array
	 */
	public function field_data($table)
	{
		$sql = 'SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, COLUMN_DEFAULT
			FROM INFORMATION_SCHEMA.Columns
			WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table));

		if (($query = $this->query($sql)) === FALSE)
		{
			return FALSE;
		}
		$query = $query->result_object();

		$retval = array();
		for ($i = 0, $c = count($query); $i < $c; $i++)
		{
			$retval[$i]			= new stdClass();
			$retval[$i]->name		= $query[$i]->COLUMN_NAME;
			$retval[$i]->type		= $query[$i]->DATA_TYPE;
			$retval[$i]->max_length		= ($query[$i]->CHARACTER_MAXIMUM_LENGTH > 0) ? $query[$i]->CHARACTER_MAXIMUM_LENGTH : $query[$i]->NUMERIC_PRECISION;
			$retval[$i]->default		= $query[$i]->COLUMN_DEFAULT;
		}

		return $retval;
	}

	// --------------------------------------------------------------------

	/**
	 * Error
	 *
	 * Returns an array containing code and message of the last
	 * database error that has occurred.
	 *
	 * @return	array
	 */
	public function error()
	{
		// We need this because the error info is discarded by the
		// server the first time you request it, and query() already
		// calls error() once for logging purposes when a query fails.
		static $error = array('code' => 0, 'message' => NULL);

		$message = mssql_get_last_message();
		if ( ! empty($message))
		{
			$error['code']    = $this->query('SELECT @@ERROR AS code')->row()->code;
			$error['message'] = $message;
		}

		return $error;
	}

	// --------------------------------------------------------------------

	/**
	 * Update statement
	 *
	 * Generates a platform-specific update string from the supplied data
	 *
	 * @param	string	$table
	 * @param	array	$values
	 * @return	string
	 */
	protected function _update($table, $values)
	{
		$this->qb_limit = FALSE;
		$this->qb_orderby = array();
		return parent::_update($table, $values);
	}

	// --------------------------------------------------------------------

	/**
	 * Truncate statement
	 *
	 * Generates a platform-specific truncate string from the supplied data
	 *
	 * If the database does not support the TRUNCATE statement,
	 * then this method maps to 'DELETE FROM table'
	 *
	 * @param	string	$table
	 * @return	string
	 */
	protected function _truncate($table)
	{
		return 'TRUNCATE TABLE '.$table;
	}

	// --------------------------------------------------------------------

	/**
	 * Delete statement
	 *
	 * Generates a platform-specific delete string from the supplied data
	 *
	 * @param	string	$table
	 * @return	string
	 */
	protected function _delete($table)
	{
		if ($this->qb_limit)
		{
			return 'WITH ci_delete AS (SELECT TOP '.$this->qb_limit.' * FROM '.$table.$this->_compile_wh('qb_where').') DELETE FROM ci_delete';
		}

		return parent::_delete($table);
	}

	// --------------------------------------------------------------------

	/**
	 * LIMIT
	 *
	 * Generates a platform-specific LIMIT clause
	 *
	 * @param	string	$sql	SQL Query
	 * @return	string
	 */
	protected function _limit($sql)
	{
		$limit = $this->qb_offset + $this->qb_limit;

		// As of SQL Server 2005 (9.0.*) ROW_NUMBER() is supported,
		// however an ORDER BY clause is required for it to work
		if (version_compare($this->version(), '9', '>=') && $this->qb_offset && ! empty($this->qb_orderby))
		{
			$orderby = $this->_compile_order_by();

			// We have to strip the ORDER BY clause
			$sql = trim(substr($sql, 0, strrpos($sql, $orderby)));

			// Get the fields to select from our subquery, so that we can avoid CI_rownum appearing in the actual results
			if (count($this->qb_select) === 0)
			{
				$select = '*'; // Inevitable
			}
			else
			{
				// Use only field names and their aliases, everything else is out of our scope.
				$select = array();
				$field_regexp = ($this->_quoted_identifier)
					? '("[^\"]+")' : '(\[[^\]]+\])';
				for ($i = 0, $c = count($this->qb_select); $i < $c; $i++)
				{
					$select[] = preg_match('/(?:\s|\.)'.$field_regexp.'$/i', $this->qb_select[$i], $m)
						? $m[1] : $this->qb_select[$i];
				}
				$select = implode(', ', $select);
			}

			return 'SELECT '.$select." FROM (\n\n"
				.preg_replace('/^(SELECT( DISTINCT)?)/i', '\\1 ROW_NUMBER() OVER('.trim($orderby).') AS '.$this->escape_identifiers('CI_rownum').', ', $sql)
				."\n\n) ".$this->escape_identifiers('CI_subquery')
				."\nWHERE ".$this->escape_identifiers('CI_rownum').' BETWEEN '.($this->qb_offset + 1).' AND '.$limit;
		}

		return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$limit.' ', $sql);
	}

	// --------------------------------------------------------------------

	/**
	 * Insert batch statement
	 *
	 * Generates a platform-specific insert string from the supplied data.
	 *
	 * @param	string	$table	Table name
	 * @param	array	$keys	INSERT keys
	 * @param	array	$values	INSERT values
	 * @return	string|bool
	 */
	protected function _insert_batch($table, $keys, $values)
	{
		// Multiple-value inserts are only supported as of SQL Server 2008
		if (version_compare($this->version(), '10', '>='))
		{
			return parent::_insert_batch($table, $keys, $values);
		}

		return ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE;
	}

	// --------------------------------------------------------------------

	/**
	 * Close DB Connection
	 *
	 * @return	void
	 */
	protected function _close()
	{
		mssql_close($this->conn_id);
	}

}


text:
package com.mbientlab.activitytracker.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public abstract class DbHelper extends SQLiteOpenHelper {

    protected static final String TEXT_TYPE = " TEXT";
    protected static final String INT_TYPE = " INT";
    protected static final String REAL_TYPE = " REAL";
    protected static final String COMMA_SEP = ",";
    public static String[] CREATE_ENTRIES_SQL;
    public static String[] DELETE_ENTRIES_SQL;
    // probably need to remove this

    public DbHelper(Context context, String databaseName, SQLiteDatabase.CursorFactory cursorFactory, int dbVersion){
        super(context, databaseName, cursorFactory, dbVersion);
    }

    public DbHelper(Context context, String databaseName, SQLiteDatabase.CursorFactory cursorFactory, int dbVersion, String[] createEntriesSql, String[] deleteEntriesSql) {
        this(context, databaseName, cursorFactory, dbVersion);
        CREATE_ENTRIES_SQL = createEntriesSql;
        DELETE_ENTRIES_SQL = deleteEntriesSql;
    }

    public void onCreate(SQLiteDatabase db) {
        for(int i = 0; i < CREATE_ENTRIES_SQL.length; i++) {
            db.execSQL(CREATE_ENTRIES_SQL[i]);
        }
    }
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // This database is only a cache for online data, so its upgrade policy is
        // to simply to discard the data and start over
        for(int i = 0; i < DELETE_ENTRIES_SQL.length; i++) {
            db.execSQL(DELETE_ENTRIES_SQL[i]);
        }
        onCreate(db);
    }
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }

}


text:
//
//  ConditionCodes.h
//  SYS_IN_C
//
//  Created by turesnake on 2017/9/18.
//  Copyright © 2017年 turesnake. All rights reserved.
//

#ifndef ConditionCodes_h
#define ConditionCodes_h

#include "Base.h"

extern bit_t ZF; //-- zero
extern bit_t SF; //-- sign
extern bit_t OF; //-- overflow

#endif /* ConditionCodes_h */


text:
char *slurp_file(char *path) {
  int fd = open(path, O_RDONLY);
  if (fd == -1) {
    fprintf(stderr, "file \"%s\" couldn't be opened: %s\n", path, strerror(errno));
    exit(1);
  }

  struct stat st;
  if (fstat(fd, &st)) {
    fprintf(stderr, "could not stat \"%s\": %s\n", path, strerror(errno));
    exit(1);
  }

  char *buf = malloc(st.st_size+1);
  buf[st.st_size] = '\0';
  if (buf == NULL) {
    perror("unable to allocate memory for file slurping");
    exit(1);
  }

  if (read(fd, buf, st.st_size) != st.st_size) {
    perror("unable to slurp some file at once");
    exit(1);
  }

  close(fd);
  return buf;
}

int main(int argc, char **argv) {
  int err;

  // ######  Parse args.  ######
  if (argc != 12) {
    fprintf(stderr, "wrong invocation: want cpu/gpu, width, height, off, len, outpath, csvoutpath!\n");
    exit(1);
  }
  int use_gpu;
  if (!strcmp(argv[1], "cpu")) {
    use_gpu = 0;
  } else if (!strcmp(argv[1], "gpu")) {
    use_gpu = 1;
  } else {
    printf("I only know cpu and gpu!\n");
    exit(1);
  }
  int width = atoi(argv[2]);
  int height = atoi(argv[3]);
  int off = atoi(argv[4]);
  size_t len = atoi(argv[5]);
  char *outpath = argv[6];
  char *csvoutpath = argv[7];
  double minphi1 = strtod(argv[8], NULL);
  double maxphi1 = strtod(argv[9], NULL);
  double minphi2 = strtod(argv[10], NULL);
  double maxphi2 = strtod(argv[11], NULL);

  FILE *csvout = fopen(csvoutpath, "w");
  if (csvout == NULL) {
    perror("can't open csvout file");
    return 1;
  }

  // ######  Prepare the OpenCL environment and our kernel.  ######
  printf("preparing the OpenCL environment and the kernel...\n");
  cl_platform_id platforms[16];
  cl_uint num_platforms;
  err = clGetPlatformIDs(15, platforms, &num_platforms);
  if (err || num_platforms == 0) {
    printf("Can't locate platform!");
    return 1;
  }
  cl_platform_id platform = platforms[0];
  printf("%i platforms found.\n", (int)num_platforms);
  cl_device_id device_id;
  err = clGetDeviceIDs(platform, use_gpu?CL_DEVICE_TYPE_GPU:CL_DEVICE_TYPE_CPU, 1, &device_id, NULL);
  if (err) {
    printf("Error: Failed to locate a compute device!\n");
    return 1;
  }
  printf("Yay! Seems as if you've got a working compute device!\n");

  size_t max_workgroup_size;
  cl_char vendor_name[1024] = {0};
  cl_char device_name[1024] = {0};
  err = clGetDeviceInfo(device_id, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), &max_workgroup_size, NULL);
  err|= clGetDeviceInfo(device_id, CL_DEVICE_VENDOR, sizeof(vendor_name), vendor_name, NULL);
  err|= clGetDeviceInfo(device_id, CL_DEVICE_NAME, sizeof(device_name), device_name, NULL);
  if (err) {
    printf("Error: Failed to retrieve device info!\n");
    return 1;
  }

  printf("Connecting to %s %s...\n", vendor_name, device_name);

  cl_context context = clCreateContext(0, 1, &device_id, NULL, NULL, &err);
  if (context == NULL) {
    printf("Error: Failed to create a compute context!\n");
    return 1;
  }

  cl_command_queue commands = clCreateCommandQueue(context, device_id, 0, &err);
  if (commands == NULL) {
    printf("Error: Failed to create a command commands!\n");
    return 1;
  }

  const char *source = slurp_file("incredible_pendulum.cl");
  cl_program prog = clCreateProgramWithSource(context, 1, &source, NULL, &err);
  if (prog == NULL) {
    printf("Error: Failed to create compute program!\n");
    return 1;
  }

  err = clBuildProgram(prog, 0, NULL, "-cl-unsafe-math-optimizations", NULL, NULL);
  if (err) {
    printf("Error: Failed to build program executable!\n");
    char build_log[2048];
    clGetProgramBuildInfo(prog, device_id, CL_PROGRAM_BUILD_LOG, sizeof(build_log), build_log, NULL);
    printf("%s\n", build_log);
    return 1;
  }

  cl_kernel kern = clCreateKernel(prog, "simulate_pendulum", &err);
  if (kern == NULL) {
    printf("Error: Failed to create compute kernel!\n");
    return 1;
  }

  // ######  Our kernel is ready, now prepare the input/output buffers and data.  ######
  printf("kernel is ready, preparing outfile, data and buffers...\n");
  //size_t number_of_all_runs = width * height;
  cl_float *inputdata;
  err = posix_memalign((void**)&inputdata, 2*sizeof(cl_float), 2*sizeof(cl_float)*len);
  if (err) {
    printf("Error allocating aligned memory.\n");
    exit(1);
  }
  cl_float *inputdata_ = inputdata;
  if (inputdata == NULL) {
    printf("Error: Failed to malloc input buffer!\n");
    return 1;
  }
  int y = off/width;
  int x = off%width;
  int n=0;
  for (; y<height; y++) {
    for (; x<width; x++) {
      cl_float phi1 = minphi1+(maxphi1-minphi1)*(1-y/(cl_float)height);
      *(inputdata_++) = phi1;
      cl_float phi2 = minphi2+(maxphi2-minphi2)*(x/(cl_float)width);
      *(inputdata_++) = phi2;
      n++;
      if (n == len) goto loopend;
    }
    x=0;
  }
loopend: ;
  cl_mem cl_inbuf = clCreateBuffer(context, CL_MEM_READ_ONLY|CL_MEM_USE_HOST_PTR, 2*sizeof(cl_float)*len, inputdata, NULL);
  if (cl_inbuf == NULL) {
    printf("Error: Failed to allocate OpenCL input buffer!\n");
    return 1;
  }
  err = clSetKernelArg(kern, 0, sizeof(cl_inbuf), &cl_inbuf);
  if (err) {
    printf("Error: Can't set kernel arg 0!\n");
    return 1;
  }

  int outfd = open(outpath, O_RDWR|O_CREAT|O_TRUNC, 0666);
  if (outfd == -1) {
    perror("can't open outfile");
    return 1;
  }
  char *header = NULL;
  asprintf(&header, "P6\n%d %d\n255\n", width, height);
  if (header == NULL) exit(1);
  if (write(outfd, header, strlen(header)) != strlen(header)) {
    printf("Error: Can't write outfile header!\n");
    exit(1);
  }
  int full_datasize = 3*width*height;
  int part_datasize = 3*len;
  off_t data_offset = 3*off;
  if (ftruncate(outfd, strlen(header)+full_datasize)) {
    printf("Error: Can't allocate disk space for outfile!\n");
    exit(1);
  }
  unsigned char *outdata_ = mmap(NULL, strlen(header)+full_datasize, PROT_READ|PROT_WRITE, MAP_SHARED, outfd, 0);
  if (outdata_ == MAP_FAILED) {
    printf("Error: Can't mmap outfile!\n");
    exit(1);
  }
  unsigned char *outdata = outdata_ + strlen(header) + data_offset;
  cl_mem cl_outbuf = clCreateBuffer(context, CL_MEM_WRITE_ONLY|CL_MEM_ALLOC_HOST_PTR, part_datasize, NULL, NULL);
  if (cl_outbuf == NULL) {
    printf("Error: Failed to allocate OpenCL output buffer!\n");
    return 1;
  }
  err = clSetKernelArg(kern, 1, sizeof(cl_outbuf), &cl_outbuf);
  if (err) {
    printf("Error: Can't set kernel arg 1!\n");
    return 1;
  }

  // ######  Everything is ready, run it!  ######
  printf("data is also ready, starting execution of %d jobs...\n", (int)len);
  err = clEnqueueNDRangeKernel(commands, kern, 1, NULL, &len, NULL, 0, NULL, NULL);
  if (err) {
    printf("Error: Failed to execute kernel!\n");
    return 1;
  }
  printf("waiting for execution to finish...\n");
  err = clFinish(commands);
  if (err) {
    printf("Error: Failed to wait for command queue to finish! %d\n", err);
    return 1;
  }

  // ######  Fetch computed data.  ######
  printf("execution has finished, fetching results...\n");
  void *outdata2 = clEnqueueMapBuffer(commands, cl_outbuf, CL_TRUE, CL_MAP_READ, 0, part_datasize, 0, NULL, NULL, NULL);
  if (outdata2 == NULL) {
    printf("Error: Failed to map output buffer!\n");
    return 1;
  }
  memcpy(outdata, outdata2, part_datasize);

  for (int i=0; i<len; i++) {
    unsigned char *pixel = outdata2+3*i;
    double phi1 = inputdata[2*i+0];
    double phi2 = inputdata[2*i+1];
    fprintf(csvout, "%f,%f,%hhu,%hhu\n", phi1, phi2, *(unsigned char*)(pixel+1), *(unsigned char*)(pixel+2));
  }

  printf("done. Thanks for flying with your trusty GPU!\n");
}


text:
#include "MainMenu.h"
#include "Game.h"
#include "Credits.h"

/**************************************************************************************************************/

/*Constructs the MainMenu object*/
MainMenu::MainMenu(StateManager * stateManager, SDL_Window* window, int screenWidth, int screenHeight)
	: State(stateManager, window, screenWidth, screenHeight)
{
	/*draw a loading screen*/
	loadingScreen();

	/*initialize random seed: */
	srand((unsigned int)time(NULL));

	/*Initialise the Camera*/
	camera = new Camera();

	/*create a menu entity from the sam model*/
	sam = new MenuEntity(new Model("texture", "texture", "sam", objects, shaders, "sam.png"), 0.08f);

	/*set the background samurai's position*/
	sam->setPosition(0.0f, 0.0f, -2.5f);

	/*initialise the menu UI*/
	userInterface = new MainMenuUI(shaders);

	/*initialise the top left particle effect*/
	particleEffects.push_back(new ParticleEffect("cube", objects, shaders, "default", "yellow",
		glm::vec3(0.0f, 0.0f, -2.5f), true));

	/*initialise the mouse*/
	mouse = glm::vec2(0.0f, 0.0f);

	/*initialise the keys to 0*/
	playKey = credKey = exitKey = 0;

	/*initialise to not pressed*/
	pressed = 0;

	/*stop the loading music*/
	music->stopAudio();

	/*initialise and start the music*/
	music = new Audio("aud/Cool Hard Facts.ogg", true);
	music->startAudio();
}

/**************************************************************************************************************/

/*Destructs the MainMenu object*/
MainMenu::~MainMenu()
{
	/*stop music*/
	music->stopAudio();
	/*delete audio pointers*/
	delete music;
	/*delete pointers*/
	delete sam;
	delete camera;
	delete userInterface;
	for (auto i = objects.begin(); i != objects.end(); ++i)
	{
		delete i->second;
	}
	for (auto i = shaders.begin(); i != shaders.end(); ++i)
	{
		delete i->second;
	}
	for (auto particleEffect : particleEffects)
	{
		delete particleEffect;
	}
}

/**************************************************************************************************************/

/*handles inputs*/
bool MainMenu::input()
{
	/*Check for user input*/
	SDL_Event incomingEvent;
	while (SDL_PollEvent(&incomingEvent))
	{
		/*get the mouse input*/
		mouse.x = ((float)incomingEvent.motion.x);
		mouse.y = ((float)incomingEvent.motion.y);

		/*****************************************************
		The values of the positions below are worked out via:
		(num/200)*640 for the x values,
		(num/200)*480 for the y values.
		******************************************************/

		/*a ternary operator checking if the mouse is above the play key*/
		playKey = (mouse.x > 240.0f && mouse.x < 400.0f && mouse.y > 240.0f && mouse.y < 288.0f) ? 1 : 0;
		/*a ternary operator checking if the mouse is above the credits key*/
		credKey = (mouse.x > 240.0f && mouse.x < 400.0f && mouse.y > 300.0f && mouse.y < 348.0f) ? 1 : 0;
		/*a ternary operator checking if the mouse is above the exit key*/
		exitKey = (mouse.x > 240.0f && mouse.x < 400.0f && mouse.y > 360.0f && mouse.y < 408.0f) ? 1 : 0;

		switch (incomingEvent.type)
		{
		case SDL_QUIT: /*If player closes the window, end the game loop*/

			return false;
			break;

		case SDL_MOUSEBUTTONDOWN: /*If the mouse is pressed*/
			/*if the left mouse button set the x and y to the current mouse position*/
			if (incomingEvent.button.button == SDL_BUTTON_LEFT)
			{
				/*if play key is highlighted*/
				if (playKey == 1)
				{
					/*set pressed to 1*/
					pressed = 1;
				}

				/*if credits key is highlighted*/
				if (credKey == 1)
				{
					/*set pressed to 2*/
					pressed = 2;
				}

				/*if exit key is highlighted*/
				if (exitKey == 1)
				{
					/*set pressed to 3*/
					pressed = 3;
				}

				/*if no key is highlighted*/
				if (playKey == 0 && credKey == 0 && exitKey == 0)
				{
					/*set pressed to 0*/
					pressed = 0;
				}
			}
			break;

		case SDL_MOUSEBUTTONUP:/*If the mouse is released*/
			/*if the left mouse button*/
			if (incomingEvent.button.button == SDL_BUTTON_LEFT)
			{
				switch (pressed)
				{
				case 1:
					/*stop music*/
					music->stopAudio();
					/*go to the game state*/
					stateManager->changeState(new Game(stateManager, window, screenWidth, screenHeight));
					return true;
					break;

				case 2:
					/*go to the credits state*/
					stateManager->addState(new Credits(stateManager, window, screenWidth, screenHeight, music));
					break;

				case 3:
					/*exit the application*/
					return false;
					break;
				}
			}
			break;
		}
	}
	return true;
}

/**************************************************************************************************************/

/*updates the game*/
void MainMenu::update(float dt)
{
	/*keep the music playing*/
	music->startAudio();

	/*update the background model*/
	sam->update(dt);

	/*loop through all of the particle effects*/
	for (auto particleEffect : particleEffects)
	{
		/*get a random x position between -1.5 and 1.5*/
		float x = (float)((rand() % 30) - 15) * 0.1f;
		/*get a random y position between -1.5 and 1.5*/
		float y = (float)((rand() % 30) - 15) * 0.1f;

		/*update the particle effect*/
		particleEffect->makeNewParticles(objects, shaders);
		particleEffect->setEmitter(glm::vec3(x, y, -2.5f));
		particleEffect->update(dt);
	}
}

/**************************************************************************************************************/

/*draws the game*/
void MainMenu::draw()
{
	/*Draw the samurai using the camera*/
	sam->draw(camera->getView(), camera->getProjection());

	/*loop through all of the particle effects*/
	for (auto particleEffect : particleEffects)
	{
		/*draw the particle effect*/
		particleEffect->draw(camera->getView(), camera->getProjection());
	}

	/*draw the UI*/
	userInterface->draw();
}

/**************************************************************************************************************/

/*Draws a LoadingScreen.*/
void MainMenu::loadingScreen()
{
	/*initialise and start the loading music*/
	music = new Audio("aud/Cut Trance.ogg", true);
	music->startAudio();

	/*create the loading screen*/
	LoadingScreen * loadingScreen = new LoadingScreen(shaders);

	/*clear the frame-buffer to a colour*/
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	/*write colour to the frame-buffer*/
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	/*draw the loading screen*/
	loadingScreen->draw();

	/*display the window*/
	SDL_GL_SwapWindow(window);

	/*delete the loading screen*/
	delete loadingScreen;
}


text:
package com.google.gwt.webworker.client;

import com.google.gwt.core.client.JavaScriptObject;

/**
 * Event structure returned whenever an uncaught runtime script error occurs in
 * one of the worker's scripts. See {@link ErrorHandler}
 */
public class ErrorEvent extends JavaScriptObject {

  protected ErrorEvent() {
    // constructors must be protected in JavaScriptObject overlays.
  }

  public final native String getFilename() /*-{
    return this.filename;
  }-*/;

  public final native int getLineNumber() /*-{
    return this.lineno ? this.lineno : 0;
  }-*/;

  public final native String getMessage() /*-{
    return this.message;
  }-*/;
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import argparse
import os
import sys

from inferlib import config, issues, utils

arg_parser = argparse.ArgumentParser(add_help=False)
arg_parser.add_argument('--issues-csv', metavar='<file>',
                        help='Location of the csv report (ignored for now)')
arg_parser.add_argument('--issues-json', metavar='<file>', required=True,
                        help='Location of the json report')
arg_parser.add_argument('--issues-txt', metavar='<file>',
                        help='Location of the text report (ignored for now)')
arg_parser.add_argument('--issues-xml', metavar='<file>',
                        help='Location of the xml report (ignored for now)')
arg_parser.add_argument('--pmd-xml', action='store_true',
                        help='Output issues in (PMD) XML format.')
arg_parser.add_argument('--project-root', metavar='<directory>', required=True,
                        help='Location of the project root')
arg_parser.add_argument('--results-dir', metavar='<directory>', required=True,
                        help='Location of the results directory')

def main():
    sys_argv = map(utils.decode, sys.argv)
    args = arg_parser.parse_args(sys_argv[1:])
    bugs_out = os.path.join(args.results_dir, config.BUGS_FILENAME)
    issues.print_and_save_errors(args.results_dir, args.project_root,
                                 args.issues_json, bugs_out, args.pmd_xml)

if __name__ == '__main__':
    main()


text:
package io.lumify.foodTruck;

import io.lumify.core.model.properties.types.DateLumifyProperty;
import io.lumify.core.model.properties.types.GeoPointLumifyProperty;
import io.lumify.core.model.properties.types.StringLumifyProperty;

public class FoodTruckOntology {
    public static final String EDGE_LABEL_HAS_KEYWORD = "http://lumify.io/foodtruck#tweetHasKeyword";
    public static final String EDGE_LABEL_HAS_TWITTER_USER = "http://lumify.io/foodtruck#foodTruckHasTwitterUser";

    public static final String CONCEPT_TYPE_FOOD_TRUCK = "http://lumify.io/foodtruck#foodTruck";
    public static final String CONCEPT_TYPE_LOCATION = "http://lumify.io/foodtruck#location";

    public static final GeoPointLumifyProperty GEO_LOCATION = new GeoPointLumifyProperty("http://lumify.io/foodtruck#geoLocation");
    public static final DateLumifyProperty GEO_LOCATION_DATE = new DateLumifyProperty("http://lumify.io/foodtruck#geoLocationDate");
    public static final StringLumifyProperty KEYWORD = new StringLumifyProperty("http://lumify.io/foodtruck#keyword");
}


text:
<?php

namespace Oro\Bundle\ApiBundle\Form\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;

use Oro\Bundle\ApiBundle\Config\EntityDefinitionConfig;
use Oro\Bundle\ApiBundle\Config\EntityDefinitionFieldConfig;
use Oro\Bundle\ApiBundle\Model\EntityIdentifier;
use Oro\Bundle\ApiBundle\Util\ConfigUtil;

class NestedAssociationListener implements EventSubscriberInterface
{
    /** @var PropertyAccessorInterface */
    protected $propertyAccessor;

    /** @var EntityDefinitionFieldConfig */
    protected $config;

    /**
     * @param PropertyAccessorInterface   $propertyAccessor
     * @param EntityDefinitionFieldConfig $config
     */
    public function __construct(
        PropertyAccessorInterface $propertyAccessor,
        EntityDefinitionFieldConfig $config
    ) {
        $this->propertyAccessor = $propertyAccessor;
        $this->config = $config;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            FormEvents::POST_SUBMIT => 'postSubmit'
        ];
    }

    /**
     * @param FormEvent $event
     */
    public function postSubmit(FormEvent $event)
    {
        $form = $event->getForm();
        $data = $form->getData();
        $entity = $form->getParent()->getData();
        $entityConfig = $this->config->getTargetEntity();

        $className = null;
        $id = null;
        if (null !== $data) {
            if (!$data instanceof EntityIdentifier) {
                throw new \UnexpectedValueException(
                    sprintf(
                        'Expected argument of type "%s", "%s" given.',
                        EntityIdentifier::class,
                        is_object($data) ? get_class($data) : gettype($data)
                    )
                );
            }
            $className = $data->getClass();
            $id = $data->getId();
        }
        $this->setPropertyValue($entityConfig, $entity, ConfigUtil::CLASS_NAME, $className);
        $this->setPropertyValue($entityConfig, $entity, 'id', $id);
    }

    /**
     * @param EntityDefinitionConfig $entityConfig
     * @param object                 $entity
     * @param string                 $fieldName
     * @param mixed                  $value
     */
    protected function setPropertyValue(
        EntityDefinitionConfig $entityConfig,
        $entity,
        $fieldName,
        $value
    ) {
        $this->propertyAccessor->setValue(
            $entity,
            $entityConfig->getField($fieldName)->getPropertyPath($fieldName),
            $value
        );
    }
}