text:
package org.elasticsearch.xpack.security.authc.support;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.SecuritySettingsSourceField;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xpack.core.security.authc.AuthenticationResult;
import org.elasticsearch.xpack.core.security.authc.Realm;
import org.elasticsearch.xpack.core.security.authc.RealmConfig;
import org.elasticsearch.xpack.core.security.authc.support.CachingUsernamePasswordRealmSettings;
import org.elasticsearch.xpack.core.security.authc.support.Hasher;
import org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken;
import org.elasticsearch.xpack.core.security.user.User;
import org.junit.After;
import org.junit.Before;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import static java.util.Collections.emptyMap;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;

public class CachingUsernamePasswordRealmTests extends ESTestCase {

    private Settings globalSettings;
    private ThreadPool threadPool;

    @Before
    public void setup() {
        globalSettings = Settings.builder().put("path.home", createTempDir()).build();
        threadPool = new TestThreadPool("caching username password realm tests");
    }

    @After
    public void stop() throws InterruptedException {
        if (threadPool != null) {
            terminate(threadPool);
        }
    }

    public void testCacheSettings() throws Exception {
        String cachingHashAlgo = Hasher.values()[randomIntBetween(0, Hasher.values().length - 1)].name().toLowerCase(Locale.ROOT);
        int maxUsers = randomIntBetween(10, 100);
        TimeValue ttl = TimeValue.timeValueMinutes(randomIntBetween(10, 20));
        Settings settings = Settings.builder()
                .put(CachingUsernamePasswordRealmSettings.CACHE_HASH_ALGO_SETTING.getKey(), cachingHashAlgo)
                .put(CachingUsernamePasswordRealmSettings.CACHE_MAX_USERS_SETTING.getKey(), maxUsers)
                .put(CachingUsernamePasswordRealmSettings.CACHE_TTL_SETTING.getKey(), ttl)
                .build();

        RealmConfig config = new RealmConfig("test_realm", settings, globalSettings, TestEnvironment.newEnvironment(globalSettings),
                new ThreadContext(Settings.EMPTY));
        CachingUsernamePasswordRealm realm = new CachingUsernamePasswordRealm("test", config, threadPool) {
            @Override
            protected void doAuthenticate(UsernamePasswordToken token, ActionListener<AuthenticationResult> listener) {
                listener.onResponse(AuthenticationResult.success(new User("username", new String[]{"r1", "r2", "r3"})));
            }

            @Override
            protected void doLookupUser(String username, ActionListener<User> listener) {
                listener.onFailure(new UnsupportedOperationException("this method should not be called"));
            }
        };
        assertThat(realm.cacheHasher, sameInstance(Hasher.resolve(cachingHashAlgo)));
    }

    public void testAuthCache() {
        AlwaysAuthenticateCachingRealm realm = new AlwaysAuthenticateCachingRealm(globalSettings, threadPool);
        SecureString pass = new SecureString("pass");
        PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("a", pass), future);
        future.actionGet();
        future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("b", pass), future);
        future.actionGet();
        future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("c", pass), future);
        future.actionGet();

        assertThat(realm.authInvocationCounter.intValue(), is(3));

        future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("a", pass), future);
        future.actionGet();
        future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("b", pass), future);
        future.actionGet();
        future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("c", pass), future);
        future.actionGet();

        assertThat(realm.authInvocationCounter.intValue(), is(3));
        assertThat(realm.lookupInvocationCounter.intValue(), is(0));
    }

    public void testLookupCache() {
        AlwaysAuthenticateCachingRealm realm = new AlwaysAuthenticateCachingRealm(globalSettings, threadPool);
        PlainActionFuture<User> future = new PlainActionFuture<>();
        realm.lookupUser("a", future);
        future.actionGet();
        future = new PlainActionFuture<>();
        realm.lookupUser("b", future);
        future.actionGet();
        future = new PlainActionFuture<>();
        realm.lookupUser("c", future);
        future.actionGet();

        assertThat(realm.lookupInvocationCounter.intValue(), is(3));
        future = new PlainActionFuture<>();
        realm.lookupUser("a", future);
        future.actionGet();
        future = new PlainActionFuture<>();
        realm.lookupUser("b", future);
        future.actionGet();
        future = new PlainActionFuture<>();
        realm.lookupUser("c", future);
        future.actionGet();

        assertThat(realm.authInvocationCounter.intValue(), is(0));
        assertThat(realm.lookupInvocationCounter.intValue(), is(3));
    }

    public void testLookupAndAuthCache() {
        AlwaysAuthenticateCachingRealm realm = new AlwaysAuthenticateCachingRealm(globalSettings, threadPool);
        // lookup first
        PlainActionFuture<User> lookupFuture = new PlainActionFuture<>();
        realm.lookupUser("a", lookupFuture);
        User lookedUp = lookupFuture.actionGet();
        assertThat(realm.lookupInvocationCounter.intValue(), is(1));
        assertThat(realm.authInvocationCounter.intValue(), is(0));
        assertThat(lookedUp.roles(), arrayContaining("lookupRole1", "lookupRole2"));

        // now authenticate
        PlainActionFuture<AuthenticationResult> authFuture = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("a", new SecureString("pass")), authFuture);
        AuthenticationResult authResult = authFuture.actionGet();
        assertThat(authResult.getStatus(), is(AuthenticationResult.Status.SUCCESS));
        User user = authResult.getUser();
        assertThat(realm.lookupInvocationCounter.intValue(), is(1));
        assertThat(realm.authInvocationCounter.intValue(), is(1));
        assertThat(user.roles(), arrayContaining("testRole1", "testRole2"));
        assertThat(user, not(sameInstance(lookedUp)));

        // authenticate a different user first
        authFuture = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("b", new SecureString("pass")), authFuture);
        authResult = authFuture.actionGet();
        assertThat(authResult.getStatus(), is(AuthenticationResult.Status.SUCCESS));
        user = authResult.getUser();
        assertThat(realm.lookupInvocationCounter.intValue(), is(1));
        assertThat(realm.authInvocationCounter.intValue(), is(2));
        assertThat(user.roles(), arrayContaining("testRole1", "testRole2"));
        //now lookup b
        lookupFuture = new PlainActionFuture<>();
        realm.lookupUser("b", lookupFuture);
        lookedUp = lookupFuture.actionGet();
        assertThat(realm.lookupInvocationCounter.intValue(), is(1));
        assertThat(realm.authInvocationCounter.intValue(), is(2));
        assertThat(user, sameInstance(lookedUp));
    }

    public void testCacheChangePassword() {
        AlwaysAuthenticateCachingRealm realm = new AlwaysAuthenticateCachingRealm(globalSettings, threadPool);

        String user = "testUser";
        SecureString pass1 = new SecureString("pass");
        SecureString pass2 = new SecureString("password");

        PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken(user, pass1), future);
        future.actionGet();
        future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken(user, pass1), future);
        future.actionGet();

        assertThat(realm.authInvocationCounter.intValue(), is(1));

        future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken(user, pass2), future);
        future.actionGet();
        future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken(user, pass2), future);
        future.actionGet();

        assertThat(realm.authInvocationCounter.intValue(), is(2));
    }

    public void testCacheDisabledUser() {
        AlwaysAuthenticateCachingRealm realm = new AlwaysAuthenticateCachingRealm(globalSettings, threadPool);
        realm.setUsersEnabled(false);

        String user = "testUser";
        SecureString password = new SecureString("password");

        PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken(user, password), future);
        assertThat(future.actionGet().getUser().enabled(), equalTo(false));

        assertThat(realm.authInvocationCounter.intValue(), is(1));

        realm.setUsersEnabled(true);
        future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken(user, password), future);
        future.actionGet();
        assertThat(future.actionGet().getUser().enabled(), equalTo(true));

        assertThat(realm.authInvocationCounter.intValue(), is(2));

        future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken(user, password), future);
        future.actionGet();
        assertThat(future.actionGet().getUser().enabled(), equalTo(true));

        assertThat(realm.authInvocationCounter.intValue(), is(2));
    }

    public void testCacheWithVeryLowTtlExpiresBetweenAuthenticateCalls() throws InterruptedException {
        TimeValue ttl = TimeValue.timeValueNanos(randomIntBetween(10, 100));
        Settings settings = Settings.builder()
                .put(CachingUsernamePasswordRealmSettings.CACHE_TTL_SETTING.getKey(), ttl)
                .build();
        RealmConfig config = new RealmConfig("test_cache_ttl", settings, globalSettings, TestEnvironment.newEnvironment(globalSettings),
                new ThreadContext(Settings.EMPTY));
        AlwaysAuthenticateCachingRealm realm = new AlwaysAuthenticateCachingRealm(config, threadPool);

        final UsernamePasswordToken authToken = new UsernamePasswordToken("the-user", new SecureString("the-password"));

        // authenticate
        PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
        realm.authenticate(authToken, future);
        final User user1 = future.actionGet().getUser();
        assertThat(user1.roles(), arrayContaining("testRole1", "testRole2"));
        assertThat(realm.authInvocationCounter.intValue(), is(1));

        Thread.sleep(2);

        // authenticate
        future = new PlainActionFuture<>();
        realm.authenticate(authToken, future);
        final User user2 = future.actionGet().getUser();
        assertThat(user2.roles(), arrayContaining("testRole1", "testRole2"));
        assertThat(user2, not(sameInstance(user1)));
        assertThat(realm.authInvocationCounter.intValue(), is(2));
    }

    public void testReadsDoNotPreventCacheExpiry() throws InterruptedException {
        TimeValue ttl = TimeValue.timeValueMillis(250);
        Settings settings = Settings.builder()
                .put(CachingUsernamePasswordRealmSettings.CACHE_TTL_SETTING.getKey(), ttl)
                .build();
        RealmConfig config = new RealmConfig("test_cache_ttl", settings, globalSettings, TestEnvironment.newEnvironment(globalSettings),
                new ThreadContext(Settings.EMPTY));
        AlwaysAuthenticateCachingRealm realm = new AlwaysAuthenticateCachingRealm(config, threadPool);

        final UsernamePasswordToken authToken = new UsernamePasswordToken("the-user", new SecureString("the-password"));
        PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();

        // authenticate
        realm.authenticate(authToken, future);
        final long start = System.currentTimeMillis();
        final User user1 = future.actionGet().getUser();
        assertThat(realm.authInvocationCounter.intValue(), is(1));

        // After 100 ms (from the original start time), authenticate (read from cache). We don't care about the result
        sleepUntil(start + 100);
        future = new PlainActionFuture<>();
        realm.authenticate(authToken, future);
        future.actionGet();

        // After 200 ms (from the original start time), authenticate (read from cache). We don't care about the result
        sleepUntil(start + 200);
        future = new PlainActionFuture<>();
        realm.authenticate(authToken, future);
        future.actionGet();

        // After 300 ms (from the original start time), authenticate again. The cache entry should have expired (despite the previous reads)
        sleepUntil(start + 300);
        future = new PlainActionFuture<>();
        realm.authenticate(authToken, future);
        final User user2 = future.actionGet().getUser();
        assertThat(user2, not(sameInstance(user1)));
        // Due to slow VMs etc, the cache might have expired more than once during the test, but we can accept that.
        // We have other tests that verify caching works - this test just checks that it expires even when there are repeated reads.
        assertThat(realm.authInvocationCounter.intValue(), greaterThan(1));
    }

    private void sleepUntil(long until) throws InterruptedException {
        final long sleep = until - System.currentTimeMillis();
        if (sleep > 0) {
            Thread.sleep(sleep);
        }
    }

    public void testAuthenticateContract() throws Exception {
        Realm realm = new FailingAuthenticationRealm(Settings.EMPTY, globalSettings, threadPool);
        PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("user", new SecureString("pass")), future);
        User user = future.actionGet().getUser();
        assertThat(user, nullValue());

        realm = new ThrowingAuthenticationRealm(Settings.EMPTY, globalSettings, threadPool);
        future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("user", new SecureString("pass")), future);
        RuntimeException e = expectThrows(RuntimeException.class, future::actionGet);
        assertThat(e.getMessage(), containsString("whatever exception"));
    }

    public void testLookupContract() throws Exception {
        Realm realm = new FailingAuthenticationRealm(Settings.EMPTY, globalSettings, threadPool);
        PlainActionFuture<User> future = new PlainActionFuture<>();
        realm.lookupUser("user", future);
        User user = future.actionGet();
        assertThat(user, nullValue());

        realm = new ThrowingAuthenticationRealm(Settings.EMPTY, globalSettings, threadPool);
        future = new PlainActionFuture<>();
        realm.lookupUser("user", future);
        RuntimeException e = expectThrows(RuntimeException.class, future::actionGet);
        assertThat(e.getMessage(), containsString("lookup exception"));
    }

    public void testReturnDifferentObjectFromCache() throws Exception {
        final AtomicReference<User> userArg = new AtomicReference<>();
        final AtomicReference<AuthenticationResult> result = new AtomicReference<>();
        Realm realm = new AlwaysAuthenticateCachingRealm(globalSettings, threadPool) {
            @Override
            protected void handleCachedAuthentication(User user, ActionListener<AuthenticationResult> listener) {
                userArg.set(user);
                listener.onResponse(result.get());
            }
        };
        PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("user", new SecureString("pass")), future);
        final AuthenticationResult result1 = future.actionGet();
        assertThat(result1, notNullValue());
        assertThat(result1.getUser(), notNullValue());
        assertThat(result1.getUser().principal(), equalTo("user"));

        final AuthenticationResult result2 = AuthenticationResult.success(new User("user"));
        result.set(result2);

        future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("user", new SecureString("pass")), future);
        final AuthenticationResult result3 = future.actionGet();
        assertThat(result3, sameInstance(result2));
        assertThat(userArg.get(), sameInstance(result1.getUser()));
    }

    public void testSingleAuthPerUserLimit() throws Exception {
        final String username = "username";
        final SecureString password = SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING;
        final AtomicInteger authCounter = new AtomicInteger(0);
        final Hasher pwdHasher = Hasher.resolve(randomFrom("pbkdf2", "pbkdf2_1000", "bcrypt", "bcrypt9"));
        final String passwordHash = new String(pwdHasher.hash(password));
        RealmConfig config = new RealmConfig("test_realm", Settings.EMPTY, globalSettings, TestEnvironment.newEnvironment(globalSettings),
            new ThreadContext(Settings.EMPTY));
        final CachingUsernamePasswordRealm realm = new CachingUsernamePasswordRealm("test", config, threadPool) {
            @Override
            protected void doAuthenticate(UsernamePasswordToken token, ActionListener<AuthenticationResult> listener) {
                authCounter.incrementAndGet();
                // do something slow
                if (pwdHasher.verify(token.credentials(), passwordHash.toCharArray())) {
                    listener.onResponse(AuthenticationResult.success(new User(username, new String[]{"r1", "r2", "r3"})));
                } else {
                    listener.onFailure(new IllegalStateException("password auth should never fail"));
                }
            }

            @Override
            protected void doLookupUser(String username, ActionListener<User> listener) {
                listener.onFailure(new UnsupportedOperationException("this method should not be called"));
            }
        };

        final int numberOfProcessors = Runtime.getRuntime().availableProcessors();
        final int numberOfThreads = scaledRandomIntBetween((numberOfProcessors + 1) / 2, numberOfProcessors * 3);
        final int numberOfIterations = scaledRandomIntBetween(20, 100);
        final CountDownLatch latch = new CountDownLatch(1 + numberOfThreads);
        List<Thread> threads = new ArrayList<>(numberOfThreads);
        for (int i = 0; i < numberOfThreads; i++) {
            threads.add(new Thread(() -> {
                try {
                    latch.countDown();
                    latch.await();
                    for (int i1 = 0; i1 < numberOfIterations; i1++) {
                        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

                        realm.authenticate(token, ActionListener.wrap((result) -> {
                            if (result.isAuthenticated() == false) {
                                throw new IllegalStateException("proper password led to an unauthenticated result: " + result);
                            }
                        }, (e) -> {
                            logger.error("caught exception", e);
                            fail("unexpected exception - " + e);
                        }));
                    }

                } catch (InterruptedException e) {
                    logger.error("thread was interrupted", e);
                    Thread.currentThread().interrupt();
                }
            }));
        }

        for (Thread thread : threads) {
            thread.start();
        }
        latch.countDown();
        for (Thread thread : threads) {
            thread.join();
        }
        assertEquals(1, authCounter.get());
    }

    public void testCacheConcurrency() throws Exception {
        final String username = "username";
        final SecureString password = SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING;
        final SecureString randomPassword = new SecureString(randomAlphaOfLength(password.length()).toCharArray());
        final Hasher localHasher = Hasher.resolve(randomFrom("pbkdf2", "pbkdf2_1000", "bcrypt", "bcrypt9"));
        final String passwordHash = new String(localHasher.hash(password));
        RealmConfig config = new RealmConfig("test_realm", Settings.EMPTY, globalSettings, TestEnvironment.newEnvironment(globalSettings),
                new ThreadContext(Settings.EMPTY));
        final CachingUsernamePasswordRealm realm = new CachingUsernamePasswordRealm("test", config, threadPool) {
            @Override
            protected void doAuthenticate(UsernamePasswordToken token, ActionListener<AuthenticationResult> listener) {
                // do something slow
                if (localHasher.verify(token.credentials(), passwordHash.toCharArray())) {
                    listener.onResponse(AuthenticationResult.success(new User(username, new String[]{"r1", "r2", "r3"})));
                } else {
                    listener.onResponse(AuthenticationResult.unsuccessful("Incorrect password", null));
                }
            }

            @Override
            protected void doLookupUser(String username, ActionListener<User> listener) {
                listener.onFailure(new UnsupportedOperationException("this method should not be called"));
            }
        };

        final int numberOfProcessors = Runtime.getRuntime().availableProcessors();
        final int numberOfThreads = scaledRandomIntBetween((numberOfProcessors + 1) / 2, numberOfProcessors * 3);
        final int numberOfIterations = scaledRandomIntBetween(20, 100);
        final CountDownLatch latch = new CountDownLatch(1 + numberOfThreads);
        List<Thread> threads = new ArrayList<>(numberOfThreads);
        for (int i = 0; i < numberOfThreads; i++) {
            final boolean invalidPassword = randomBoolean();
            final int threadNum = i;
            threads.add(new Thread(() -> {
                threadPool.getThreadContext().putTransient("key", threadNum);
                try {
                    latch.countDown();
                    latch.await();
                    for (int i1 = 0; i1 < numberOfIterations; i1++) {
                        UsernamePasswordToken token = new UsernamePasswordToken(username, invalidPassword ? randomPassword : password);

                        realm.authenticate(token, ActionListener.wrap((result) -> {
                            assertThat(threadPool.getThreadContext().getTransient("key"), is(threadNum));
                            if (invalidPassword && result.isAuthenticated()) {
                                throw new RuntimeException("invalid password led to an authenticated user: " + result);
                            } else if (invalidPassword == false && result.isAuthenticated() == false) {
                                throw new RuntimeException("proper password led to an unauthenticated result: " + result);
                            }
                        }, (e) -> {
                            logger.error("caught exception", e);
                            fail("unexpected exception - " + e);
                        }));
                    }

                } catch (InterruptedException e) {
                    logger.error("thread was interrupted", e);
                    Thread.currentThread().interrupt();
                }
            }));
        }

        for (Thread thread : threads) {
            thread.start();
        }
        latch.countDown();
        for (Thread thread : threads) {
            thread.join();
        }
    }

    public void testUserLookupConcurrency() throws Exception {
        final String username = "username";
        final AtomicInteger lookupCounter = new AtomicInteger(0);

        RealmConfig config = new RealmConfig("test_realm", Settings.EMPTY, globalSettings, TestEnvironment.newEnvironment(globalSettings),
                new ThreadContext(Settings.EMPTY));
        final CachingUsernamePasswordRealm realm = new CachingUsernamePasswordRealm("test", config, threadPool) {
            @Override
            protected void doAuthenticate(UsernamePasswordToken token, ActionListener<AuthenticationResult> listener) {
                listener.onFailure(new UnsupportedOperationException("authenticate should not be called!"));
            }

            @Override
            protected void doLookupUser(String username, ActionListener<User> listener) {
                lookupCounter.incrementAndGet();
                listener.onResponse(new User(username, new String[]{"r1", "r2", "r3"}));
            }
        };

        final int numberOfProcessors = Runtime.getRuntime().availableProcessors();
        final int numberOfThreads = scaledRandomIntBetween(numberOfProcessors, numberOfProcessors * 3);
        final int numberOfIterations = scaledRandomIntBetween(10000, 100000);
        final CountDownLatch latch = new CountDownLatch(1 + numberOfThreads);
        List<Thread> threads = new ArrayList<>(numberOfThreads);
        for (int i = 0; i < numberOfThreads; i++) {
            final int threadNum = i;
            threads.add(new Thread(() -> {
                try {
                    threadPool.getThreadContext().putTransient("key", threadNum);
                    latch.countDown();
                    latch.await();
                    for (int i1 = 0; i1 < numberOfIterations; i1++) {
                        realm.lookupUser(username, ActionListener.wrap((user) -> {
                            assertThat(threadPool.getThreadContext().getTransient("key"), is(threadNum));
                            if (user == null) {
                                throw new RuntimeException("failed to lookup user");
                            }
                        }, (e) -> {
                            logger.error("caught exception", e);
                            fail("unexpected exception");
                        }));
                    }

                } catch (InterruptedException e) {
                    logger.error("thread was interrupted", e);
                    Thread.currentThread().interrupt();
                }
            }));
        }

        for (Thread thread : threads) {
            thread.start();
        }
        latch.countDown();
        for (Thread thread : threads) {
            thread.join();
        }
        assertEquals(1, lookupCounter.get());
    }

    public void testAuthenticateDisabled() throws Exception {
        final Settings settings = Settings.builder()
            .put(CachingUsernamePasswordRealmSettings.AUTHC_ENABLED_SETTING.getKey(), false)
            .build();
        final Environment env = TestEnvironment.newEnvironment(globalSettings);
        final ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
        final RealmConfig config = new RealmConfig("test_authentication_disabled", settings, globalSettings, env, threadContext);
        final AlwaysAuthenticateCachingRealm realm = new AlwaysAuthenticateCachingRealm(config, threadPool);

        final UsernamePasswordToken token = new UsernamePasswordToken("phil", new SecureString("tahiti"));
        UsernamePasswordToken.putTokenHeader(threadContext, token);
        assertThat(realm.token(threadContext), nullValue());
        assertThat(realm.supports(token), equalTo(false));

        PlainActionFuture<AuthenticationResult> authFuture = new PlainActionFuture<>();
        realm.authenticate(token, authFuture);
        final AuthenticationResult authResult = authFuture.get();
        assertThat(authResult.isAuthenticated(), equalTo(false));
        assertThat(authResult.getStatus(), equalTo(AuthenticationResult.Status.CONTINUE));

        PlainActionFuture<User> lookupFuture = new PlainActionFuture<>();
        realm.lookupUser(token.principal(), lookupFuture);
        final User user = lookupFuture.get();
        assertThat(user, notNullValue());
        assertThat(user.principal(), equalTo(token.principal()));
    }

    static class FailingAuthenticationRealm extends CachingUsernamePasswordRealm {

        FailingAuthenticationRealm(Settings settings, Settings global, ThreadPool threadPool) {
            super("failing", new RealmConfig("failing-test", settings, global, TestEnvironment.newEnvironment(global),
                    threadPool.getThreadContext()), threadPool);
        }

        @Override
        protected void doAuthenticate(UsernamePasswordToken token, ActionListener<AuthenticationResult> listener) {
            listener.onResponse(AuthenticationResult.notHandled());
        }

        @Override
        protected void doLookupUser(String username, ActionListener<User> listener) {
            listener.onResponse(null);
        }
    }

    static class ThrowingAuthenticationRealm extends CachingUsernamePasswordRealm {

        ThrowingAuthenticationRealm(Settings settings, Settings globalSettings, ThreadPool threadPool) {
            super("throwing", new RealmConfig("throwing-test", settings, globalSettings, TestEnvironment.newEnvironment(globalSettings),
                    threadPool.getThreadContext()), threadPool);
        }

        @Override
        protected void doAuthenticate(UsernamePasswordToken token, ActionListener<AuthenticationResult> listener) {
            listener.onFailure(new RuntimeException("whatever exception"));
        }

        @Override
        protected void doLookupUser(String username, ActionListener<User> listener) {
            listener.onFailure(new RuntimeException("lookup exception"));
        }
    }

    static class AlwaysAuthenticateCachingRealm extends CachingUsernamePasswordRealm {

        public final AtomicInteger authInvocationCounter = new AtomicInteger(0);
        public final AtomicInteger lookupInvocationCounter = new AtomicInteger(0);

        private boolean usersEnabled = true;

        AlwaysAuthenticateCachingRealm(Settings globalSettings, ThreadPool threadPool) {
            this(new RealmConfig("always-test", Settings.EMPTY, globalSettings, TestEnvironment.newEnvironment(globalSettings),
                    threadPool.getThreadContext()), threadPool);
        }

        AlwaysAuthenticateCachingRealm(RealmConfig config, ThreadPool threadPool) {
            super("always", config, threadPool);
        }

        void setUsersEnabled(boolean usersEnabled) {
            this.usersEnabled = usersEnabled;
        }

        @Override
        protected void doAuthenticate(UsernamePasswordToken token, ActionListener<AuthenticationResult> listener) {
            authInvocationCounter.incrementAndGet();
            final User user = new User(token.principal(), new String[]{"testRole1", "testRole2"}, null, null, emptyMap(), usersEnabled);
            listener.onResponse(AuthenticationResult.success(user));
        }

        @Override
        protected void doLookupUser(String username, ActionListener<User> listener) {
            lookupInvocationCounter.incrementAndGet();
            listener.onResponse(new User(username, new String[]{"lookupRole1", "lookupRole2"}));
        }
    }

    static class LookupNotSupportedRealm extends CachingUsernamePasswordRealm {

        public final AtomicInteger authInvocationCounter = new AtomicInteger(0);
        public final AtomicInteger lookupInvocationCounter = new AtomicInteger(0);

        LookupNotSupportedRealm(Settings globalSettings, ThreadPool threadPool) {
            super("lookup", new RealmConfig("lookup-notsupported-test", Settings.EMPTY, globalSettings,
                    TestEnvironment.newEnvironment(globalSettings), threadPool.getThreadContext()), threadPool);
        }

        @Override
        protected void doAuthenticate(UsernamePasswordToken token, ActionListener<AuthenticationResult> listener) {
            authInvocationCounter.incrementAndGet();
            listener.onResponse(AuthenticationResult.success(new User(token.principal(), new String[]{"testRole1", "testRole2"})));
        }

        @Override
        protected void doLookupUser(String username, ActionListener<User> listener) {
            lookupInvocationCounter.incrementAndGet();
            listener.onFailure(new UnsupportedOperationException("don't call lookup if lookup isn't supported!!!"));
        }
    }
}


text:
Murraycoin 1.7.2 ALPHA
====================

* Copyright (c) 2009-2014 Bitcoin Developers
* Copyright (c) 2011-2013 Litecoin Developers
* Copyright (c) 2013-2014 Murraycoin Developers

Setup
---------------------
[Murraycoin](http://murraycoin.org/en/download) is the original Murraycoin client and it builds the backbone of the network. However, it downloads and stores the entire history of Murraycoin transactions (which is currently several GBs); depending on the speed of your computer and network connection, the synchronization process can take anywhere from a few hours to a day or more. Thankfully you only have to do this once. If you would like the process to go faster you can [download the blockchain directly](bootstrap.md)

Running
---------------------
The following are some helpful notes on how to run Murraycoin on your native platform.

### Unix

You need the Qt4 run-time libraries to run Murraycoin-Qt. On Debian or Ubuntu:

	sudo apt-get install libqtgui4

Unpack the files into a directory and run:

- bin/32/murraycoin-qt (GUI, 32-bit) or bin/32/murraycoind (headless, 32-bit)
- bin/64/murraycoin-qt (GUI, 64-bit) or bin/64/murraycoind (headless, 64-bit)

### Windows

Unpack the files into a directory, and then run murraycoin-qt.exe.

### OSX

Drag Murraycoin-Qt to your applications folder, and then run Murraycoin-Qt.

### Need Help?

* See the documentation at the [Murraycoin Wiki](http://dogeco.in/)
for help and more information.
* Ask for help on [#murraycoin](http://webchat.freenode.net?channels=murraycoin) on Freenode. If you don't have an IRC client use [webchat here](http://webchat.freenode.net?channels=murraycoin).
* Ask for help on the [/r/dogeducation subreddit](http://reddit.com/r/dogeducation).

Building
---------------------
The following are developer notes on how to build Murraycoin on your native platform. They are not complete guides, but include notes on the necessary libraries, compile flags, etc.

- [OSX Build Notes](build-osx.md)
- [Unix Build Notes](build-unix.md)
- [Windows Build Notes](build-msw.md)

Development
---------------------
The Murraycoin repo's [root README](https://github.com/murraycoin/murraycoin/blob/master/README.md) contains relevant information on the development process and automated testing.

- [Coding Guidelines](coding.md)
- [Multiwallet Qt Development](multiwallet-qt.md)
- [Release Notes](release-notes.md)
- [Release Process](release-process.md)
- [Source Code Documentation (External Link)](https://dev.visucore.com/bitcoin/doxygen/)
- [Translation Process](translation_process.md)
- [Unit Tests](unit-tests.md)

### Resources
* Discuss on the [/r/murraycoindev](http://www.reddit.com/r/murraycoindev) subreddit.
* Discuss on [#murraycoin-dev](http://webchat.freenode.net/?channels=murraycoin-dev) on Freenode. If you don't have an IRC client use [webchat here](http://webchat.freenode.net/?channels=murraycoin-dev).

### Miscellaneous
- [Assets Attribution](assets-attribution.md)
- [Files](files.md)
- [Tor Support](tor.md)

License
---------------------
Distributed under the [MIT/X11 software license](http://www.opensource.org/licenses/mit-license.php).
This product includes software developed by the OpenSSL Project for use in the [OpenSSL Toolkit](http://www.openssl.org/). This product includes
cryptographic software written by Eric Young ([eay@cryptsoft.com](mailto:eay@cryptsoft.com)), and UPnP software written by Thomas Bernard.

redpajama_set_name: RedPajamaGithub


text:
#ifndef __TRACKING_OBJ__
#define __TRACKING_OBJ__

#include <opencv2/core/core.hpp>

namespace cvar{
namespace tracking{

class trackingOBJ
{
protected:
	trackingOBJ(void);

public:
	virtual ~trackingOBJ(void);

	typedef enum{
		TRACKER_KLT = 1,
		TRACKER_ORB = 2
	}TRACKER_TYPE;

public:
	//! create tracking OBJ
	/*!
	\param[in] type tracker type
	\return pointer of tracker
	*/
	static trackingOBJ* create(TRACKER_TYPE type);

	//! Start Tracking
	/*!
	\param[in] grayImg first farme in gray scale
	\param[in] pts initial object position: pts[0]:Top Left, pts[1]:Bottom Left, pts[2]:Bottom Right, pts[3]:Top Right
	*/
	virtual void startTracking(const cv::Mat& grayImg, std::vector<cv::Point2f>& pts) = 0;

	//! Continue Tracking
	/*!
	\param[in] grayImg input gray scale image
	\return false if tracking failed
	*/
	virtual bool onTracking(const cv::Mat& grayImg) = 0;

	//! Get current obj position
	/*!
	\return Homography from previous frame
	*/
	virtual cv::Mat& getHomographyMat() = 0;
};

};
};
#endif


text:
/*
	Big thanks to https://github.com/wayou/hexo-image-caption
 */

hexo.extend.filter.register('after_post_render', function(data) {

    if (data.layout == 'post' || data.layout == 'page' || data.layout == 'about') {
		data.content = data.content.replace(/(]*>)/g, '
$1
')
        data.content = data.content.replace(/(]*alt="([^"]+)"[^>]*>)/g, '$1' + '
$2
')
    }
    return data

})


text:
<?php

	class Controller
	{
		protected $postVars = null;
		protected $getVars = null;

		function __construct()
		{
			$this->postVars = new stdClass();
			$this->getVars = new stdClass();

			foreach ($_POST as $postKey => $postValue) {
				$this->postVars->$postKey = $postValue;
			}
			foreach ($_GET as $getKey => $getValue) {
				$this->getVars->$getKey = $getValue;
			}
		}

		function __destruct()
		{
		}

		protected function postedData()
		{
			return (isset($_POST) && is_array($_POST) && count($_POST) > 0);
		}

		protected function submittedData()
		{
			return (isset($_GET) && is_array($_GET) && count($_GET) > 0);
		}

		protected function redirect($url)
		{
			header('Location: '. $url);
			exit;
		}

		protected function redirectToReferrer()
		{
			return $this->redirect($_SERVER['HTTP_REFERER']);
		}

		protected function getSecureSiteUri($path = '', $subdomain = '')
		{
			return $this->getSiteUri($path, $subdomain, true);
		}

		protected function getSiteUri($path = '', $subdomain = '', $isSecure = false)
		{
			if ($subdomain != '') {
				$uri = 'http://'. $subdomain .'.'. Config::get('domain_name');
			}
			else {
				$uri = Config::get('url');
			}

			if ($isSecure) {
				$uri = preg_replace('/^http:/https:/i', $uri);
			}

			// Avoid double-slashes between the root URI and the path.
			$uriLength = strlen($uri);
			if ($uri[$uriLength - 1] == '/' && strlen($path) > 0 && $path[0] == '/') {
				$path = substr($path, 1);
			}

			return $uri . $path;
		}

		/********************************************************************************
		 *** POST-BASED JSON METHODS ****************************************************
		 ********************************************************************************/
		protected function getJsonPostRequest($reqFieldName = 'request')
		{
			$obj = json_decode($_POST[$reqFieldName]);

			if (!is_object($obj)) {
				return false;
			}

			foreach (get_object_vars($obj) as $name => $value) {
				if (is_string($value)) {
					$value = trim($value);
				}

				$obj->$name = $value;
			}

			return $obj;
		}

		protected function sendJsonRequest($url, $req = '', $reqFieldName = 'request')
		{
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

			if ($req != '') {
				$req = json_encode($req);
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $reqFieldName .'='. urlencode($req));
			}

			$resp = curl_exec($ch);

			return json_decode($resp);
		}

		protected function sendJsonResponse($obj)
		{
			header('Content-type: application/x-javascript');
			echo(json_encode($obj));
		}

		protected function sendJsonError($message)
		{
			$resp = new JsonResponse();
			$resp->setError($message);

			return $this->sendJsonResponse($resp);
		}

	}


text:
var express = require('express');
var passport = require('passport');
var router = express.Router();

//Google
router.route('/google/callback')
    .get(passport.authenticate('google',
            {
                successRedirect: '/users/',
                failure: '/error/'
            }
        )
     );

router.route('/google')
    .get(passport.authenticate('google',
            {   //scope is specific to Google, what info we want provided
                scope: [
                    'https://www.googleapis.com/auth/userinfo.profile',
                    'https://www.googleapis.com/auth/userinfo.email'
                    ]
            }
        )
    );

//Twitter
router.route('/twitter/callback')
    .get(passport.authenticate('twitter',
            {
                successRedirect: '/users/',
                failure: '/error/'
            }
        )
     );

router.route('/twitter')
    .get(passport.authenticate('twitter'));

//Facebook
router.route('/facebook/callback')
    .get(passport.authenticate('facebook',
            {
                successRedirect: '/users/',
                failure: '/error/'
            }
        )
     );

router.route('/facebook')
    .get(passport.authenticate('facebook',
            {   //scope is specific to Facebook as well, what info we want provided
                scope: [
                    'email',
                    'user_friends'
                    ]
            }
        )
    );

//Github
router.route('/github/callback')
    .get(passport.authenticate('github',
            {
                successRedirect: '/users/',
                failure: '/error/'
            }
        )
     );

router.route('/github')
    .get(passport.authenticate('github'));

//LinkedIn
router.route('/linkedin/callback')
    .get(passport.authenticate('linkedin',
            {
                successRedirect: '/users/',
                failure: '/error/'
            }
        )
     );

router.route('/linkedin')
    .get(passport.authenticate('linkedin'));

module.exports = router;


text:
import java.util.ArrayList;

public class BookShelf implements Aggregate {
    public ArrayList books;

    public BookShelf(int initialCapacity) {
        this.books = new ArrayList(initialCapacity);
    }

    public Book getBookAt(int index) {
        return (Book) books.get(index);
    }

    public void appendBook(Book book) {
        books.add(book);
    }

    public int getLength() {
        return books.size();
    }

    public Iterator iterator() {
        return new BookShelfIterator(this);
    }
}


text:
Listagem de Fornecedores

            Nome
            Endereço
            Cidade
            Ações

        <?php
        if($fornecedor) {

            foreach ($fornecedor as $item) { ?>

                    <?php echo $item['nome_f']; ?>
                    <?php echo $item['endereco_f']; ?>
                    <?php echo $item['nome']; ?>

                        <a href="<?php echo base_url('fornecedor/editar/' . $item['idfornecedor']); ?>"><button type="button" class="btn btn-primary btn-sm"></button>
                        <a href="<?php echo base_url('fornecedor/deletar/' . $item['idfornecedor']); ?>" onclick="return confirm('Deseja deletar este Item?');"><button type="button" class="btn btn-danger btn-sm"></button>

                <?php
            }
        }else {

        }
        ?>

                        <button type="button" class="close" data-dismiss="modal">×</button>

Confirmar exclusão do registro?

                        <button type="button" class="btn btn-primary" data-dismiss="modal">Cancelar</button>
                        <a href="<?php echo base_url('fornecedor/deletar/' . $item['idfornecedor']); ?>"><button class="btn btn-success">Confirmar</button>


text:
package com.teambytes.inflatable.raft

import model._
import protocol._
import config.RaftConfig

private[raft] trait Candidate {
  this: RaftActor =>

  protected def raftConfig: RaftConfig

  val candidateBehavior: StateFunction = {
    // message from client, tell it that we know of no leader
    case Event(msg: ClientMessage[Command], m: ElectionMeta) =>
      log.info("Candidate got {} from client; Respond with anarchy - there is no leader.", msg)
      sender() ! LeaderIs(None, Some(msg))
      stay()

    // election
    case Event(BeginElection, m: ElectionMeta) =>
      if (m.config.members.isEmpty) {
        log.warning("Tried to initialize election with no members...")
        goto(Follower) using m.forFollower
      } else {
        log.info("Initializing election (among {} nodes) for {}", m.config.members.size, m.currentTerm)
        log.info(s"Nodes: ${m.config.members.map(_.path).mkString(",")}")

        val request = RequestVote(m.currentTerm, m.clusterSelf, replicatedLog.lastTerm, replicatedLog.lastIndex)

        if(m.config.singleNodeCluster && m.config.members.size == 1){
          log.info("Single node cluster, voting for myself!")
          self ! VoteCandidate(m.currentTerm)
          stay() using m.withVoteFor(request.term, self)
        } else {
          log.info(s"Election started in ${m.currentTerm}, asking ${m.membersExceptSelf(self).size} for votes.")
          log.info(s"Self: ${self.path}, ClusterSelf: ${m.clusterSelf.path} - Others [${m.membersExceptSelf(self).map(_.path).mkString(",")}}]")

          m.membersExceptSelf(self).foreach(_ ! request)

          val includingThisVote = m.incVote
          log.info(s"Voting for ${m.clusterSelf}")
          stay() using includingThisVote.withVoteFor(m.currentTerm, m.clusterSelf)
        }
      }

    case Event(msg: RequestVote, m: ElectionMeta) if m.canVoteIn(msg.term) =>
      log.info(s"Got a vote request from ${sender().path} in ${m.currentTerm}, voting...")
      sender ! VoteCandidate(m.currentTerm)
      stay() using m.withVoteFor(msg.term, candidate())

    case Event(msg: RequestVote, m: ElectionMeta) =>
      log.info(s"Not able to vote because: Term: ${msg.term} is >= to ${m.currentTerm} or votes [${m.votes}] for requested term is not empty")
      log.info(s"Got a vote request from ${sender().path} in ${m.currentTerm}, unable to vote, declining.")
      sender ! DeclineCandidate(msg.term)
      stay()

    case Event(VoteCandidate(term), m: ElectionMeta) =>
      val includingThisVote = m.incVote

      if (includingThisVote.hasMajority) {
        log.info("Received vote by {}; Won election with {} of {} votes", voter(), includingThisVote.votesReceived, m.config.members.size)
        log.info(s"Votes: ${includingThisVote.votes}")
        goto(Leader) using m.forLeader
      } else {
        log.info("Received vote by {}; Have {} of {} votes", voter(), includingThisVote.votesReceived, m.config.members.size)
        stay() using includingThisVote
      }

    case Event(DeclineCandidate(term), m: ElectionMeta) =>
      log.info("{} declined to vote for me, in term {}", voter(), term)
      stay()

    // end of election

    // handle appends
    case Event(append: AppendEntries[Entry[Command]], m: ElectionMeta) =>
      val leaderIsAhead = append.term >= m.currentTerm

      if (leaderIsAhead) {
        log.info("Reverting to Follower, because got AppendEntries from Leader in {}, but am in {}", append.term, m.currentTerm)
        m.clusterSelf forward append
        goto(Follower) using m.forFollower
      } else {
        log.info("Leader isn't ahead, being stubborn!")
        stay()
      }

    // ending election due to timeout
    case Event(ElectionTimeout, m: ElectionMeta) if m.config.members.size > 1 =>
      log.info("Voting timeout, starting a new election (among {})...", m.config.members.size)
      m.clusterSelf ! BeginElection
      stay() using m.forNewElection

    // would like to start election, but I'm all alone! ;-(
    case Event(ElectionTimeout, m: ElectionMeta) =>
      log.info("Voting timeout, unable to start election, don't know enough nodes (members: {})...", m.config.members.size)
      goto(Follower) using m.forFollower

    case Event(AskForState, _) =>
      sender() ! IAmInState(Candidate)
      stay()
  }

}


text:
package expect4j;

import java.io.IOException;

/**
 *
 * @author justin
 */
public interface Consumer extends Runnable {
    public void run();
    public void waitForBuffer(long timeoutMilli);
    public void send(String str) throws IOException;
    public String pause();
    public void resume();
    public void resume(int offset);
    public void stop();
    public boolean foundEOF();
}


text:
package sms

import (
	"fmt"

	"google.golang.org/grpc"
)

// NewClient returns a gRPC client for interacting with the sms.
// After calling it, run a defer close on the close function
func NewClient() (SmsServiceClient, func() error, error) {
	conn, err := grpc.Dial(Endpoint, grpc.WithInsecure())
	if err != nil {
		return nil, nil, fmt.Errorf("did not connect: %v", err)
	}
	return NewSmsServiceClient(conn), conn.Close, nil
}


text:
package com.android.mediaframeworktest.stress;

import com.android.mediaframeworktest.MediaFrameworkTest;
import com.android.mediaframeworktest.MediaPlayerStressTestRunner;

import android.os.Bundle;
import android.os.Environment;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
import android.util.Log;

import com.android.mediaframeworktest.MediaNames;
import com.android.mediaframeworktest.functional.CodecTest;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;

/**
 * Junit / Instrumentation test case for the media player
 */
public class MediaPlayerStressTest extends ActivityInstrumentationTestCase2<MediaFrameworkTest> {
    private String TAG = "MediaPlayerStressTest";
    private String mMediaSrc;

    public MediaPlayerStressTest() {
        super("com.android.mediaframeworktest", MediaFrameworkTest.class);
    }

    protected void setUp() throws Exception {
        //Insert a 2 second before launching the test activity. This is
        //the workaround for the race condition of requesting the updated surface.
        Thread.sleep(2000);
        getActivity();
        MediaPlayerStressTestRunner mRunner = (MediaPlayerStressTestRunner)getInstrumentation();
        Bundle arguments = mRunner.getArguments();
        mMediaSrc = arguments.getString("media-source");
        if (mMediaSrc == null) {
            mMediaSrc = MediaNames.MEDIA_SAMPLE_POOL;
        }
        super.setUp();
    }

    private int mTotalPlaybackError = 0;
    private int mTotalComplete = 0;
    private int mTotalInfoUnknown = 0;
    private int mTotalVideoTrackLagging = 0;
    private int mTotalBadInterleaving = 0;
    private int mTotalNotSeekable = 0;
    private int mTotalMetaDataUpdate = 0;
    private int mTotalFailedToCompleteWithNoError = 0;

    //Test result output file
    private static final String PLAYBACK_RESULT = "PlaybackTestResult.txt";

    private void writeTestOutput(String filename, Writer output) throws Exception{
        output.write("File Name: " + filename);
        output.write(" Complete: " + CodecTest.onCompleteSuccess);
        output.write(" Error: " + CodecTest.mPlaybackError);
        output.write(" Unknown Info: " + CodecTest.mMediaInfoUnknownCount);
        output.write(" Track Lagging: " +  CodecTest.mMediaInfoVideoTrackLaggingCount);
        output.write(" Bad Interleaving: " + CodecTest.mMediaInfoBadInterleavingCount);
        output.write(" Not Seekable: " + CodecTest.mMediaInfoNotSeekableCount);
        output.write(" Info Meta data update: " + CodecTest.mMediaInfoMetdataUpdateCount);
        output.write(" Failed To Complete With No Error: " +
                CodecTest.mFailedToCompleteWithNoError);
        output.write("\n");
    }

    private void writeTestSummary(Writer output) throws Exception{
        output.write("Total Result:\n");
        output.write("Total Complete: " + mTotalComplete + "\n");
        output.write("Total Error: " + mTotalPlaybackError + "\n");
        output.write("Total Unknown Info: " + mTotalInfoUnknown + "\n");
        output.write("Total Track Lagging: " + mTotalVideoTrackLagging + "\n" );
        output.write("Total Bad Interleaving: " + mTotalBadInterleaving + "\n");
        output.write("Total Not Seekable: " + mTotalNotSeekable + "\n");
        output.write("Total Info Meta data update: " + mTotalMetaDataUpdate + "\n");
        output.write("Total Failed To Complete With No Error: " +
                mTotalFailedToCompleteWithNoError);
        output.write("\n");
    }

    private void updateTestResult(){
        if (CodecTest.onCompleteSuccess) {
            mTotalComplete++;
        }
        else if (CodecTest.mPlaybackError) {
            mTotalPlaybackError++;
        }
        else if (CodecTest.mFailedToCompleteWithNoError) {
            mTotalFailedToCompleteWithNoError++;
        }
        mTotalInfoUnknown += CodecTest.mMediaInfoUnknownCount;
        mTotalVideoTrackLagging += CodecTest.mMediaInfoVideoTrackLaggingCount;
        mTotalBadInterleaving += CodecTest.mMediaInfoBadInterleavingCount;
        mTotalNotSeekable += CodecTest.mMediaInfoNotSeekableCount;
        mTotalMetaDataUpdate += CodecTest.mMediaInfoMetdataUpdateCount;
    }

    //Test that will start the playback for all the videos
    //under the samples folder
    @LargeTest
    public void testVideoPlayback() throws Exception {
        String fileWithError = "Filename:\n";
        File playbackOutput = new File(Environment.getExternalStorageDirectory(), PLAYBACK_RESULT);
        Writer output = new BufferedWriter(new FileWriter(playbackOutput, true));

        boolean testResult = true;
        // load directory files
        boolean onCompleteSuccess = false;
        String[] children = MediaNames.NETWORK_VIDEO_FILES;
        if (MediaNames.MEDIA_SAMPLE_POOL.equals(mMediaSrc)) {
            File dir = new File(mMediaSrc);
            children = dir.list();
        }
        if (children == null) {
            Log.v("MediaPlayerApiTest:testMediaSamples", "dir is empty");
            return;
        } else {
            for (int i = 0; i < children.length; i++) {
                //Get filename
                String filename = children[i];
                onCompleteSuccess =
                    CodecTest.playMediaSamples(mMediaSrc + filename);
                if (!onCompleteSuccess){
                    //Don't fail the test right away, print out the failure file.
                    fileWithError += filename + '\n';
                    Log.v(TAG, "Failure File : " + fileWithError);
                    testResult = false;
                }
                Thread.sleep(3000);
                //Write test result to an output file
                writeTestOutput(filename,output);
                //Get the summary
                updateTestResult();
            }
            writeTestSummary(output);
            output.close();
            assertTrue("testMediaSamples", testResult);
       }
    }
}


text:
package org.jetbrains.yaml.refactoring.rename;

import com.intellij.openapi.project.Project;
import com.intellij.patterns.ElementPattern;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.refactoring.rename.RenameInputValidatorEx;
import com.intellij.util.ProcessingContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.YAMLBundle;
import org.jetbrains.yaml.psi.YAMLKeyValue;

import java.util.regex.Pattern;

public final class YamlKeyValueRenameInputValidator implements RenameInputValidatorEx {
  private static final String IDENTIFIER_START_PATTERN = "(([^\\n\\t\\r \\-?:,\\[\\]{}#&*!|>'\"%@`])" +
                                                         "|([?:-][^\\n\\t\\r ])" +
                                                         ")";

  private static final String IDENTIFIER_END_PATTERN = "(([^\\n\\t\\r ]#)" +
                                                       "|([^\\n\\t\\r :#])" +
                                                       "|(:[^\\n\\t\\r ])" +
                                                       ")";

  // Taken from yaml.flex, NS_PLAIN_ONE_LINE_block. This may not be entirely correct, but it is less restrictive than the default names
  // validator
  public static final Pattern IDENTIFIER_PATTERN = Pattern.compile(
    "(" + IDENTIFIER_START_PATTERN + "([ \t]*" + IDENTIFIER_END_PATTERN + ")*)|" +
    "('[^\\n']*')|(\"[^\\n\"]*\")"
  );

  @Nullable
  @Override
  public String getErrorMessage(@NotNull final String newName, @NotNull final Project project) {
    return IDENTIFIER_PATTERN.matcher(newName).matches() ? null : YAMLBundle.message("rename.invalid.name", newName);
  }

  @NotNull
  @Override
  public ElementPattern<? extends PsiElement> getPattern() {
    return PlatformPatterns.psiElement(YAMLKeyValue.class);
  }

  @Override
  public boolean isInputValid(@NotNull final String newName, @NotNull final PsiElement element, @NotNull final ProcessingContext context) {
    return true;
  }
}


text:
set -o errexit
set -o nounset
set -o pipefail

SCRIPT_ROOT=$(dirname ${PWD})

vendor/k8s.io/code-generator/generate-groups.sh all \
  github.com/noironetworks/aci-containers/pkg/rdconfig github.com/noironetworks/aci-containers/pkg/rdconfig/apis \
  aci.snat:v1 \
  --go-header-file ${SCRIPT_ROOT}/aci-containers/crd-code-generation/hack/custom-boilerplate.go.txt


text:
import styled from "styled-components"

import { Col as FlexCol, Grid as FlexGrid, Row as FlexRow } from "react-styled-flexboxgrid"

import { media } from "./Helpers"

export const Grid = FlexGrid

export const Col: FlexCol = styled(FlexCol)`
    ${media.sm`
    padding-left: 0.5rem;
    padding-right: 0.5rem;
  `}
`

export const Row: FlexRow = styled(FlexRow)`
  ${media.sm`
    margin-left: 1rem;
    margin-right: 1rem;
  `}
`


text:
package io.github.meln1k.vkApi.models.wall

import play.api.libs.json.Json

case class Geo(`type`: String,
               coordinates: String,
               place: Place)

object Geo {
  implicit val geoReads = Json.reads[Geo]
}


text:
from java.util import Collections

x = Collections.emptyList()
s = x.size()


text:
package gov.hhs.onc.sdcct.ws.logging.impl;

import gov.hhs.onc.sdcct.context.SdcctPropertyNames;
import gov.hhs.onc.sdcct.net.http.logging.HttpRequestEvent;
import gov.hhs.onc.sdcct.net.logging.RestEndpointType;
import gov.hhs.onc.sdcct.ws.WsMessageType;
import gov.hhs.onc.sdcct.ws.logging.WsRequestEvent;
import gov.hhs.onc.sdcct.ws.utils.SdcctRestEventUtils;
import org.apache.cxf.io.CacheAndWriteOutputStream;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.message.Message;

public class ClientLoggingOutCallback extends AbstractLoggingOutCallback<WsRequestEvent> {
    public ClientLoggingOutCallback(SdcctLoggingFeature feature, Exchange exchange, Message msg, WsRequestEvent event, WsMessageType msgType) {
        super(feature, exchange, msg, event, msgType);
    }

    @Override
    protected void onCloseInternal(CacheAndWriteOutputStream cachedStream) throws Exception {
        super.onCloseInternal(cachedStream);

        HttpRequestEvent httpEvent = SdcctRestEventUtils.createHttpRequestEvent(msg, SdcctPropertyNames.HTTP_CLIENT_TX_ID, RestEndpointType.CLIENT);

        this.feature.logEvent(httpEvent);
    }
}


text:
layout: shiny
address: http://shiny.njit.edu/app/04_bee_house_hunting

---


text:
/*
 * EDefaultIoFuture.cpp
 *
 *  Created on: 2016-1-11
 *      Author: cxxjava@163.com
 */

#include "../inc/EDefaultIoFuture.hh"
#include "../inc/EExceptionMonitor.hh"

namespace efc {
namespace eio {

EDefaultIoFuture::~EDefaultIoFuture() {
	//
}

sp<EIoFuture> EDefaultIoFuture::tosp() {
	return shared_from_this();
}

EDefaultIoFuture::EDefaultIoFuture(sp<EIoSession> is) :
		session(is), result(null), ready(
				false), waiters(0) {

}

sp<EIoSession> EDefaultIoFuture::getSession() {
	return session.lock();
}

void EDefaultIoFuture::await() {
	SYNCHRONIZED(this) {
		while (!ready) {
			waiters++;

			{
				ON_SCOPE_EXIT(
						waiters--;

						if (!ready) {
							checkDeadLock();
						}
				);

				// Wait for a notify, or if no notify is called,
				// assume that we have a deadlock and exit the
				// loop to check for a potential deadlock.
				this->wait(DEAD_LOCK_CHECK_INTERVAL);
			}
		}
    }}
}

boolean EDefaultIoFuture::await(llong timeout, ETimeUnit* unit) {
	return await0(unit->toMillis(timeout), true);
}

boolean EDefaultIoFuture::await(llong timeoutMillis) {
	return await0(timeoutMillis, true);
}

void EDefaultIoFuture::awaitUninterruptibly() {
	try {
		await0(ELLong::MAX_VALUE, false);
	} catch (EInterruptedException& ie) {
		// Do nothing : this catch is just mandatory by contract
	}
}

boolean EDefaultIoFuture::awaitUninterruptibly(llong timeout, ETimeUnit* unit) {
	try {
		return await0(unit->toMillis(timeout), false);
	} catch (EInterruptedException& e) {
		//throw new InternalError();
		throw ERuntimeException(__FILE__, __LINE__);
	}
}

boolean EDefaultIoFuture::awaitUninterruptibly(llong timeoutMillis) {
	try {
		return await0(timeoutMillis, false);
	} catch (EInterruptedException& e) {
		//throw new InternalError();
		throw ERuntimeException(__FILE__, __LINE__);
	}
}

boolean EDefaultIoFuture::isDone() {
	SYNCHRONIZED(this) {
		return ready;
    }}
}

boolean EDefaultIoFuture::setValue(sp<EObject> newValue) {
	SYNCHRONIZED(this) {
		// Allowed only once.
		if (ready) {
			return false;
		}

		result = newValue;
		ready = true;

		// Now, if we have waiters, notofy them that the operation has completed
		if (waiters > 0) {
			this->notifyAll();
		}
    }}

	// Last, not least, inform the listeners
	notifyListeners();

	return true;
}

void EDefaultIoFuture::addListener(sp<EIoFutureListener> listener) {
	if (listener == null) {
		throw EIllegalArgumentException(__FILE__, __LINE__, "listener");
	}

	SYNCHRONIZED(this) {
		if (ready) {
			// Shortcut : if the operation has completed, no need to
			// add a new listener, we just have to notify it. The existing
			// listeners have already been notified anyway, when the
			// 'ready' flag has been set.
			notifyListener(listener);
		} else {
			if (firstListener == null) {
				firstListener = listener;
			} else {
				otherListeners.add(listener);
			}
		}
    }}
}

void EDefaultIoFuture::removeListener(EIoFutureListener* listener) {
	if (listener == null) {
		throw EIllegalArgumentException(__FILE__, __LINE__, "listener");
	}

	SYNCHRONIZED(this) {
		if (!ready) {
			if (firstListener == listener) {
				if (!otherListeners.isEmpty()) {
					firstListener = otherListeners.removeAt(0);
				} else {
					firstListener = null;
				}
			} else if (!otherListeners.isEmpty()) {
				otherListeners.remove(listener);
			}
		}
    }}
}

sp<EObject> EDefaultIoFuture::getValue() {
	SYNCHRONIZED(this) {
		return result;
    }}
}

boolean EDefaultIoFuture::await0(llong timeoutMillis, boolean interruptable) {
	llong endTime = ESystem::currentTimeMillis() + timeoutMillis;

	if (endTime < 0) {
		endTime = ELLong::MAX_VALUE;
	}

	SYNCHRONIZED(this) {
		// We can quit if the ready flag is set to true, or if
		// the timeout is set to 0 or below : we don't wait in this case.
		if (ready||(timeoutMillis <= 0)) {
			return ready;
		}

		// The operation is not completed : we have to wait
		waiters++;

		{
			ON_SCOPE_EXIT(
				// We get here for 3 possible reasons :
				// 1) We have been notified (the operation has completed a way or another)
				// 2) We have reached the timeout
				// 3) The thread has been interrupted
				// In any case, we decrement the number of waiters, and we get out.
				waiters--;

				if (!ready) {
					checkDeadLock();
				}
			);

			for (;;) {
				try {
					llong timeOut = EMath::min(timeoutMillis, DEAD_LOCK_CHECK_INTERVAL);

					// Wait for the requested period of time,
					// but every DEAD_LOCK_CHECK_INTERVAL seconds, we will
					// check that we aren't blocked.
					this->wait(timeOut);
				} catch (EInterruptedException& e) {
					if (interruptable) {
						throw e;
					}
				}

				if (ready || (endTime < ESystem::currentTimeMillis())) {
					return ready;
				} else {
					// Take a chance, detect a potential deadlock
					checkDeadLock();
				}
			}
		}
    }}
}

void EDefaultIoFuture::checkDeadLock() {
//	// Only read / write / connect / write future can cause dead lock.
//	if (!(dynamic_cast<ECloseFuture*>(this)
//			|| dynamic_cast<EWriteFuture*>(this)
//			|| dynamic_cast<EReadFuture*>(this)
//			|| dynamic_cast<EConnectFuture*>(this)
//		)) {
//		return;
//	}

//TODO...

//	// Get the current thread stackTrace.
//	// Using Thread.currentThread().getStackTrace() is the best solution,
//	// even if slightly less efficient than doing a new Exception().getStackTrace(),
//	// as internally, it does exactly the same thing. The advantage of using
//	// this solution is that we may benefit some improvement with some
//	// future versions of Java.
//	StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
//
//	// Simple and quick check.
//	for (StackTraceElement stackElement : stackTrace) {
//		if (AbstractPollingIoProcessor.class.getName().equals(stackElement.getClassName())) {
//			IllegalStateException e = new IllegalStateException("t");
//			e.getStackTrace();
//			throw new IllegalStateException("DEAD LOCK: " + IoFuture.class.getSimpleName()
//					+ ".await() was invoked from an I/O processor thread.  " + "Please use "
//					+ IoFutureListener.class.getSimpleName() + " or configure a proper thread model alternatively.");
//		}
//	}
//
//	// And then more precisely.
//	for (StackTraceElement s : stackTrace) {
//		try {
//			Class<?> cls = DefaultIoFuture.class.getClassLoader().loadClass(s.getClassName());
//			if (IoProcessor.class.isAssignableFrom(cls)) {
//				throw new IllegalStateException("DEAD LOCK: " + IoFuture.class.getSimpleName()
//						+ ".await() was invoked from an I/O processor thread.  " + "Please use "
//						+ IoFutureListener.class.getSimpleName()
//						+ " or configure a proper thread model alternatively.");
//			}
//		} catch (Exception cnfe) {
//			// Ignore
//		}
//	}
}

void EDefaultIoFuture::notifyListeners() {
	// There won't be any visibility problem or concurrent modification
	// because 'ready' flag will be checked against both addListener and
	// removeListener calls.
	if (firstListener != null) {
		notifyListener(firstListener);
		firstListener = null;

		if (!otherListeners.isEmpty()) {
			sp<EIterator<sp<EIoFutureListener> > > iter = otherListeners.iterator();
			while (iter->hasNext()) {
				sp<EIoFutureListener> listener = iter->next();
				notifyListener(listener);
			}

			otherListeners.clear();
		}
	}
}

void EDefaultIoFuture::notifyListener(sp<EIoFutureListener> listener) {
	try {
		listener->operationComplete(this);
	} catch (EException& e) {
		EExceptionMonitor::getInstance()->exceptionCaught(e);
	}
}

} /* namespace eio */
} /* namespace efc */


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.dt.cms.mapper.sys.UserRoleMapper">
	<sql id="Base_Column_List">
		ID,
		USER_ID as 'user.id',
		ROLE_ID as 'role.id'
	</sql>
	<select id="selectByPrimaryKey" resultType="com.dt.cms.domain.sys.UserRole"
		parameterType="java.lang.Integer">
		select
		<include refid="Base_Column_List" />
		from user_role
		where ID = #{id,jdbcType=INTEGER}
	</select>
	<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
		delete from
		user_role
		where ID = #{id,jdbcType=INTEGER}
	</delete>
	<insert id="insertSelective" parameterType="com.dt.cms.domain.sys.UserRole">
		insert into user_role
		<trim prefix="(" suffix=")" suffixOverrides=",">
			<if test="id != null">
				ID,
			</if>
			<if test="user!=null and user.id != null">
				USER_ID,
			</if>
			<if test="role!=null and role.id != null">
				ROLE_ID,
			</if>
		</trim>
		<trim prefix="values (" suffix=")" suffixOverrides=",">
			<if test="id != null">
				#{id,jdbcType=INTEGER},
			</if>
			<if test="user!=null and user.id != null">
				#{user.id,jdbcType=INTEGER},
			</if>
			<if test="role!=null and role.id != null">
				#{role.id,jdbcType=INTEGER},
			</if>
		</trim>
	</insert>
	<update id="updateByPrimaryKeySelective" parameterType="com.dt.cms.domain.sys.UserRole">
		update user_role
		<set>
			<if test="user!=null and user.id != null">
				USER_ID = #{user.id,jdbcType=INTEGER},
			</if>
			<if test="role!=null and roleId != null">
				ROLE_ID = #{role.id,jdbcType=INTEGER},
			</if>
		</set>
		where ID = #{id,jdbcType=INTEGER}
	</update>
	<select id="findRoleIds" resultType="java.lang.Integer">
		select ROLE_ID from user_role where USER_ID=#{userId,jdbcType=INTEGER}
	</select>
	<select id="deleteUR" >
	    delete user_role where USER_ID=#{userId,jdbcType=INTEGER} and ROLE_ID=#{roleId,jdbcType=INTEGER}
	</select>
	<select id="selectList" resultType="com.dt.cms.domain.sys.UserRole">
		select
		<include refid="Base_Column_List" />
		from user_role
		<if test="where!=null and where!=''">
			where ${where}
		</if>
	</select>
</mapper>


text:
set -ev
BRANCH_TO_RELEASE="master"
if [ "${TRAVIS_BRANCH}" = "ci/releaseTrigger" ]; then
  git clone --depth=50 --branch=${BRANCH_TO_RELEASE} git://github.com/datenstrudel/bulbs-shared.git master
  cd master
  pwd | xargs echo "Operating in path: "
  openssl aes-256-cbc -d -a -pass pass:${GPG_ENCR_KEY} -in ci-scripts/pubring.gpg.encr -out ci-scripts/local.pubring.gpg
  openssl aes-256-cbc -d -a -pass pass:${GPG_ENCR_KEY} -in ci-scripts/secring.gpg.encr -out ci-scripts/local.secring.gpg
  gpg --import ci-scripts/local.pubring.gpg
  gpg --allow-secret-key-import --import ci-scripts/local.secring.gpg
  gpg --list-keys
  echo "Branch is "${TRAVIS_BRANCH}
  git config --global user.email "twx1@gmx.de"
  git config --global user.name "Travis CI Release"
  git config credential.helper "store --file=.git/credentials"
  echo "https://${TRAVIS_GITHUB_TK}:@github.com" > .git/credentials
  cat .git/HEAD|xargs echo "Head is: "
  echo "Starting Maven release... "
  PASSPHRASE_STRING="-Darguments=-Dgpg.passphrase="${GPG_PASSPHRASE}
  mvn -B release:clean release:prepare --settings ci-scripts/settings.xml
  mvn -B release:perform ${PASSPHRASE_STRING} --settings ci-scripts/settings.xml
fi


text:
<?xml version="1.0"?>
<package>
  <name>hector_quadrotor_controller_gazebo</name>
  <version>0.3.5</version>
  <description>The hector_quadrotor_controller_gazebo package implements the ros_control RobotHWSim interface for the quadrotor controller in package hector_quadrotor_controller.</description>
  <maintainer email="meyer@fsr.tu-darmstadt.de">Johannes Meyer</maintainer>

  <license>BSD</license>

  <url type="website">http://ros.org/wiki/hector_quadrotor_controller_gazebo</url>
  <url type="bugtracker">https://github.com/tu-darmstadt-ros-pkg/hector_quadrotor/issues</url>

  <author email="meyer@fsr.tu-darmstadt.de">Johannes Meyer</author>

  <buildtool_depend>catkin</buildtool_depend>
  <build_depend version_gte="2.3.4">gazebo_ros_control</build_depend>
  <build_depend>hector_quadrotor_controller</build_depend>
  <run_depend version_gte="2.3.4">gazebo_ros_control</run_depend>
  <run_depend>hector_quadrotor_controller</run_depend>

  <export>
    <gazebo_ros_control plugin="${prefix}/quadrotor_controller_gazebo.xml"/>
  </export>
</package>


text:
package nlb

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// TagResultModelList is a nested struct in nlb response
type TagResultModelList struct {
	ResourceId   string `json:"ResourceId" xml:"ResourceId"`
	ResourceType string `json:"ResourceType" xml:"ResourceType"`
	RegionNo     string `json:"RegionNo" xml:"RegionNo"`
	AliUid       int64  `json:"AliUid" xml:"AliUid"`
	TagKey       string `json:"TagKey" xml:"TagKey"`
	TagValue     string `json:"TagValue" xml:"TagValue"`
	Scope        string `json:"Scope" xml:"Scope"`
	Category     string `json:"Category" xml:"Category"`
}


text:
import httplib, json
import json as simplejson

def prettyPrint(s):
    """Prettyprints the json response of an HTTPResponse object"""

    # HTTPResponse instance -> Python object -> str
    print simplejson.dumps(json.loads(s.read()), sort_keys=True, indent=4)

class Couch:
    """Basic wrapper class for operations on a couchDB"""

    def __init__(self, host, port=5984, options=None):
        self.host = host
        self.port = port

    def connect(self):
        return httplib.HTTPConnection(self.host, self.port) # No close()

    # Database operations

    def createDb(self, dbName):
        """Creates a new database on the server"""

        r = self.put(''.join(['/',dbName,'/']), "")
        prettyPrint(r)

    def deleteDb(self, dbName):
        """Deletes the database on the server"""

        r = self.delete(''.join(['/',dbName,'/']))
        prettyPrint(r)

    def listDb(self):
        """List the databases on the server"""

        prettyPrint(self.get('/_all_dbs'))

    def infoDb(self, dbName):
        """Returns info about the couchDB"""
        r = self.get(''.join(['/', dbName, '/']))
        prettyPrint(r)

    # Document operations

    def listDoc(self, dbName):
        """List all documents in a given database"""

        r = self.get(''.join(['/', dbName, '/', '_all_docs']))
        prettyPrint(r)

    def openDoc(self, dbName, docId):
        """Open a document in a given database"""
        r = self.get(''.join(['/', dbName, '/', docId,]))
        prettyPrint(r)

    def saveDoc(self, dbName, body, docId=None):
        """Save/create a document to/in a given database"""
        if docId:
            r = self.put(''.join(['/', dbName, '/', docId]), body)
        else:
            r = self.post(''.join(['/', dbName, '/']), body)
        prettyPrint(r)

    def deleteDoc(self, dbName, docId):
        # XXX Crashed if resource is non-existent; not so for DELETE on db. Bug?
        # XXX Does not work any more, on has to specify an revid
        #     Either do html head to get the recten revid or provide it as parameter
        r = self.delete(''.join(['/', dbName, '/', docId, '?revid=', rev_id]))
        prettyPrint(r)

    # Basic http methods

    def get(self, uri):
        c = self.connect()
        headers = {"Accept": "application/json"}
        c.request("GET", uri, None, headers)
        return c.getresponse()

    def post(self, uri, body):
        c = self.connect()
        headers = {"Content-type": "application/json"}
        c.request('POST', uri, body, headers)
        return c.getresponse()

    def put(self, uri, body):
        c = self.connect()
        if len(body) > 0:
            headers = {"Content-type": "application/json"}
            c.request("PUT", uri, body, headers)
        else:
            c.request("PUT", uri, body)
        return c.getresponse()

    def delete(self, uri):
        c = self.connect()
        c.request("DELETE", uri)
        return c.getresponse()


text:
SANI_FORWARD_DECLARE_2(sani, io, FileSystem);
SANI_FORWARD_DECLARE_2(sani, resource, ResourceItem);

namespace sani {

	using namespace io;

	namespace resource {

		namespace pipeline {

			class Texture2DImporter : public ContentImporter {
			private:
				std::vector<String> supportedFileTypes;
			public:
				Texture2DImporter();
				~Texture2DImporter();

				ResourceItem* import(const String& filename, FileSystem* fileSystem) const override;

				virtual String getImporterName() const {
					return "sani::resource::pipeline::Texture2DImporter";
				}
			};
		}
	}
}
#endif


text:
<?php

require_once dirname(dirname(dirname(__FILE__))) . '/bootstrap.php';

class Storymarket_Categories_CategoryManagerTest extends StorymarketTestCase {
    public function setUp() {
        $this->api = $this->getMockApi();
        $this->handler = $this->getMock('Storymarket_RequestHandler', array(),
            array($this->api, 'Storymarket_Base_Resource'));
    }

    public function test_is_subclass_of_base_manager() {
        $reflection = new ReflectionClass('Storymarket_Categories_CategoryManager');
        $this->assertTrue($reflection->isSubclassOf('Storymarket_Base_Manager'));
    }

    public function test_resourceClass_is_category() {
        $manager = new Storymarket_Categories_CategoryManager($this->api, $this->handler);
        $this->assertEquals('Storymarket_Categories_Category', $manager->resourceClass);
    }

    public function test_all_requests_slash_orgs_slash() {
        $this->handler->expects($this->once())
            ->method('doList')
            ->with('/content/category/');

        $manager = new Storymarket_Categories_CategoryManager($this->api, $this->handler);
        $manager->all();
    }

    public function test_all_returns_value_from_handler() {
        $randomValue = rand(1000, 2000);
        $this->handler->expects($this->once())
            ->method('doList')
            ->with('/content/category/')
            ->will($this->returnValue($randomValue));

        $manager = new Storymarket_Categories_CategoryManager($this->api, $this->handler);
        $result = $manager->all();
        $this->assertEquals($randomValue, $result);
    }

    public function test_get_requests_slash_content_slash_category_slash_resource_id() {
        $resource = $this->generateRandomResource();
        $this->handler->expects($this->once())
            ->method('doGet')
            ->with("/content/category/{$resource->id}/");

        $manager = new Storymarket_Categories_CategoryManager($this->api, $this->handler);
        $manager->get($resource);
    }

    public function test_get_requests_slash_content_slash_category_slash_id() {
        $id = rand(1000, 2000);
        $this->handler->expects($this->once())
            ->method('doGet')
            ->with("/content/category/{$id}/");

        $manager = new Storymarket_Categories_CategoryManager($this->api, $this->handler);
        $manager->get($id);
    }

    public function test_get_returns_value_from_handler() {
        $randomValue = rand(1000, 2000);
        $resource = $this->generateRandomResource();
        $this->handler->expects($this->once())
            ->method('doGet')
            ->with("/content/category/{$resource->id}/")
            ->will($this->returnValue($randomValue));

        $manager = new Storymarket_Categories_CategoryManager($this->api, $this->handler);
        $result = $manager->get($resource);
        $this->assertEquals($randomValue, $result);
    }
}


text:
#ifndef SIGNAL_H
#define SIGNAL_H
#include "common.h"
#include "glib_common.h"
/**
 * The routing layer of the signal
 *
 * This represents the layer of the signal that is understood by
 * the routing system; it explains where the signal is meant to
 * be going and what widget generated the signal
 */
class Signal {
	public:
		/** The pointer to a SignalHandler object cast to a void pinter */
		void *handler;

		/** The widget that generated the signal */
		GtkWidget *widget;

		virtual ~Signal() {
			this->handler = NULL;
		}
};

#endif


text:
class Collector

  def initialize(input, output)
    @path = File.dirname(__FILE__)
    @input_files = input.map{|i| @path + '/' + i}
    @output_file = File.expand_path(@path + '/' + output)
    @file = ''
  end

  def accumulate!
    read_file
    save_file
  end

  protected

    def read_file
      @file = ""
      plan = @input_files.inject([]) {|sum, i| sum += File.read(i).split("\n") }
      plan.each do |line|
        @file += File.read(@path + '/' + line)
        @file += "\n"
      end
      @file
    end

    def save_file
      File.open(@output_file, 'w') do |file|
        file.write(@file)
      end
    end

end

plugin = Collector.new(['ruby_debugger_plugin_plan.txt'], '../plugin/ruby_debugger.vim')
plugin.accumulate!

auto_load = Collector.new(['ruby_debugger_autoload_plan.txt'], '../autoload/ruby_debugger.vim')
auto_load.accumulate!

with_tests = Collector.new(['ruby_debugger_autoload_plan.txt', 'ruby_test_plan.txt'], 'additionals/autoload/ruby_debugger.vim')
with_tests.accumulate!


text:
<?php

namespace Mizzencms\Core\Test;

class NavigationTest extends \PHPUnit_Framework_TestCase
{

}


text:
#ifndef __ZipArchiveTests_H__
#define __ZipArchiveTests_H__

#include <gtest/gtest.h>
#include "OgreZip.h"

class ZipArchiveTests : public ::testing::Test
{

protected:
    Ogre::Archive* arch;
public:
    void SetUp();
    void TearDown();
};

#endif


text:
using System;
using System.Collections;
using System.Collections.Specialized;
using Xunit;

namespace System.Diagnostics.Tests
{
    public static class CounterSampleTests
    {
        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void CounterSample_Constructor_EmptyCounterSample()
        {
            CounterSample counterSample = new CounterSample();

            Assert.Equal(0, counterSample.BaseValue);
            Assert.Equal(0, counterSample.CounterFrequency);
            Assert.Equal(PerformanceCounterType.NumberOfItemsHEX32, counterSample.CounterType);
            Assert.Equal(0, counterSample.RawValue);
            Assert.Equal(0, counterSample.SystemFrequency);
            Assert.Equal(0, counterSample.TimeStamp);
            Assert.Equal(0, counterSample.TimeStamp100nSec);
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void CounterSample_Constructor_CounterSample()
        {
            long timeStamp = DateTime.Now.ToFileTime();
            CounterSample counterSample = new CounterSample(1, 2, 3, 4, timeStamp, timeStamp, PerformanceCounterType.SampleFraction);

            Assert.Equal(2, counterSample.BaseValue);
            Assert.Equal(3, counterSample.CounterFrequency);
            Assert.Equal(PerformanceCounterType.SampleFraction, counterSample.CounterType);
            Assert.Equal(1, counterSample.RawValue);
            Assert.Equal(4, counterSample.SystemFrequency);
            Assert.Equal(timeStamp, counterSample.TimeStamp);
            Assert.Equal(timeStamp, counterSample.TimeStamp100nSec);
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void CounterSample_Calculate_CalculateCounterSample()
        {
            CounterSample counterSample = new CounterSample(5, 0, 0, 0, 0, 0, PerformanceCounterType.NumberOfItems32);

            Assert.Equal(5, CounterSample.Calculate(counterSample));
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void CounterSample_Calculate_CalculateCounterSampleCounterSample()
        {
            CounterSample counterSample1 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);
            CounterSample counterSample2 = new CounterSample(15, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);

            Assert.Equal(10, CounterSample.Calculate(counterSample1, counterSample2));
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void CounterSample_Equal()
        {
            CounterSample counterSample1 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);
            CounterSample counterSample2 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);

            Assert.Equal(counterSample1, counterSample2);
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void CounterSample_opInequality()
        {
            CounterSample counterSample1 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);
            CounterSample counterSample2 = new CounterSample(15, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);

            Assert.True(counterSample1 != counterSample2);
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void CounterSample_opEquality()
        {
            CounterSample counterSample1 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);
            CounterSample counterSample2 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);

            Assert.True(counterSample1 == counterSample2);
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))]
        public static void CounterSample_GetHashCode()
        {
            CounterSample counterSample1 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);
            CounterSample counterSample2 = new CounterSample(5, 0, 0, 1, 0, 0, PerformanceCounterType.CounterDelta32);

            Assert.Equal(counterSample1.GetHashCode(), counterSample2.GetHashCode());
        }
    }
}


text:
package com.vecna.dbDiff.model.relationalDb;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * A Serializable collection of RelationalTables, representing a db.
 *
 * Note that this is designed to work wrt to a single schema or catalog!
 *
 * @author dlopuch@vecna.com
 */
public class RelationalDatabase {
  private final Map<String, RelationalTable> m_tablesByName;

  /**
   * Construct a new instance.
   * @param tables ordered collection of tables.
   */
  public RelationalDatabase(Collection<RelationalTable> tables) {
    m_tablesByName = new LinkedHashMap<>(tables.size());
    for (RelationalTable rt : tables) {
      if (m_tablesByName.containsKey(rt.getName())) {
        throw new InconsistentSchemaException("A RelationalDatabase supports only unique table names of tables of the same "
            + "catalog/schema. Non-unique name found: " + rt.getName());
      }
      m_tablesByName.put(rt.getName(), rt);
    }
  }

  /**
   * @return ordered collection of tables in this database.
   */
  public Collection<RelationalTable> getTables() {
    return Collections.unmodifiableCollection(m_tablesByName.values());
  }

  /**
   * Gets a specific table by name.
   * @param tableName the name of the table.
   * @return the table with the given name.
   */
  public RelationalTable getTableByName(String tableName) {
    return m_tablesByName.get(tableName);
  }
}


text:
START_ATF_NAMESPACE
    #pragma pack(push, 2)
    struct  $_TypeDescriptor$_extraBytes_150
    {
        const void *pVFTable;
        void *spare;
        char name[150];
    };
    #pragma pack(pop)
END_ATF_NAMESPACE


text:
Microservice Bootstrap as a commandline tool (alternatively, you can also clone from [https://github.com/coreorm/node-micro-service-bootstrap](https://github.com/coreorm/node-micro-service-bootstrap) and add your own service manually).

It takes all the boring chores away, while leaving the fun part to you: the very service / API you wanted.

Heroku App Example: [https://glacial-mountain-78419.herokuapp.com/](https://glacial-mountain-78419.herokuapp.com/).

Example APIs:
- [ping](https://glacial-mountain-78419.herokuapp.com/ping)
- [example: foo](https://glacial-mountain-78419.herokuapp.com/example/foo)
- [example: bar](https://glacial-mountain-78419.herokuapp.com/example/bar)

## Quick start

### Install from NPM

First, install the command
```
npm install -g microservice-bootstrap
```

Then create your web service by running
```
microservice-bootstrap create -t path-to-myservice
```

Then wait patiently, it will install the service and all dependencies (Yes, you don't need to run npm install').

### Create your own service.

Simply run
```
microservice-bootstrap add-service my-service
```

If you want to add more than one, just separate the names with comma (,).
```
microservice-bootstrap add-service service-name1,service-name2...
```

By default, it will expose `GET /my-service` api.

For more details, run `microservice-bootstrap add-service -h`.

### Start the server

`microservice-bootstrap run [options]`

e.g.
```
microservice-bootstrap run -e local -s my-service -v
```

Or run `microservice-bootstrap run -h` to see the man page for more details on the allowed options.

## How-to

### Service How-to

The server is already setup with global `APP` variable, simply do your routes (APP is an instance of express) e.g.

```
APP.get('/', function(req, res) {
    res.send('hello world!');
});
```

If you have added services using the CLI tool, a default GET /[service name] is already added for you.

For more details, check [express](https://expressjs.com/) website.

#### JSON API response maker.

This bootstrap includes a very easy to use JSON response maker, the output format is:
```
{
  "data": <Object or string>,
  "message": <String message>,
  "success": <Boolean true|false>,
  "code": <INT 200-500>,
  "size": <INT size of data in bytes>,
  "time": <TIMESTAMP milliseconds>
}
```

To use it, simple use the two apis:
- for successful JSON output: `_LIB.util.response.success(data, message, code)`
- for erroneous JSON output: `_LIB.util.response.error(error, code)`.

Details see [./services/default/index.js](https://github.com/coreorm/node-micro-service-bootstrap/blob/master/services/default/index.js#L52).

### Environment How-to

#### Configuration

Configurations are environment specific, the are located inside ./config folder, the structure is as follows:

```
config
├── local
│   ├── app.js
│   └── lib.js
├── production
│   ├── app.js
│   └── lib.js
└── uat
    ├── app.js
    └── lib.js
```

These 3 environments are pre-installed, if you need to add more environment, just follow the same structure. `[environment name as folder name]/[config file]`
- app.js is the application config;
- lib.js is the library registry;

Config inheritance: `production` -> `uat` -> `local`;

#### Library

Library files should be placed inside ./lib, following the structure:

```
lib
├── README.md
├── package-name         // package
│   ├── file1.js
│   └── file2.js
├── package-name.js      // package header - use it to include package files
```

## Unit Tests

Simple run `npm run test`. All tests are under `./tests` folder. Follow `exampleTest.js` to write your own tests.

### Appendix

#### Globals

| name | description | example/comment |
|---|---|---|
| `_CONF` | configuration object | `_CONF.env` |
|`_PATH_ROOT`|root path| `require(_PATH_ROOT + 'header.js')` |
|`_PATH_LIB`|library path| points to `./lib/` |
| `_LIB` | custom library object | Libraries can be registered in different environments, see *Environment How-to* for more details |
|`_log`|log function| see below logging section |
|`_v`|verbose output function| see below verbose output section |

#### Logging

Use `_log(section, data, level = INFO|ERROR|SUCCESS|...)` to log (this will format it into logstash friendly message structure)
- section is where your code runs (e.g. 'service:foo', or a filename)
- data can be a simple string, or a complex javascript object.
- level: text value for level of the log

Log format is a custom pattern for logstash, feel free to change it by overriding the custom `global._log` function, or directly update `lib/util/log.js`.

Default GROK syntax:
```
\[(?<datetime>.+)\] (?<level>[\w]+) "(?<section>[^"]+)" DATA<(?<data>.+)>$
```

#### Verbose output

Simply use `_v(section, data)` to log out the verbose output. This will remain hidden unless the app is run with `-v` or `--verbose`.

#### Built-in Debug tool

NOTE: only supported when _CONF.debug = true;

- `_dump(name, object)` to record objects in the debug information (returned from api)
- `_debug(message)` to record debug messages (returned from api)
- Pass `x-debug-enabled=1` in the header or add `?x-debug-enabled=1` in the query string to enable debug output (NOT supported in production mode).


text:
class Solution {
    public:
        TreeNode *sortedArrayToBST(vector<int> &num) {
            if(num.size() == 0) return NULL;
            int start = 0, end = num.size() - 1;
            TreeNode * root = createBST(num, start, end);
            return root;
        }

        TreeNode * createBST(vector<int> &num, int start, int end){
            if(start > end) return NULL;
            int mid = start - (start - end)/2;
            TreeNode * root = new TreeNode(num[mid]);
            root->left = createBST(num, start, mid-1);
            root->right = createBST(num, mid+1, end);
            return root;
        }
};


text:
import React from 'react';
import AppStore from '../stores/AppStore';
import { Link } from 'react-router-dom'

class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = AppStore.getState();
    this.onChange = this.onChange.bind(this);
  }

  componentDidMount() {
    AppStore.listen(this.onChange);
  }

  componentWillUnmount() {
    AppStore.unlisten(this.onChange);
  }

  onChange(state) {
    this.setState(state);
  }
  render() {
    return (

 Hello { this.state.logined ?  this.state.user.username : 'Guest' }!

            {this.state.logined ? "Welcome back!" : <Link to="/Login">Click here to login.</Link>}

    );
  }
}

export default Home;


text:
package com.itheima.zhbj52.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class HorizontalViewPager extends ViewPager {

	public HorizontalViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public HorizontalViewPager(Context context) {
		super(context);
	}
	/**
	 * 事件分发,请求父控件及祖宗控件是否拦截事件
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if(getCurrentItem()!=0){
			getParent().requestDisallowInterceptTouchEvent(true); //禁止拦截
		}else {
			getParent().requestDisallowInterceptTouchEvent(false);
		}
		return super.dispatchTouchEvent(ev);
	}
}


text:
namespace boost {
namespace compute {
namespace detail {

// counts values that match the predicate using a single thread
template<class InputIterator, class Predicate>
inline size_t serial_count_if(InputIterator first,
                              InputIterator last,
                              Predicate predicate,
                              command_queue &queue)
{
    typedef typename std::iterator_traits<InputIterator>::value_type value_type;

    const context &context = queue.get_context();
    size_t size = iterator_range_size(first, last);

    meta_kernel k("serial_count_if");
    k.add_set_arg("size", static_cast<uint_>(size));
    size_t result_arg = k.add_arg<uint_ *>(memory_object::global_memory, "result");

    k <<
        "uint count = 0;\n" <<
        "for(uint i = 0; i < size; i++){\n" <<
            k.decl<const value_type>("value") << "="
                << first[k.var<uint_>("i")] << ";\n" <<
            "if(" << predicate(k.var<const value_type>("value")) << "){\n" <<
                "count++;\n" <<
            "}\n"
        "}\n"
        "*result = count;\n";

    kernel kernel = k.compile(context);

    // setup result buffer
    scalar<uint_> result(context);
    kernel.set_arg(result_arg, result.get_buffer());

    // run kernel
    queue.enqueue_task(kernel);

    // read index
    return result.read(queue);
}

} // end detail namespace
} // end compute namespace
} // end boost namespace

#endif // BOOST_COMPUTE_ALGORITHM_DETAIL_SERIAL_COUNT_IF_HPP


text:
package com.royalrangers.repository;

import com.royalrangers.model.VerificationToken;
import org.springframework.data.jpa.repository.JpaRepository;

import java.sql.Date;
import java.util.stream.Stream;

public interface VerificationTokenRepository extends JpaRepository<VerificationToken, Long> {

    VerificationToken findByToken(String token);

    void deleteByExpiryDateLessThan(Date now);

}