text:
namespace blackrock {
namespace {

struct sockaddr_in localhostIp4() {
  struct sockaddr_in result;
  memset(&result, 0, sizeof(result));
  result.sin_family = AF_INET;
  result.sin_addr.s_addr = htonl(0x7F000001);
  result.sin_port = 0;
  return result;
}

void logException(kj::Exception&& e) {
  KJ_LOG(ERROR, e);
};

kj::Promise<void> pump(kj::AsyncIoStream& in, kj::AsyncIoStream& out) {
  auto buffer = kj::heapArray<byte>(4096);
  auto promise = in.tryRead(buffer.begin(), 1, buffer.size());
  return promise.then([&,KJ_MVCAP(buffer)](size_t n) mutable -> kj::Promise<void> {
    if (n == 0) {
      out.shutdownWrite();
      return kj::READY_NOW;
    } else {
      auto result = out.write(buffer.begin(), n);
      return result.attach(kj::mv(buffer)).then([&]() {
        return pump(in, out);
      });
    }
  }, [&](kj::Exception&& e) {
    // Input died. Close output.
    out.shutdownWrite();
  });
}

struct TestEnv {
  kj::AsyncIoContext ioContext;
  VatNetwork network1;
  VatNetwork network2;
  kj::WaitScope& waitScope;
  kj::TimePoint start;

  TestEnv()
      : ioContext(kj::setupAsyncIo()),
        network1(ioContext.provider->getNetwork(), ioContext.provider->getTimer(), localhostIp4()),
        network2(ioContext.provider->getNetwork(), ioContext.provider->getTimer(), localhostIp4()),
        waitScope(ioContext.waitScope),
        start(ioContext.provider->getTimer().now()) {}

  ~TestEnv() {}

  void sendMessage(VatNetwork::Connection& conn, kj::StringPtr text) {
    auto msg = conn.newOutgoingMessage(32);
    msg->getBody().setAs<capnp::Text>(text);
    msg->send();
  }

  void expectMessage(VatNetwork::Connection& conn, kj::StringPtr expectedText) {
    auto msg = KJ_ASSERT_NONNULL(conn.receiveIncomingMessage().wait(waitScope));
    auto msgText = msg->getBody().getAs<capnp::Text>();
    KJ_EXPECT(msgText == expectedText, msgText, expectedText);
  }

  kj::Promise<void> shutdown(VatNetwork::Connection& conn) KJ_WARN_UNUSED_RESULT {
    // Asynchronously shut down the given connection.
    return conn.shutdown().eagerlyEvaluate(logException);
  }

  void expectShutdown(VatNetwork::Connection& conn) {
    // Expect to receive shutdown on the given connection.
    KJ_EXPECT(conn.receiveIncomingMessage().wait(waitScope) == nullptr);
  }

  kj::Promise<void> nextIo() {
    // Resolves the next time we check for I/O.

    static char scratch[4];
    auto pipe = ioContext.provider->newOneWayPipe();
    auto read = pipe.in->read(&scratch, 4);
    auto write = pipe.out->write("foo", 4);
    auto promises = kj::heapArrayBuilder<kj::Promise<void>>(2);
    promises.add(read.attach(kj::mv(pipe.in)));
    promises.add(write.attach(kj::mv(pipe.out)));
    return kj::joinPromises(promises.finish());
  }

  template <typename T>
  kj::Promise<void> expectNever(
      kj::Promise<T>&& promise, kj::StringPtr what) KJ_WARN_UNUSED_RESULT {
    // Expect that the promise never resolves.
    return promise.then([what](T&&) { KJ_FAIL_ASSERT("unexpected return", what); })
        .eagerlyEvaluate(logException);
  }

  kj::Promise<void> expectNever(
      kj::Promise<void>&& promise, kj::StringPtr what) KJ_WARN_UNUSED_RESULT {
    // Expect that the promise never resolves.
    return promise.then([what]() { KJ_FAIL_ASSERT("unexpected return", what); })
        .eagerlyEvaluate(logException);
  }
};

KJ_TEST("can connect and send messages") {
  TestEnv env;

  kj::Own<VatNetwork::Connection> conn1 =
      KJ_ASSERT_NONNULL(env.network1.connect(env.network2.getSelf()));
  kj::Own<VatNetwork::Connection> conn2 = env.network2.accept().wait(env.waitScope);

  // We send conn2 -> conn1 first to be sure no optimistic messages are used.
  env.sendMessage(*conn2, "foo");
  env.expectMessage(*conn1, "foo");
  env.sendMessage(*conn1, "bar");
  env.expectMessage(*conn2, "bar");
  env.sendMessage(*conn1, "baz");
  env.sendMessage(*conn2, "qux");
  env.expectMessage(*conn2, "baz");
  env.expectMessage(*conn1, "qux");

  // Test clean shutdown.
  auto promise1 = env.shutdown(*conn1);
  env.expectShutdown(*conn2);
  auto promise2 = env.shutdown(*conn2);
  env.expectShutdown(*conn1);
}

KJ_TEST("can optimistically send messages") {
  TestEnv env;

  kj::Own<VatNetwork::Connection> conn1 =
      KJ_ASSERT_NONNULL(env.network1.connect(env.network2.getSelf()));

  env.sendMessage(*conn1, "foo");
  env.sendMessage(*conn1, "bar");

  kj::Own<VatNetwork::Connection> conn2 = env.network2.accept().wait(env.waitScope);

  // Verify that the next two messages are received immediately.
  bool didIo = false;
  auto ioPromise = env.nextIo().then([&]() { didIo = true; }).eagerlyEvaluate(nullptr);

  env.expectMessage(*conn2, "foo");
  env.expectMessage(*conn2, "bar");

  KJ_EXPECT(!didIo);

  env.sendMessage(*conn2, "baz");
  env.expectMessage(*conn1, "baz");
  env.sendMessage(*conn1, "qux");
  env.sendMessage(*conn2, "quux");
  env.expectMessage(*conn2, "qux");
  env.expectMessage(*conn1, "quux");

  KJ_EXPECT(didIo);

  // Test clean shutdown.
  auto promise1 = env.shutdown(*conn1);
  env.expectShutdown(*conn2);
  auto promise2 = env.shutdown(*conn2);
  env.expectShutdown(*conn1);
}

KJ_TEST("can connect both ways simultaneously") {
  TestEnv env;

  kj::Own<VatNetwork::Connection> conn1 =
      KJ_ASSERT_NONNULL(env.network1.connect(env.network2.getSelf()));
  kj::Own<VatNetwork::Connection> conn2 =
      KJ_ASSERT_NONNULL(env.network2.connect(env.network1.getSelf()));

  auto promise1 = env.expectNever(env.network1.accept(), "network1.accept() returned");
  auto promise2 = env.expectNever(env.network2.accept(), "network2.accept() returned");

  env.sendMessage(*conn1, "foo");
  env.sendMessage(*conn2, "bar");
  env.expectMessage(*conn2, "foo");
  env.expectMessage(*conn1, "bar");
  env.sendMessage(*conn1, "baz");
  env.sendMessage(*conn2, "qux");
  env.expectMessage(*conn2, "baz");
  env.expectMessage(*conn1, "qux");

  // Test clean shutdown.
  auto promise3 = env.shutdown(*conn1);
  env.expectShutdown(*conn2);
  auto promise4 = env.shutdown(*conn2);
  env.expectShutdown(*conn1);
}

KJ_TEST("rejects bogus send header") {
  TestEnv env;
  VatNetwork network3(env.ioContext.provider->getNetwork(),
                      env.ioContext.provider->getTimer(), localhostIp4());

  KJ_EXPECT_LOG(ERROR, "connection had invalid handshake header");

  capnp::MallocMessageBuilder message;
  message.setRoot(env.network2.getSelf());
  auto path = message.getRoot<VatPath>();
  path.setAddress(network3.getSelf().getAddress());

  kj::Own<VatNetwork::Connection> conn1 =
      KJ_ASSERT_NONNULL(env.network1.connect(path));

  auto promise1 = env.expectNever(env.network1.accept(), "network1.accept() returned");
  auto promise2 = env.expectNever(env.network2.accept(), "network2.accept() returned");
  auto promise3 = env.expectNever(network3.accept(), "network3.accept() returned");

  env.sendMessage(*conn1, "foo");

  KJ_EXPECT_THROW(DISCONNECTED, conn1->receiveIncomingMessage().wait(env.waitScope));
}

KJ_TEST("rejects bogus reply header") {
  TestEnv env;

  auto listener = env.ioContext.provider->getNetwork()
      .parseAddress("127.0.0.1")
      .wait(env.waitScope)
      ->listen();

  capnp::MallocMessageBuilder message;
  message.setRoot(env.network2.getSelf());
  auto path = message.getRoot<VatPath>();
  path.getAddress().setPort(listener->getPort());

  kj::Own<VatNetwork::Connection> conn1 =
      KJ_ASSERT_NONNULL(env.network1.connect(path));

  auto promise1 = env.expectNever(env.network1.accept(), "network1.accept() returned");
  auto promise2 = env.expectNever(env.network2.accept(), "network2.accept() returned");

  env.sendMessage(*conn1, "foo");

  auto conn2 = listener->accept().wait(env.waitScope);
  byte header[64];
  conn2->read(header, sizeof(header)).wait(env.waitScope);
  ++header[32];  // increment connection number
  conn2->write(header, sizeof(header)).wait(env.waitScope);

  KJ_EXPECT_THROW_MESSAGE("peer responded with invalid handshake header",
      conn1->receiveIncomingMessage().wait(env.waitScope));
}

KJ_TEST("can't man in the middle") {
  TestEnv env;

  auto listener = env.ioContext.provider->getNetwork()
      .parseAddress("127.0.0.1")
      .wait(env.waitScope)
      ->listen();

  capnp::MallocMessageBuilder message;
  message.setRoot(env.network2.getSelf());
  auto path = message.getRoot<VatPath>();
  auto addr = path.getAddress();
  uint32_t realPort = addr.getPort();
  addr.setPort(listener->getPort());

  kj::Own<VatNetwork::Connection> conn1 =
      KJ_ASSERT_NONNULL(env.network1.connect(path));

  auto promise1 = env.expectNever(env.network1.accept(), "network1.accept() returned");
  auto promise2 = env.expectNever(env.network2.accept(), "network2.accept() returned");

  env.sendMessage(*conn1, "foo");

  KJ_EXPECT_LOG(ERROR, "connection had invalid handshake header");

  // Receive the connection from network1 and attempt to forward it to network2, thus becoming
  // a MITM.
  auto conn2 = listener->accept().wait(env.waitScope);
  auto conn3 = env.ioContext.provider->getNetwork()
      .parseAddress("127.0.0.1", realPort)
      .wait(env.waitScope)
      ->connect()
      .wait(env.waitScope);
  auto pumpUpTask = pump(*conn2, *conn3).eagerlyEvaluate(nullptr);
  auto pumpDownTask = pump(*conn3, *conn2).eagerlyEvaluate(nullptr);

  KJ_EXPECT_THROW(FAILED, conn1->receiveIncomingMessage().wait(env.waitScope));
}

KJ_TEST("can reconnect after disconnect") {
  TestEnv env;

  kj::Own<VatNetwork::Connection> conn1 =
      KJ_ASSERT_NONNULL(env.network1.connect(env.network2.getSelf()));
  kj::Own<VatNetwork::Connection> conn2 = env.network2.accept().wait(env.waitScope);

  env.sendMessage(*conn1, "foo");
  env.expectMessage(*conn2, "foo");

  // As long as we're still connected, connect() will return the same connection.
  kj::Own<VatNetwork::Connection> conn1b =
      KJ_ASSERT_NONNULL(env.network1.connect(env.network2.getSelf()));
  KJ_ASSERT(conn1b.get() == conn1.get());

  // In fact connect() will return the same connection even for the accepter.
  kj::Own<VatNetwork::Connection> conn2b =
      KJ_ASSERT_NONNULL(env.network2.connect(env.network1.getSelf()));
  KJ_ASSERT(conn2b.get() == conn2.get());

  // But let's say we shut down.
  auto promise1 = env.shutdown(*conn1);
  env.expectShutdown(*conn2);

  // Now the next connect creates an all-new connection.
  kj::Own<VatNetwork::Connection> conn1c =
      KJ_ASSERT_NONNULL(env.network1.connect(env.network2.getSelf()));
  KJ_ASSERT(conn1c.get() != conn1.get());

  kj::Own<VatNetwork::Connection> conn2c =
      KJ_ASSERT_NONNULL(env.network2.connect(env.network1.getSelf()));
  KJ_ASSERT(conn2c.get() != conn2.get());

  auto promise2 = env.expectNever(env.network1.accept(), "network1.accept() returned");
  auto promise3 = env.expectNever(env.network2.accept(), "network2.accept() returned");

  env.sendMessage(*conn1c, "bar");
  env.expectMessage(*conn2c, "bar");

  // Test clean shutdown.
  auto promise4 = env.shutdown(*conn1c);
  env.expectShutdown(*conn2c);
  auto promise5 = env.shutdown(*conn2c);
  env.expectShutdown(*conn1c);
}

KJ_TEST("can reconnect after authentication failure") {
  TestEnv env;
  VatNetwork network3(env.ioContext.provider->getNetwork(),
                      env.ioContext.provider->getTimer(), localhostIp4());

  KJ_EXPECT_LOG(ERROR, "connection had invalid handshake header");

  capnp::MallocMessageBuilder message;
  message.setRoot(env.network2.getSelf());
  auto path = message.getRoot<VatPath>();
  path.setAddress(network3.getSelf().getAddress());

  kj::Own<VatNetwork::Connection> conn1 =
      KJ_ASSERT_NONNULL(env.network1.connect(path));

  auto promise1 = env.expectNever(network3.accept(), "network3.accept() returned");

  env.sendMessage(*conn1, "foo");

  KJ_EXPECT_THROW(DISCONNECTED, conn1->receiveIncomingMessage().wait(env.waitScope));

  // Now the next connect creates an all-new connection.
  kj::Own<VatNetwork::Connection> conn1b =
      KJ_ASSERT_NONNULL(env.network1.connect(env.network2.getSelf()));
  KJ_ASSERT(conn1b.get() != conn1.get());

  kj::Own<VatNetwork::Connection> conn2 = env.network2.accept().wait(env.waitScope);

  env.sendMessage(*conn1b, "bar");
  env.expectMessage(*conn2, "bar");

  // Test clean shutdown.
  auto promise2 = env.shutdown(*conn1b);
  env.expectShutdown(*conn2);
  auto promise3 = env.shutdown(*conn2);
  env.expectShutdown(*conn1b);
}

}  // namespace
}  // namespace blackrock


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Ku.Core.Cache.Redis
{
    internal class RedisOptions
    {
        /// <summary>
        /// Gets or sets the password to be used to connect to the Redis server.
        /// </summary>
        /// <value>
        /// The password.
        /// </value>
        public string Password { get; set; } = null;

        /// <summary>
        /// Gets or sets a value indicating whether to use SSL encryption.
        /// </summary>
        /// <value>
        ///   <c>true</c> if this instance is SSL; otherwise, <c>false</c>.
        /// </value>
        public bool IsSsl { get; set; } = false;

        /// <summary>
        /// Gets or sets the SSL Host.
        /// If set, it will enforce this particular host on the server's certificate.
        /// </summary>
        /// <value>
        /// The SSL host.
        /// </value>
        public string SslHost { get; set; } = null;

        public bool AllowAdmin { get; set; } = false;

        /// <summary>
        /// Gets or sets the timeout for any connect operations.
        /// </summary>
        /// <value>
        /// The connection timeout.
        /// </value>
        public int ConnectionTimeout { get; set; } = 5000;

        /// <summary>
        /// Gets the list of endpoints to be used to connect to the Redis server.
        /// </summary>
        /// <value>
        /// The endpoints.
        /// </value>
        public IList<ServerEndPoint> Endpoints { get; } = new List<ServerEndPoint>();

        /// <summary>
        /// Gets or sets the Redis database index the cache will use.
        /// </summary>
        /// <value>
        /// The database.
        /// </value>
        public int Database { get; set; } = 0;
    }

    internal class ServerEndPoint
    {
        /// <summary>
        /// Gets or sets the port.
        /// </summary>
        /// <value>The port.</value>
        public int Port { get; set; } = 6379;

        /// <summary>
        /// Gets or sets the host.
        /// </summary>
        /// <value>The host.</value>
        public string Host { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
IRCLog
======

![IRCLog Screenshot](http://i.imgur.com/tgc4QaZ.png)

IRCLog is a simple IRC channel logger. Give it an IRC server and one or more
channels and it will sit there and take notes. A nice web interface is
included too.

It's written in Node.js with help from Express (for the web app part) and
node-irc (for the IRC bits).

## Installation

### Getting a copy of the code

To get a copy of the code either clone this repo:

    git clone git@github.com:timdavies/IRCLog.git

Or download the zip:

    wget https://github.com/timdavies/IRCLog/archive/master.zip

### Installing dependencies

IRCLog depends on a bunch of fantastic projects. Get them by running the
following command whilst inside the root directory of the project:

    npm install

### Configure it

Next, go inside the config directory and do this:

    cp database.json.dist database.json
    cp irc.json.dist irc.json

Then, edit those .json files and fill in the details. It should be pretty
straight forward but if not, scroll to the bottom of this README - there are
some example config files.

Something to remember - you must create the database beforehand. IRCLog won't
do that for you.

### Run it

Finally, run it with the following command:

    node IRCLog.js

IRCLog will connect to the server you've defined in your config file, join the
channels you've defined and start logging immediately. You'll be able to access
the web interface at the following URL:

    http://localhost:3000/

Happy logging.

## Example config files

### database.json

    {
      "hostname" : "localhost",
      "username" : "root",
      "password" : "password",
      "database" : "IRCLog"
    }

### irc.json

    {
      "bot_name": "IRCLog",
      "server": {
        "hostname": "chat.freenode.net"
      },
      "channels": [
        "#ubuntu",
        "#debian",
        "#git",
        "#docker"
      ]
    }


text:
package com.mattunderscore.rated.executor;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;

import com.mattunderscore.executors.ITaskWrapper;
import com.mattunderscore.executors.ITaskWrapperFactory;
import com.mattunderscore.executors.IUniversalExecutor;
import net.jcip.annotations.ThreadSafe;

/**
 * A simple rated executor that returns no {@link Future}s.
 * @author Matt Champion
 * @since 0.1.1
 */
@ThreadSafe
/*package*/ final class SimpleRatedExecutor implements IUniversalExecutor
{
    private final IInternalExecutor executor;
    private final ITaskWrapperFactory wrapperFactory;

    public SimpleRatedExecutor(final IInternalExecutor executor, final ITaskWrapperFactory wrapperFactory)
    {
        this.executor = executor;
        this.wrapperFactory = wrapperFactory;
    }

    @Override
    public void execute(final Runnable task)
    {
        final ITaskWrapper thing = wrapperFactory.newWrapper(task);
        executor.submit(thing);
    }

    public <V> void execute(final Callable<V> task)
    {
        final ITaskWrapper thing = wrapperFactory.newWrapper(task);
        executor.submit(thing);
    }
}


text:
FROM instructure/spark:2.1-hadoop2.7

ENV ZEPPELIN_VERSION 0.7.0

ENV ZEPPELIN_PORT 8080
ENV ZEPPELIN_HOME /usr/zeppelin
ENV ZEPPELIN_CONF_DIR $ZEPPELIN_HOME/conf
ENV ZEPPELIN_NOTEBOOK_DIR $ZEPPELIN_HOME/notebook

USER root

WORKDIR /root
RUN curl -sS http://apache.cs.utah.edu/zeppelin/zeppelin-${ZEPPELIN_VERSION}/zeppelin-${ZEPPELIN_VERSION}-bin-netinst.tgz | tar -xzf - && \
    mv /root/zeppelin* $ZEPPELIN_HOME && \
    mkdir -p $ZEPPELIN_HOME/logs \
             $ZEPPELIN_HOME/run && \
    chown -R docker:docker $ZEPPELIN_HOME && \
    rm -rf /root/zeppelin*

USER docker
WORKDIR $ZEPPELIN_HOME
CMD ["bin/zeppelin.sh"]


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Diagnostics;
using System.Linq;
using Analyzer.Utilities.PooledObjects;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis;

namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow
{
    /// <summary>
    /// An abstract domain implementation for analyses that store dictionary typed data.
    /// </summary>
    public abstract class AnalysisEntityMapAbstractDomain<TValue> : MapAbstractDomain<AnalysisEntity, TValue>
    {
        private static readonly Func<AnalysisEntity, bool> s_defaultIsTrackedEntity = new Func<AnalysisEntity, bool>(_ => true);
        private static readonly Func<PointsToAbstractValue, bool> s_defaultIsTrackedPointsToValue = new Func<PointsToAbstractValue, bool>(_ => true);

        private readonly Func<AnalysisEntity, bool> _isTrackedEntity;
        private readonly Func<PointsToAbstractValue, bool> _isTrackedPointsToValue;

        private protected AnalysisEntityMapAbstractDomain(
            AbstractValueDomain<TValue> valueDomain,
            Func<AnalysisEntity, bool> isTrackedEntity,
            Func<PointsToAbstractValue, bool> isTrackedPointsToValue)
            : base(valueDomain)
        {
            _isTrackedEntity = isTrackedEntity ?? throw new ArgumentNullException(nameof(isTrackedEntity));
            _isTrackedPointsToValue = isTrackedPointsToValue ?? throw new ArgumentNullException(nameof(isTrackedPointsToValue));
        }

        protected AnalysisEntityMapAbstractDomain(AbstractValueDomain<TValue> valueDomain, PointsToAnalysisResult? pointsToAnalysisResult)
            : this(valueDomain,
                  pointsToAnalysisResult != null ? pointsToAnalysisResult.IsTrackedEntity : s_defaultIsTrackedEntity,
                  pointsToAnalysisResult != null ? pointsToAnalysisResult.IsTrackedPointsToValue : s_defaultIsTrackedPointsToValue)
        {
        }

        protected abstract TValue GetDefaultValue(AnalysisEntity analysisEntity);
        protected abstract bool CanSkipNewEntry(AnalysisEntity analysisEntity, TValue value);
        protected virtual void OnNewMergedValue(TValue value)
        {
        }

        private bool CanSkipNewEntity(AnalysisEntity analysisEntity)
        {
            if (_isTrackedEntity(analysisEntity) ||
                _isTrackedPointsToValue(analysisEntity.InstanceLocation))
            {
                return false;
            }

            if (analysisEntity.ParentOpt != null &&
                !CanSkipNewEntity(analysisEntity.ParentOpt))
            {
                return false;
            }

            return true;
        }

        protected abstract void AssertValidEntryForMergedMap(AnalysisEntity analysisEntity, TValue value);
        protected virtual void AssertValidAnalysisData(DictionaryAnalysisData<AnalysisEntity, TValue> map)
        {
#if DEBUG
            foreach (var kvp in map)
            {
                AssertValidEntryForMergedMap(kvp.Key, kvp.Value);
            }
#endif
        }

        public override DictionaryAnalysisData<AnalysisEntity, TValue> Merge(DictionaryAnalysisData<AnalysisEntity, TValue> map1, DictionaryAnalysisData<AnalysisEntity, TValue> map2)
        {
            AssertValidAnalysisData(map1);
            AssertValidAnalysisData(map2);

            var resultMap = new DictionaryAnalysisData<AnalysisEntity, TValue>();
            using var newKeys = PooledHashSet<AnalysisEntity>.GetInstance();
            using var valuesToMergeBuilder = ArrayBuilder<TValue>.GetInstance(5);

            var map2LookupIgnoringInstanceLocation = map2.Keys.Where(IsAnalysisEntityForFieldOrProperty)
                                                              .ToLookup(entity => entity.EqualsIgnoringInstanceLocationId);
            foreach (var entry1 in map1)
            {
                AnalysisEntity key1 = entry1.Key;
                TValue value1 = entry1.Value;

                if (map2LookupIgnoringInstanceLocation.Count > 0 && IsAnalysisEntityForFieldOrProperty(key1))
                {
                    var equivalentKeys2 = map2LookupIgnoringInstanceLocation[key1.EqualsIgnoringInstanceLocationId];
                    if (!equivalentKeys2.Any())
                    {
                        TValue mergedValue = GetMergedValueForEntityPresentInOneMap(key1, value1);
                        Debug.Assert(!map2.ContainsKey(key1));
                        Debug.Assert(ValueDomain.Compare(value1, mergedValue) <= 0);
                        AddNewEntryToResultMap(key1, mergedValue);
                        continue;
                    }

                    foreach (AnalysisEntity key2 in equivalentKeys2)
                    {
                        // Confirm that key2 and key1 are indeed EqualsIgnoringInstanceLocation
                        // This ensures that we handle hash code clashes of EqualsIgnoringInstanceLocationId.
                        if (!key1.EqualsIgnoringInstanceLocation(key2))
                        {
                            continue;
                        }

                        TValue value2 = map2[key2];

                        valuesToMergeBuilder.Clear();
                        valuesToMergeBuilder.Add(value1);
                        valuesToMergeBuilder.Add(value2);

                        if (key1.InstanceLocation.Equals(key2.InstanceLocation))
                        {
                            var mergedValue = GetMergedValue(valuesToMergeBuilder);
                            AddNewEntryToResultMap(key1, mergedValue);
                        }
                        else
                        {
                            if (key1.SymbolOpt == null || !Equals(key1.SymbolOpt, key2.SymbolOpt))
                            {
                                // PERF: Do not add a new key-value pair to the resultMap for unrelated entities or non-symbol based entities.
                                continue;
                            }

                            AnalysisEntity mergedKey = key1.WithMergedInstanceLocation(key2);

                            var isExistingKeyInInput = false;
                            var isExistingKeyInResult = false;
                            if (resultMap.TryGetValue(mergedKey, out var existingValue))
                            {
                                valuesToMergeBuilder.Add(existingValue);
                                isExistingKeyInResult = true;
                            }

                            if (map1.TryGetValue(mergedKey, out existingValue))
                            {
                                valuesToMergeBuilder.Add(existingValue);
                                isExistingKeyInInput = true;
                            }

                            if (map2.TryGetValue(mergedKey, out existingValue))
                            {
                                valuesToMergeBuilder.Add(existingValue);
                                isExistingKeyInInput = true;
                            }

                            var isCandidateToBeSkipped = !isExistingKeyInInput && !isExistingKeyInResult;
                            if (isCandidateToBeSkipped && CanSkipNewEntity(mergedKey))
                            {
                                // PERF: Do not add a new key-value pair to the resultMap if the key is not reachable from tracked entities and PointsTo values.
                                continue;
                            }

                            var mergedValue = GetMergedValue(valuesToMergeBuilder);

                            Debug.Assert(ValueDomain.Compare(value1, mergedValue) <= 0);
                            Debug.Assert(ValueDomain.Compare(value2, mergedValue) <= 0);

                            if (isCandidateToBeSkipped && CanSkipNewEntry(mergedKey, mergedValue))
                            {
                                // PERF: Do not add a new key-value pair to the resultMap if the value can be skipped.
                                continue;
                            }

                            if (!isExistingKeyInInput)
                            {
                                newKeys.Add(mergedKey);
                            }

                            AddNewEntryToResultMap(mergedKey, mergedValue, isNewKey: !isExistingKeyInInput);
                        }
                    }
                }
                else if (map2.TryGetValue(key1, out var value2))
                {
                    TValue mergedValue = ValueDomain.Merge(value1, value2);
                    Debug.Assert(ValueDomain.Compare(value1, mergedValue) <= 0);
                    Debug.Assert(ValueDomain.Compare(value2, mergedValue) <= 0);
                    AddNewEntryToResultMap(key1, mergedValue);
                    continue;
                }

                if (!resultMap.ContainsKey(key1))
                {
                    TValue mergedValue = GetMergedValueForEntityPresentInOneMap(key1, value1);
                    Debug.Assert(ValueDomain.Compare(value1, mergedValue) <= 0);
                    AddNewEntryToResultMap(key1, mergedValue);
                }
            }

            foreach (var kvp in map2)
            {
                var key2 = kvp.Key;
                var value2 = kvp.Value;
                if (!resultMap.ContainsKey(key2))
                {
                    TValue mergedValue = GetMergedValueForEntityPresentInOneMap(key2, value2);
                    Debug.Assert(ValueDomain.Compare(value2, mergedValue) <= 0);
                    AddNewEntryToResultMap(key2, mergedValue);
                }
            }

            foreach (var newKey in newKeys)
            {
                Debug.Assert(!map1.ContainsKey(newKey));
                Debug.Assert(!map2.ContainsKey(newKey));
                var value = resultMap[newKey];
                if (ReferenceEquals(value, GetDefaultValue(newKey)))
                {
                    resultMap.Remove(newKey);
                }
                else
                {
                    OnNewMergedValue(value);
                }
            }

            Debug.Assert(Compare(map1, resultMap) <= 0);
            Debug.Assert(Compare(map2, resultMap) <= 0);
            AssertValidAnalysisData(resultMap);

            return resultMap;
            static bool IsAnalysisEntityForFieldOrProperty(AnalysisEntity entity)
                => entity.SymbolOpt?.Kind == SymbolKind.Field || entity.SymbolOpt?.Kind == SymbolKind.Property;

            TValue GetMergedValueForEntityPresentInOneMap(AnalysisEntity key, TValue value)
            {
                if (key.HasConstantValue)
                {
                    return value;
                }

                var defaultValue = GetDefaultValue(key);
                return ValueDomain.Merge(value, defaultValue);
            }

            TValue GetMergedValue(ArrayBuilder<TValue> values)
            {
                Debug.Assert(values.Count > 0);
                var mergedValue = values[0];
                for (var i = 1; i < values.Count; i++)
                {
                    mergedValue = GetMergedValueCore(mergedValue, values[i]);
                }

                return mergedValue;

                TValue GetMergedValueCore(TValue value1, TValue value2)
                {
                    TValue mergedValue = ValueDomain.Merge(value1, value2);
                    Debug.Assert(ValueDomain.Compare(value1, mergedValue) <= 0);
                    Debug.Assert(ValueDomain.Compare(value2, mergedValue) <= 0);
                    return mergedValue;
                }
            }

            void AddNewEntryToResultMap(AnalysisEntity key, TValue value, bool isNewKey = false)
            {
                Debug.Assert(isNewKey == (!map1.ContainsKey(key) && !map2.ContainsKey(key)));
                AssertValidEntryForMergedMap(key, value);
                resultMap[key] = value;
                if (!isNewKey)
                {
                    OnNewMergedValue(value);
                }
            }
        }
    }
}


text:
<?php
namespace Rizeway\Anchour\Config\Resolvers;

use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Helper\DialogHelper;

use jubianchi\Adapter\AdapterInterface;

use Rizeway\Anchour\Config\ConfigurableInterface;
use Rizeway\Anchour\Config\Resolver;

class InteractiveCliResolver extends Resolver
{
    /**
     * @var \Symfony\Component\Console\Output\OutputInterface
     */
    private $output;

    /**
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     * @param \Symfony\Component\Console\Helper\DialogHelper    $dialog
     */
    public function __construct(OutputInterface $output, DialogHelper $dialog, AdapterInterface $adapter = null)
    {
        $this->setAdapter($adapter);

        $this->output = $output;
        $this->dialog = $dialog;
    }

    public function getValues(ConfigurableInterface $command) {
        $values = array();

        foreach ($this->getVariablesToAskInArray($command->getConfig()) as $key => $var) {
            $question = sprintf('Entrer the <info>%s (%s)</info> : ', $key, $var);

            if (preg_match('/password|pwd|passwd?/', $key) > 0) {
                $this->output->write($question);
                $values[$key] = $this->getAdapter()->exec('stty -echo; read PASSWORD; stty echo; echo $PASSWORD');
                $this->output->writeln('');
            } else {
                $values[$key] = $this->dialog->ask($this->output, $question);
            }
        }

        return $values;
    }
}


text:
require 'simplecov'
SimpleCov.start

$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)

require 'i18n'
I18n.load_path = Dir['./spec/fixtures/locales/*.yml']

require 'json_error'
require './spec/fixtures/json_error_base_children'


text:
package com.composum.sling.core.usermanagement.service;

import org.apache.commons.lang3.StringUtils;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.sling.serviceusermapping.Mapping;

import javax.jcr.RepositoryException;
import javax.jcr.Value;
import java.security.Principal;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * an Authorizable facade to represent a service user (bundle or subservice) as a member of an Authorizable set
 */
public class ServiceUser implements Authorizable {

    public static final String SERVICE_USER_ROOT = "/home/services";

    public class ServicePrincipal implements Principal {

        @Override
        public String getName() {
            return getID();
        }
    }

    protected final String serviceName;
    protected final String serviceInfo;

    protected final String id;
    protected final String path;
    protected final Mapping mapping;
    protected final Principal principal;

    private transient Set<Group> declaredMemberOf;
    private transient Set<Group> memberOf;

    public ServiceUser(Authorizables.Context context, Mapping mapping) throws RepositoryException {
        this.mapping = mapping;
        serviceName = mapping.getServiceName();
        serviceInfo = mapping.getSubServiceName();
        if (StringUtils.isNotBlank(serviceInfo)) {
            id = serviceName + ":" + serviceInfo;
            path = SERVICE_USER_ROOT + "/" + serviceName.replace('.', '/') + "/" + serviceInfo;
        } else {
            id = serviceName;
            path = SERVICE_USER_ROOT + "/" + serviceName.replace('.', '/');
        }
        principal = new ServicePrincipal();
    }

    /**
     * to avoid a possible endless loop during construction the relations are set up in a separate step
     */
    public void initialize(Authorizables.Context context) throws RepositoryException {
        if (declaredMemberOf == null) {
            declaredMemberOf = new LinkedHashSet<>();
            memberOf = new LinkedHashSet<>();
            Authorizable authorizable;
            String user = mapping.map(mapping.getServiceName(), mapping.getSubServiceName());
            if (StringUtils.isNotBlank(user)) {
                authorizable = context.getService().getAuthorizable(context, user);
                if (authorizable != null) {
                    declaredMemberOf.add(new GroupFacade(authorizable, this));
                }
            }
            Iterable<String> principals = mapping.mapPrincipals(mapping.getServiceName(), mapping.getSubServiceName());
            if (principals != null) {
                for (String principal : principals) {
                    authorizable = context.getService().getAuthorizable(context, principal);
                    if (authorizable != null) {
                        declaredMemberOf.add(new GroupFacade(authorizable, this));
                    }
                }
            }
            for (Group group : declaredMemberOf) {
                memberOf.add(group);
                Iterator<Group> groups = group.memberOf();
                while (groups.hasNext()) {
                    memberOf.add(groups.next());
                }
            }
        }
    }

    public String getServiceName() {
        return serviceName;
    }

    public String getServiceInfo() {
        return serviceInfo;
    }

    @Override
    public String getID() {
        return id;
    }

    @Override
    public boolean isGroup() {
        return false;
    }

    @Override
    public Principal getPrincipal() {
        return principal;
    }

    @Override
    public Iterator<Group> declaredMemberOf() {
        return declaredMemberOf.iterator();
    }

    @Override
    public Iterator<Group> memberOf() {
        return memberOf.iterator();
    }

    @Override
    public void remove() throws RepositoryException {
    }

    @Override
    public Iterator<String> getPropertyNames() {
        return Collections.emptyIterator();
    }

    @Override
    public Iterator<String> getPropertyNames(String relPath) {
        return Collections.emptyIterator();
    }

    @Override
    public boolean hasProperty(String relPath) {
        return false;
    }

    @Override
    public void setProperty(String relPath, Value value) {

    }

    @Override
    public void setProperty(String relPath, Value[] value) {

    }

    @Override
    public Value[] getProperty(String relPath) {
        return new Value[0];
    }

    @Override
    public boolean removeProperty(String relPath) {
        return false;
    }

    @Override
    public String getPath() {
        return path;
    }
}


text:
import scalaz.Scalaz._
import scalaz.effect.IO

sealed trait Move
case object Up extends Move
case object Down extends Move
case object Left extends Move
case object Right extends Move

sealed trait Query
case object Quit extends Query
case class NewGame(difficulty: Int) extends Query
case class Play(m: Move) extends Query

class Game(val emptyField: Game.Pos, val gameBoard: Game.Board) {
  import Game._

  def show(): String = {
    gameBoard.map(_ + 1).grouped(WIDTH).foldLeft("+---+---+---+---+\n")((acc, row) => {
      acc + "|" + row.mkString("\t|") +"\t|" + "\n+---+---+---+---+\n"
    }).replace("16", "  ")
  }
}

object Game {
  type Pos = (Int, Int)
  type Label = Int
  type Board = (Vector[Label])
  type Vec = (Int, Int)

  val EMPTY_LABEL = 15
  val WIDTH = 4

  def to1D(pos: Pos): Int = {
    val (x, y) = pos
    WIDTH * x + y
  }

  def to2D(idx: Int): Pos = {
    val x = idx / WIDTH
    val y = idx % WIDTH
    (x, y)
  }

  val initGame: Game = {
    val empty: Pos = to2D(WIDTH * WIDTH)
    val board: Board = Vector.tabulate(WIDTH*WIDTH)(lbl => lbl)
    new Game(empty, board)
  }

  def doMove(m: Move, g: Game): Game = {

    def orient(move: Move): Vec = move match {
      case Up    => (-1, 0)
      case Down  => (1, 0)
      case Left  => (0, -1)
      case Right => (0, 1)
    }

    def shift(vec: Vec, pos: Pos): Pos = {
      val (va, vb) = vec
      val (pa, pb) = pos
      (va + pa, vb + pb)
    }

    def within(pos: Pos): Boolean = {
      val check = (p: Int) => p >= 0 && p <= (WIDTH - 1)
      val (a, b) = pos
      check(a) && check(b)
    }

    val currEmpPos = g.emptyField
    val nextEmpPos = shift(orient(m), currEmpPos)

    if (within(nextEmpPos)) {
      val currBoard = g.gameBoard
      val nextBoard = currBoard
                      .updated(to1D(currEmpPos), currBoard(to1D(nextEmpPos)))
                      .updated(to1D(nextEmpPos), EMPTY_LABEL)

      new Game(nextEmpPos, nextBoard)
    } else g
  }

  def shuffle(diff: Int): IO[Game] = {
    val nextStage = initGame.gameBoard.permutations.drop(42).next()
    val emptyIdx = nextStage.indexOf(EMPTY_LABEL)
    new Game(to2D(emptyIdx), nextStage).point[IO]
  }

  def isGameOver(game: Game): Boolean = game == initGame
}


text:
package com.thegongoliers.hardware;

import com.thegongoliers.input.switches.ResettableSwitch;
import com.thegongoliers.input.switches.Switch;
import com.thegongoliers.input.voltage.VoltageSensor;
import com.thegongoliers.math.GMath;
import com.thegongoliers.output.interfaces.Drivetrain;

import edu.wpi.first.wpilibj.AnalogPotentiometer;
import edu.wpi.first.wpilibj.drive.DifferentialDrive;
import edu.wpi.first.wpilibj.interfaces.Gyro;
import edu.wpi.first.wpilibj2.command.Subsystem;
import edu.wpi.first.wpilibj2.command.button.Button;
import edu.wpi.first.wpilibj2.command.button.Trigger;

import java.util.function.BooleanSupplier;

/**
 * Miscellaneous hardware functions.
 */
public class Hardware {

	/**
     * Combines multiple buttons into a single button.
     * @param button1 The first button.
     * @param buttons The rest of the buttons.
     * @return A Button which is pressed only when ALL of the buttons are pressed.
     */
    public static Button combineButtons(Button button1, Button... buttons){
        return new Button(){
            @Override
            public boolean get() {
                for (Button button: buttons){
                    if (!button.get()){
                        return false;
                    }
                }
                return button1.get();
            }
        };
    }

	/**
	 * Creates a button from a boolean supplier.
	 * @param booleanSupplier The boolean supplier to become a button.
	 * @return The button which is pressed when the boolean supplier is true.
	 */
	public static Button makeButton(BooleanSupplier booleanSupplier){
		return new Button() {
			@Override
			public boolean get() {
				return booleanSupplier.getAsBoolean();
			}
		};
	}

	/**
	 * Creates a button from a trigger.
	 * @param trigger The trigger to become a button.
	 * @return The button which is pressed when the trigger is triggered.
	 */
	public static Button triggerToButton(Trigger trigger){
		return Hardware.makeButton(trigger::get);
	}

	/**
	 * Creates a trigger from a switch.
	 * @param aSwitch The switch to become a trigger.
	 * @return The trigger which is triggered when the switch is triggered.
	 */
	public static Trigger switchToTrigger(Switch aSwitch){
		return Hardware.makeTrigger(aSwitch::isTriggered);
	}

	/**
	 * Creates a trigger from a boolean supplier.
	 * @param booleanSupplier The boolean supplier to become a trigger.
	 * @return The trigger which is triggered when the boolean supplier is true.
	 */
	public static Trigger makeTrigger(BooleanSupplier booleanSupplier){
		return new Trigger() {
			@Override
			public boolean get() {
				return booleanSupplier.getAsBoolean();
			}
		};
	}

	/**
	 * Creates a switch from a boolean supplier.
	 * @param booleanSupplier The boolean supplier to become a switch.
	 * @return The switch which is triggered when the boolean supplier is true.
	 */
	public static Switch makeSwitch(BooleanSupplier booleanSupplier){
		return booleanSupplier::getAsBoolean;
	}

	/**
	 * Creates a resettable switch from a switch.
	 * @param aSwitch The switch to become a resettable switch.
	 * @return The resettable switch, which will remain true if the switch becomes triggered.
	 */
	public static ResettableSwitch makeResettableSwitch(Switch aSwitch){
		return new ResettableSwitch() {

			private boolean wasTriggered = false;

			@Override
			public void reset() {
				wasTriggered = false;
			}

			@Override
			public boolean isTriggered() {
				wasTriggered |= aSwitch.isTriggered();
				return wasTriggered;
			}
		};
	}

	/**
	 * Invert the direction of the Gyro.
	 *
	 * @param gyro
	 *            The Gyro to invert.
	 * @return The inverted Gyro.
	 */
	public static Gyro invertGyro(Gyro gyro) {
		return new Gyro() {

			@Override
			public void close() throws Exception {
				gyro.close();
			}

			@Override
			public void reset() {
				gyro.reset();
			}

			@Override
			public double getRate() {
				return -gyro.getRate();
			}

			@Override
			public double getAngle() {
				return -gyro.getAngle();
			}

			@Override
			public void calibrate() {
				gyro.calibrate();
			}
		};
	}

	/**
	 * Creates potentiometer.
	 * @param port The analog port that the potentiometer is plugged into.
	 * @param degreeRange The total range in degrees that the potentiometer can turn (pass a negative number to invert)
     * @param zeroPoint The zero point of the potentiometer. If you expect a position to be 0, but it is reading X degrees, put X here. (ex. actual 1000 to 1100 degrees, expected 0 to 100 degrees. Put 1000 here.)
	 * @return A potentiometer.
     */
	public static AnalogPotentiometer createPotentiometer(int port, double degreeRange, double zeroPoint){
        return new AnalogPotentiometer(port, degreeRange, -zeroPoint);
    }

	/**
	 * Creates a 10 turn potentiometer as sold by Andymark.
	 * @param port The analog port that the potentiometer is plugged into.
     * @param zeroPoint The zero point of the potentiometer. If you expect a position to be 0, but it is reading X degrees, put X here. (ex. actual 1000 to 1100 degrees, expected 0 to 100 degrees. Put 1000 here.)
	 * @return A 10 turn potentiometer.
     */
	public static AnalogPotentiometer create10TurnPotentiometer(int port, double zeroPoint){
        return createPotentiometer(port, 3600, -zeroPoint);
    }

    public static Drivetrain createDrivetrain(DifferentialDrive robotDrive){
        return new Drivetrain(){

            @Override
            public void stop() {
                robotDrive.stopMotor();
            }

            @Override
            public void tank(double leftSpeed, double rightSpeed) {
                robotDrive.tankDrive(leftSpeed, rightSpeed, false);
            }

            @Override
            public void arcade(double speed, double turn) {
                robotDrive.arcadeDrive(speed, turn, false);
            }
        };
    }

	/**
	 * Convert a voltage to a PWM signal (percent power) based on the current voltage of the battery
	 * @param voltage the desired voltage
	 * @param batteryVoltageSensor the battery voltage sensor
	 * @return the PWM signal [-1, 1] which delivers the desired voltage
	 */
    public static double voltageToPWM(double voltage, VoltageSensor batteryVoltageSensor){
    	if (batteryVoltageSensor == null || batteryVoltageSensor.getVoltage() == 0){
    		return 0;
		}
    	double rawPWM = voltage / batteryVoltageSensor.getVoltage();
		return GMath.clamp(rawPWM, -1, 1);
	}

	public static Subsystem noSubsystem(){
    	return new Subsystem() {
		};
	}

}


text:
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">

        <title>公告</title>
        <link rel="icon" type="image/png" th:href="@{/resources/image/logo.png}"/>
        <link rel="stylesheet" type="text/css" th:href="@{/resources/css/notice/notice-list.css}"/>

                    邮币圈

                    邮币卡投资者的圈子

                点击下载

                    交易所

                        全部

                    公告类型

                        全部

        <input id="presentExchangeId" type="hidden" value="0"/>

                    全部

        <input id="presentNoticeType" type="hidden" value="0"/>

                    全部


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using Microsoft.CodeAnalysis.Text;

namespace Roslyn.Test.Utilities
{
    internal sealed partial class SourceWithMarkedNodes
    {
        internal struct MarkedSpan
        {
            public readonly TextSpan MarkedSyntax;
            public readonly TextSpan MatchedSpan;
            public readonly string TagName;
            public readonly int SyntaxKind;
            public readonly int Id;
            public readonly int ParentId;

            public MarkedSpan(TextSpan markedSyntax, TextSpan matchedSpan, string tagName, int syntaxKind, int id, int parentId)
            {
                MarkedSyntax = markedSyntax;
                MatchedSpan = matchedSpan;
                TagName = tagName;
                SyntaxKind = syntaxKind;
                Id = id;
                ParentId = parentId;
            }
        }
    }
}


text:
function is_friend(id) {
	var error = '';
	var ids = [];
	var petitions = [];
	var pending = [];
	var path = Ti.App.dataURL + 'friends_id.php';
	var client = Ti.Network.createHTTPClient({
		onload: function(e) {
			Ti.API.info('success ' + this.responseText);
			var result = eval('(' + this.responseText + ')');
			if (result.status == 'ok') {
				ids = result.friends;
				petitions = result.petitions;
				pending = result.pending;
				if (Ti.App.inArray(id, ids)) {
					win.rightNavButton = newMessage;
					var help = require('help');
					help(L('Enviar mensaje privado'), win);
					tableData.push(rowSendMessage);
				} else if (Ti.App.inArray(id, pending)) {
					win.rightNavButton = addFriend;
					var help = require('help');
					help(L('Aceptar solicitud de amistad'), win);
					rowAddFriend._title.text = L('Aceptar solicitud de amistad');
					tableData.push(rowAddFriend);
				} else if (Ti.App.Properties.getString('login', null) != id) {
					win.rightNavButton = addFriend;
					var help = require('help');
					help(L('Enviar solicitud de amistad'), win);
					tableData.push(rowAddFriend);
				}
				view.data = tableData;

				if (Ti.App.inArray(id, petitions)) {
					addFriend.enabled = false;
					text1.text = L('Solicitud de amistad enviada');
					icon1.image = 'images/addFriend2.png';
				}
			} else {
				error = result.message;
			}
		},
		onerror: function(e) {
			error = L('Ha ocurrido un error con la conexión');
			Ti.API.info('error');
		},
		timeout: 15000
	});

	client.open('POST', path);
	client.send({
		userId:Ti.App.Properties.getString('login'),
		token:Ti.App.Properties.getString('token')
	});
}

is_friend(win.current.user_id);


text:
struct InstanceCounter
{
   InstanceCounter(){++counter;}
   InstanceCounter(const InstanceCounter&){++counter;}
   InstanceCounter & operator=(const InstanceCounter&){  return *this;  }
  ~InstanceCounter(){--counter;}
   static std::size_t counter;
};

std::size_t InstanceCounter::counter = 0;

using namespace boost::interprocess;

int main ()
{
   const int memsize = 16384;
   const char *const shMemName = test::get_process_id_name();

   try{
   shared_memory_object::remove(shMemName);

   //Named allocate capable shared mem allocator
   managed_shared_memory segment(create_only, shMemName, memsize);

   //STL compatible allocator object, uses allocate(), deallocate() functions
   typedef allocator<InstanceCounter,
                     managed_shared_memory::segment_manager>
      inst_allocator_t;
   const inst_allocator_t myallocator (segment.get_segment_manager());

   typedef vector<InstanceCounter, inst_allocator_t> MyVect;

   //We'll provoke an exception, let's see if exception handling works
   try{
      //Fill vector until there is no more memory
      MyVect myvec(myallocator);
      int i;
      for(i = 0; true; ++i){
         myvec.push_back(InstanceCounter());
      }
   }
   catch(boost::interprocess::bad_alloc &){
      if(InstanceCounter::counter != 0)
         return 1;
   }

   //We'll provoke an exception, let's see if exception handling works
   try{
      //Fill vector at the beginning until there is no more memory
      MyVect myvec(myallocator);
      int i;
      InstanceCounter ic;
      for(i = 0; true; ++i){
         myvec.insert(myvec.begin(), i, ic);
      }
   }
   catch(boost::interprocess::bad_alloc &){
      if(InstanceCounter::counter != 0)
         return 1;
   }
   catch(std::length_error &){
      if(InstanceCounter::counter != 0)
         return 1;
   }
   }
   catch(...){
      shared_memory_object::remove(shMemName);
      throw;
   }
   shared_memory_object::remove(shMemName);
   return 0;
}


text:
require("ember-bootstrap/mixins/text_support");

Bootstrap.Forms.TextField = Bootstrap.Forms.Field.extend({
  type: 'text',

  inputField: Ember.TextField.extend(Bootstrap.TextSupport, {
    typeBinding: 'parentView.type',
    sizeBinding: 'parentView.size'
  })
});


text:
<!--

 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/session_twopane_layout"
    xmlns:tools="http://schemas.android.com/tools"
    style="@style/Theme.Rhetolog"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="@dimen/sessiontwopanelayout_marginLeft"
    android:layout_marginRight="@dimen/sessiontwopanelayout_marginRight"
    android:divider="?android:attr/dividerHorizontal"
    android:orientation="horizontal"
    android:showDividers="middle"
    tools:context=".SessionListActivity" >

    <fragment
        android:id="@+id/session_list"
        android:name="name.zurell.kirk.apps.android.rhetolog.SessionListFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        tools:layout="@layout/simple_list_item_activated_1"
         />

    <FrameLayout android:id="@+id/session_detail_container"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3" />

</LinearLayout>


text:
package org.jaxen.function.ext;

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

import org.jaxen.Context;
import org.jaxen.ContextSupport;
import org.jaxen.Function;
import org.jaxen.FunctionCallException;
import org.jaxen.Navigator;
import org.jaxen.XPath;
import org.jaxen.function.StringFunction;

/**
 * node-set evaluate(string)
 *
 * @author Erwin Bolwidt (ejb @ klomp.org)
 */
public class EvaluateFunction implements Function
{
    public Object call( Context context, List args )
        throws FunctionCallException
    {
        if ( args.size() == 1 ) {
            return evaluate( context, args.get(0));
        }

        throw new FunctionCallException( "evaluate() requires one argument" );
    }

    public static List evaluate (Context context, Object arg)
        throws FunctionCallException
    {
        List contextNodes = context.getNodeSet();

        if (contextNodes.size() == 0)
            return Collections.EMPTY_LIST;

        Navigator nav = context.getNavigator();

        String xpathString;
        if ( arg instanceof String )
            xpathString = (String)arg;
        else
            xpathString = StringFunction.evaluate(arg, nav);

        try {
            XPath xpath = nav.parseXPath(xpathString);
            ContextSupport support = context.getContextSupport();
            xpath.setVariableContext( support.getVariableContext() );
            xpath.setFunctionContext( support.getFunctionContext() );
            xpath.setNamespaceContext( support.getNamespaceContext() );
            return xpath.selectNodes( context.duplicate() );
        }
        catch ( org.jaxen.saxpath.SAXPathException e ) {
            throw new FunctionCallException(e.toString());
        }
    }
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<title>iGoogle</title>

					<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
						Toggle navigation

					</button>
					iGoogle

Date

Twitter

Youtube

GoogleMaps

News

Weather

Flickr

	<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">


text:
using System;
using System.IO;
using System.Collections.Generic;

namespace Thor.DataForge
{

public class Utilities
{
    private static Logger m_Logger = new Logger();

    public static Logger Log
    {
        get
        {
            return m_Logger;
        }
    }

    public static string TrimQuotes(string str)
    {
        if (str.Length > 2)
            return str.Substring(1, str.Length - 2);
        else
            return "";
    }

    public static string AddQuotes(string str)
    {
        return string.Format("\"{0}\"", str);
    }

    public static string GetRelativePath(string path, string relativeTo, string newExt)
    {
        Uri fromUri = new Uri(relativeTo + "\\");
        Uri toUri = new Uri(path);

        Uri relativeUri = fromUri.MakeRelativeUri(toUri);
        String relativePath = Uri.UnescapeDataString(relativeUri.ToString());

        path = relativePath.Replace('/', Path.DirectorySeparatorChar);

        if (newExt != null)
            path = Path.ChangeExtension(path, newExt);

        return path;
    }

    public static T GetOption<T>(List<Option> options) where T : Option
    {
        if (options == null)
            return null;

        foreach(var o in options)
        {
            T t = o as T;
            if (t != null)
                return t;
        }

        return null;
    }
}

public class Logger
{
    private StreamWriter log = new StreamWriter(Console.OpenStandardOutput());

    void RedirectStream(Stream st)
    {
        log = new StreamWriter(st);
    }

    public void Write(string text)
    {
        log.Write(text);
        log.Flush();
    }

    public void WriteLine(string text)
    {
        log.WriteLine(text);
        log.Flush();
    }

    public void RedirectStream(string file)
    {
        log = new StreamWriter(file);
    }

    public void WriteLine(object obj)
    {
        log.WriteLine(obj);
        log.Flush();
    }

    public void PrintExceptionInfo(Exception e)
    {
        WriteLine(e.Message);
        //WriteLine(e.StackTrace);
    }
}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.notrace.MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <include layout="@layout/include_toolbar"
            android:id="@+id/toolbar_container"/>

        <FrameLayout
            android:id="@+id/container"
            android:layout_below="@id/toolbar_container"
            android:layout_above="@+id/controls_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></FrameLayout>

        <android.support.v7.widget.CardView
            android:id="@+id/controls_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:cardElevation="8dp"

            />

        <fragment
            android:name="com.notrace.ui.PlaybackControlsFragment"
            android:id="@+id/fragment_playback_controls"
            android:layout_alignParentBottom="true"
            tools:layout="@layout/fragment_playback_controls"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </RelativeLayout>

</android.support.v4.widget.DrawerLayout>


text:
import Tabs from './tabs'
import Pane from '../Pane/pane'
import {mount, render, shallow} from 'enzyme'
import React from 'react'
import assert from 'assert'

describe('Tabs', function () {
  it('Tabs component imported successfuly', function () {
    // let wrapper = shallow(
    //   <Tabs hide={true} selected={0}>
    //     <Pane label='Some sample child'>
    //       <div>
    //         <h1> Here is the content for the first child </h1>
    //       </div>
    //     </Pane>
    //   </Tabs>
    // )
    // assert.ok(wrapper)
    expect(true).to.be.true
  })
})


text:
package com.kuizhiqing.dtn.data.statistic;

public class Service {

	public static void main(String[] args) {
		String[] pres = {"pmtr","sassy","infocom2006","mit_l","roller"};
		for(String pre : pres){
			String file = pre+".txt";
			ContactStat cs = new ContactStat();
			try {
				System.out.println("op...");
				cs.op(file);
				System.out.println("report...");
				cs.report(pre);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}


text:
/**
 * Service that will fetch the user credentials from the database.
 * @param $q
 * @param $rootScope
 * @param Restangular
 * @param USER_EVENTS
 */
var UserService = function($q, $rootScope, Restangular, USER_EVENTS) {

    // Promise that will always return the currently found user.
    var deferred = null;

    // User service that is being created.
    var UserService = {};

    /**
     * Return a promise that will resolve to the user.
     * @returns {*}
     */
    UserService.getUser = function() {
        if (deferred === null) {

            var _deferred = Restangular.one('self').get().then(function(user) {
                // After resolved, replace the cache with the temporary value.
                deferred = _deferred;
                $rootScope.$broadcast(USER_EVENTS.USER_DEFINED, user);
                return user;
            }).catch(function(message) {
                console.log('Error fetching user: ' + message);
                return $q.reject(message);
            });

            // Until the user has been resolved, return a temporary value.
            return _deferred;

        }

        return deferred;
    };

    /**
     * Clear out the cached user promise.  This means that the next call to getUser will force a login.
     */
    UserService.clearUser = function() {
        if (deferred !== null) {
            deferred = null;
            $rootScope.$broadcast(USER_EVENTS.USER_CLEARED);
        }
    };

    /**
     * Allows for a quick query to determine if the user has been defined from the back-end or not.
     * @returns {boolean}
     */
    UserService.isUserDefined = function() {
        return deferred !== null;
    };

    return UserService;

};

angular.module('user')
    .factory('UserService', ['$q', '$rootScope', 'Restangular', 'USER_EVENTS', UserService]);


text:
package cn.limw.summer.mongo.driver.util;

import java.io.StringReader;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.Function;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.select.SelectBody;
import net.sf.jsqlparser.statement.select.SelectExpressionItem;
import net.sf.jsqlparser.statement.select.SelectItem;
import net.sf.jsqlparser.statement.update.Update;

import org.apache.log4j.Logger;

import cn.limw.summer.mongo.driver.query.Query;
import cn.limw.summer.mongo.driver.query.impl.CountQuery;
import cn.limw.summer.mongo.driver.query.impl.DeleteQuery;
import cn.limw.summer.mongo.driver.query.impl.InsertQuery;
import cn.limw.summer.mongo.driver.query.impl.MaxQuery;
import cn.limw.summer.mongo.driver.query.impl.MinQuery;
import cn.limw.summer.mongo.driver.query.impl.SelectQuery;
import cn.limw.summer.mongo.driver.query.impl.UpdateQuery;
import cn.limw.summer.util.Errors;

/**
 * @author li
 * @version 1 2014年3月12日上午11:29:15
 */
public class Querys {
    private static final Logger log = Logs.get();

    private static final String COUNT = "COUNT", MAX = "MAX", MIN = "MIN";;

    private static final CCJSqlParserManager SQL_PARSER_MANAGER = new CCJSqlParserManager();

    /**
     * SQL解析缓存
     */
    private static final Map<String, Query> QUERY_CACHE = new ConcurrentHashMap<String, Query>();

    /**
     * 解析SQL语句,有缓存
     */
    public static Query parseQuery(String sql) {
        try {
            Query query = QUERY_CACHE.get(sql);
            if (null == query) {
                query = doParse(sql);
                QUERY_CACHE.put(sql, query);
            }
            return query;
        } catch (Throwable e) {
            throw Errors.wrap(sql + " " + e.getMessage(), e);
        }
    }

    private synchronized static Query doParse(String sql) throws Throwable {
        Query query;
        Statement statement = SQL_PARSER_MANAGER.parse(new StringReader(sql));
        if (statement instanceof Select) {
            if (isCount((Select) statement)) {
                query = new CountQuery();
            } else if (isMax((Select) statement)) {
                query = new MaxQuery();
            } else if (isMin((Select) statement)) {
                query = new MinQuery();
            } else {
                query = new SelectQuery();
            }
        } else if (statement instanceof Insert) {
            query = new InsertQuery();
        } else if (statement instanceof Delete) {
            query = new DeleteQuery();
        } else if (statement instanceof Update) {
            query = new UpdateQuery();
        } else {
            throw Errors.wrap("error query " + sql);
        }
        query.setStatement(statement);
        log.trace("doParse() sql = " + sql + ", query = " + query);
        return query;
    }

    /**
     * 第一种 LIMIT A 第二种 LIMIT B,A 第三种 LIMIT A OFFSET B
     */
    public static Boolean isLimitBA(String sql) {
        sql = sql.toUpperCase();
        int limit_index = sql.indexOf(" LIMIT ");
        if (limit_index < 0) {
            return false;
        }
        int comma_index = sql.indexOf((int) ',', limit_index);
        if (comma_index < 0) {
            return false;
        }
        String _b = sql.substring(limit_index + " LIMIT ".length(), comma_index).trim();
        return _b.equals("?") || ConvertUtil.isInt(_b);
    }

    /**
     * 是否Count查询
     */
    private static Boolean isCount(Select select) {
        Function function = getSelectFunction(select);
        return null != function && function.getName().equalsIgnoreCase(COUNT);
    }

    /**
     * 是否Min查询
     */
    private static Boolean isMin(Select select) {
        Function function = getSelectFunction(select);
        return null != function && function.getName().equalsIgnoreCase(MIN);
    }

    /**
     * 是否Max查询
     */
    private static Boolean isMax(Select select) {
        Function function = getSelectFunction(select);
        return null != function && function.getName().equalsIgnoreCase(MAX);
    }

    /**
     * getFirstSelectItemAsFunctionOrNull
     *
     * @param select
     * @return
     */
    public static Function getSelectFunction(Select select) {
        SelectBody selectBody = select.getSelectBody();
        PlainSelect plainSelect = (PlainSelect) selectBody;
        List<SelectItem> selectItems = plainSelect.getSelectItems();
        if (1 == selectItems.size() && selectItems.get(0) instanceof SelectExpressionItem) {
            SelectExpressionItem selectExpressionItem = ((SelectExpressionItem) selectItems.get(0));
            Expression expression = selectExpressionItem.getExpression();
            return expression instanceof Function ? (Function) expression : null;
        }
        return null;
    }
}


text:
BOARD_TAG = uno
ARDUINO_PORT = /dev/cu.usb*

ARDUINO_LIBS = Wire

include /usr/local/arduino/Arduino.mk


text:
import * as React from "react";
import PropTypes, { bool } from "prop-types";
import { listenTo, Component, handles, dispatch, CarbonLabel } from "../CarbonFlux";
import styled, { css } from "styled-components";
import { FormattedMessage, defineMessages } from 'react-intl';
import * as cx from "classnames";
import theme from "../theme";
import icons from "../theme-icons";
import Icon from "./Icon";
import { MainButtonComponent } from "../components/CommonStyle";

interface IMainButtonProps extends IReactElementProps {
    label: string;
}

export default class MainButton extends Component<IMainButtonProps, {}> {
    render() {
        var { ...props } = this.props;

        return <MainButtonComponent {...props}>
            <CarbonLabel id={this.props.label} />
        </MainButtonComponent>;
    }
}


text:
package rtdc.core.impl.voip;

public interface TextGroup {

    TextMessage createTextMessage(String message);

    void sendTextMessage(TextMessage textMessage);

}


text:
from __future__ import unicode_literals

from django.db import migrations

def set_null_to_blank(queryset, fields):
    for element in queryset:
        for field in fields:
            setattr(element, field, getattr(element, field) or '')
        element.save()

def run_data_migration(apps, schema_editor):
    Catalog = apps.get_model('questions', 'Catalog')
    Section = apps.get_model('questions', 'Section')
    QuestionSet = apps.get_model('questions', 'QuestionSet')
    Question = apps.get_model('questions', 'Question')

    set_null_to_blank(Catalog.objects.all(), [
        'uri',
        'uri_prefix',
        'key',
        'comment',
        'title_lang1',
        'title_lang2',
        'title_lang3',
        'title_lang4',
        'title_lang5',
    ])
    set_null_to_blank(Section.objects.all(), [
        'uri',
        'uri_prefix',
        'key',
        'path',
        'comment',
        'title_lang1',
        'title_lang2',
        'title_lang3',
        'title_lang4',
        'title_lang5',
    ])
    set_null_to_blank(QuestionSet.objects.all(), [
        'uri',
        'uri_prefix',
        'key',
        'path',
        'comment',
        'title_lang1',
        'title_lang2',
        'title_lang3',
        'title_lang4',
        'title_lang5',
        'help_lang1',
        'help_lang2',
        'help_lang3',
        'help_lang4',
        'help_lang5',
    ])
    set_null_to_blank(Question.objects.all(), [
        'uri',
        'uri_prefix',
        'key',
        'comment',
        'text_lang1',
        'text_lang2',
        'text_lang3',
        'text_lang4',
        'text_lang5',
        'help_lang1',
        'help_lang2',
        'help_lang3',
        'help_lang4',
        'help_lang5',
        'value_type',
        'widget_type',
        'unit',
    ])

class Migration(migrations.Migration):

    dependencies = [
        ('questions', '0040_add_language_fields'),
    ]

    operations = [
        migrations.RunPython(run_data_migration),
    ]


text:
package com.a9ski.gerrit.ldap;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.entry.Attribute;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.entry.ModificationOperation;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.a9ski.gerrit.exceptions.PluginException;
import com.a9ski.gerrit.ldap.exceptions.InvalidPasswordException;
import com.a9ski.gerrit.ldap.exceptions.UserNotFoundException;
import com.a9ski.gerrit.model.User;
import com.a9ski.gerrit.utils.CryptoUtils;

public class LdapClient {

	private static final Logger logger = LoggerFactory.getLogger(LdapClient.class);

	private LdapConnection connection;

	private final String host;
	private final int port;

	private final String login;
	private final String password;

	private final String accountBase;
	private final String groupBase;

	public LdapClient(final URI uri, final String login, final String password, final String accountBase, final String groupBase) {
		if (uri.getHost() != null) {
			this.host = uri.getHost();
		} else {
			this.host = "localhost";
		}
		if (uri.getPort() != -1) {
			this.port = uri.getPort();
		} else {
			this.port = 389;
		}
		this.login = login;
		this.password = password;
		this.accountBase = accountBase;
		this.groupBase = groupBase;

		if (logger.isDebugEnabled()) {
			logger.debug("LDAP Host:" + host);
			logger.debug("LDAP Port:" + port);
			logger.debug("LDAP Login:" + login);
			logger.debug("LDAP Account base:" + accountBase);
			logger.debug("LDAP Group base:" + groupBase);
		}
	}

	public synchronized void connect() throws LdapException {
		if (connection != null && connection.isConnected()) {
			disconnect();
		}

		connection = new LdapNetworkConnection(host, port);
		// Password in clear text = danger !
		connection.bind(login, password);

		// The password is encrypted, but it does not protect against a MITM attack
		// connection.bind( "ou=example, dc=com", "{crypt}wSiewPyxdEC2c" );
	}

	public void disconnect() {
		if (connection != null) {
			synchronized(this) {
				try {
					connection.unBind();
				} catch(final LdapException ex) {
					logger.error("Error disconnecting LDAP client", ex);
				}

				try {
					connection.close();
				} catch (final IOException ex) {
					logger.error("Error disconnecting LDAP client", ex);
				}
				connection = null;
			}
		}
	}

	private synchronized void establishConnection() throws LdapException {
		if (connection == null || !connection.isConnected()) {
			connect();
		}
	}

	private String getAttr(Entry entry, String key, String defaultValue) {
		final Attribute attr = entry.get(key);
		if (attr != null) {
			try {
				return attr.getString();
			} catch (final LdapInvalidAttributeValueException ex) {
				logger.error(String.format("Cannot get attribute '%s' of entry '%s'", key, entry.getDn()), ex);
			}
		}
		return defaultValue;
	}

	public synchronized List<User> getUsers() throws LdapException, CursorException {
		establishConnection();
		try {
			//final EntryCursor cursor = connection.search( "ou=system", "(objectclass=*)", SearchScope.ONELEVEL, "*" );
			final EntryCursor cursor = connection.search( accountBase, "(objectclass=*)", SearchScope.ONELEVEL, "*" );

			final List<User> users = new ArrayList<User>();

			while ( cursor.next() ) {
			    final Entry entry = cursor.get();
	//		    if (entry.hasObjectClass("person")) {
	//
	//		    }
			    final String id = getAttr(entry, "uid", "");
			    final String firstName = getAttr(entry, "givenname", "");
			    final String lastName = getAttr(entry, "sn", "");
			    final String email = getAttr(entry, "mail", "");
			    final String password = getAttr(entry, "userpassword", "");
			    final User user = new User(id, firstName, lastName, email, password);
			    users.add(user);
			}

			return users;
		} finally {
			disconnect();
		}
	}

	public void forceChangePassword(String userId, String newPassword) throws LdapException, CursorException {
		establishConnection();
		try {
			final String filter = String.format("(uid=%s)", userId);
			final EntryCursor cursor = connection.search( accountBase, filter, SearchScope.ONELEVEL, "*" );
			if(cursor.next()) {
				final Entry entry = cursor.get();
				entry.put("userpassword", newPassword);
				connection.modify(entry, ModificationOperation.REPLACE_ATTRIBUTE);
			}
		} finally {
			disconnect();
		}
	}

	public void changePassword(String userId, String oldPassword, String newPassword) throws LdapException, CursorException, PluginException{
		establishConnection();
		try {
			final String filter = String.format("(uid=%s)", userId);
			final EntryCursor cursor = connection.search( accountBase, filter, SearchScope.ONELEVEL, "*" );
			if(cursor.next()) {
				final Entry entry = cursor.get();
				if (!oldPassword.equals(getAttr(entry, "userpassword", ""))) {
					throw new InvalidPasswordException("Old password doesn't match");
				}
				entry.put("userpassword", newPassword);
				connection.modify(entry, ModificationOperation.REPLACE_ATTRIBUTE);
			} else {
				throw new UserNotFoundException(String.format("User with ID '%s' not found. Filter is [%s]", userId, filter));
			}
		} finally {
			disconnect();
		}
	}
}


text:
import java.io.FileNotFoundException;
import java.util.ArrayList;

import main.woj.controllers.ActionController;
import main.woj.gameplay.Category;
import main.woj.gameplay.Game;
import main.woj.utils.QuestionDeserializer;

import com.esotericsoftware.yamlbeans.YamlException;

public class Main {
	public static void main(String[] args) throws FileNotFoundException, YamlException {
		ActionController game = new ActionController("lib/question_set.example.yml", "lib/question_set_round_2.yml");
	}
}


text:
<?php
include_once "client.php";

abstract class RIQObject
{
  private static $class = 'RIQBase';
  private static $cache = [];
  private static $cache_index = 0;
  private static $page_index = 0;
  protected static $page_length = 200;
  private static $fetch_options = array();
  private static $last_modified_date = null;
  private static $parent = null;

  abstract public function id();
  abstract public function payload();
  abstract public function parse($data);

  public function __toString()
  {
    $dataAux = $this->payload();
    ksort($dataAux);
    return json_encode($dataAux);
  }

  public function save($options=[])
  {
    if ($this->exists()) {
      return $this->update($options);
    } else {
      return $this->create($options);
    }
  }

  public function create($options=[])
  {
    $data = Client::post(static::endpoint(), $this->payload(), $options);
    if (count($data)>0) {
      $data = json_decode($data, true);
    }
    return $this->parse($data);
  }

  public function get($options=[])
  {
    $data = Client::fetch(static::endpoint().'/'.$this->id(), $options);
    if (count($data) > 0) {
      $data = json_decode($data, true);
    }
    return $this->parse($data);
  }

  public function update($options=[])
  {
    $data = Client::put(static::endpoint().'/'.$this->id(), $this->payload(), $options);
    if (count($data)>0) {
      $data = json_decode($data, true);
    }
    return $this->parse($data);
  }

  public function delete($options=[])
  {
    $data = Client::delete(static::endpoint().'/'.$this->id(), $options);
    if (count($data)>0) {
      $data = json_decode($data, true);
    }
    return $data;
  }

  public function exists()
  {
    if ($this->id() == null) {
      return false;
    }
    return Client::fetch(static::endpoint().'/'.$this->id()) != [];
  }

  public static function find_key($key, $array, $default=null)
  {
    return array_key_exists($key, $array) ? $array[$key] : $default;
  }
}
?>


text:
package com.dytech.edge.importexport;

import javax.swing.JPanel;

/** @author Nicholas Read */
public abstract class WizardPage extends JPanel {
  protected SharedData data;
  protected WizardFrame frame;

  public WizardPage(SharedData data) {
    this.data = data;
  }

  public abstract boolean onNext();

  public abstract boolean onBack();

  public abstract void onShow();

  public void setFrame(WizardFrame frame) {
    this.frame = frame;
  }

  public SharedData getData() {
    return data;
  }
}


text:
package org.apache.bookkeeper.util;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * Daemon thread factory.
 */
public class DaemonThreadFactory implements ThreadFactory {
    private ThreadFactory defaultThreadFactory = Executors.defaultThreadFactory();
    private int priority = Thread.NORM_PRIORITY;
    public DaemonThreadFactory() {
    }
    public DaemonThreadFactory(int priority) {
        assert priority >= Thread.MIN_PRIORITY && priority <= Thread.MAX_PRIORITY;
        this.priority = priority;
    }
    @Override
    public Thread newThread(Runnable r) {
        Thread thread = defaultThreadFactory.newThread(r);
        thread.setDaemon(true);
        thread.setPriority(priority);
        return thread;
    }
}


text:
#include "paddle/phi/kernels/sparse/batch_norm_kernel.h"
#include "paddle/phi/core/kernel_registry.h"
#include "paddle/phi/kernels/batch_norm_kernel.h"
#include "paddle/phi/kernels/sparse/empty_kernel.h"

namespace phi {
namespace sparse {

template <typename T, typename Context>
void BatchNormCooKernel(const Context& dev_ctx,
                        const SparseCooTensor& x,
                        const DenseTensor& mean,
                        const DenseTensor& variance,
                        const DenseTensor& scale,
                        const DenseTensor& bias,
                        bool is_test,
                        float momentum,
                        float epsilon,
                        const std::string& data_layout,
                        bool use_global_stats,
                        bool trainable_statistics,
                        SparseCooTensor* y,
                        DenseTensor* mean_out,
                        DenseTensor* variance_out,
                        DenseTensor* saved_mean,
                        DenseTensor* saved_variance,
                        DenseTensor* reserve_space) {
  EmptyLikeCooKernel<T, Context>(dev_ctx, x, y);
  phi::BatchNormKernel<T, Context>(dev_ctx,
                                   x.values(),
                                   mean,
                                   variance,
                                   scale,
                                   bias,
                                   is_test,
                                   momentum,
                                   epsilon,
                                   data_layout,
                                   use_global_stats,
                                   trainable_statistics,
                                   y->mutable_values(),
                                   mean_out,
                                   variance_out,
                                   saved_mean,
                                   saved_variance,
                                   reserve_space);
  y->SetIndicesDict(x.GetIndicesDict());
}

}  // namespace sparse
}  // namespace phi

PD_REGISTER_KERNEL(batch_norm_coo,
                   CPU,
                   ALL_LAYOUT,
                   phi::sparse::BatchNormCooKernel,
                   float,
                   double) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_COO);
}

#if defined(PADDLE_WITH_HIP)
PD_REGISTER_KERNEL(batch_norm_coo,
                   GPU,
                   ALL_LAYOUT,
                   phi::sparse::BatchNormCooKernel,
                   float,
                   phi::dtype::float16) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_COO);
  kernel->InputAt(1).SetDataType(phi::DataType::FLOAT32);
  kernel->InputAt(2).SetDataType(phi::DataType::FLOAT32);
  kernel->InputAt(3).SetDataType(phi::DataType::FLOAT32);
  kernel->InputAt(4).SetDataType(phi::DataType::FLOAT32);
  kernel->OutputAt(1).SetDataType(phi::DataType::FLOAT32);
  kernel->OutputAt(2).SetDataType(phi::DataType::FLOAT32);
  kernel->OutputAt(3).SetDataType(phi::DataType::FLOAT32);
  kernel->OutputAt(4).SetDataType(phi::DataType::FLOAT32);
}
#endif

#if defined(PADDLE_WITH_CUDA)
PD_REGISTER_KERNEL(batch_norm_coo,
                   GPU,
                   ALL_LAYOUT,
                   phi::sparse::BatchNormCooKernel,
                   float,
                   double,
                   phi::dtype::float16) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_COO);
  if (kernel_key.dtype() == phi::DataType::FLOAT16) {
    kernel->InputAt(1).SetDataType(phi::DataType::FLOAT32);
    kernel->InputAt(2).SetDataType(phi::DataType::FLOAT32);
    kernel->InputAt(3).SetDataType(phi::DataType::FLOAT32);
    kernel->InputAt(4).SetDataType(phi::DataType::FLOAT32);
    kernel->OutputAt(1).SetDataType(phi::DataType::FLOAT32);
    kernel->OutputAt(2).SetDataType(phi::DataType::FLOAT32);
    kernel->OutputAt(3).SetDataType(phi::DataType::FLOAT32);
    kernel->OutputAt(4).SetDataType(phi::DataType::FLOAT32);
  }
}
#endif


text:
// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.

#include "cefclient/browser/urlrequest_test.h"

#include <string>

#include "include/base/cef_bind.h"
#include "include/base/cef_callback.h"
#include "include/base/cef_logging.h"
#include "include/cef_urlrequest.h"
#include "include/wrapper/cef_helpers.h"

namespace client {
namespace urlrequest_test {

namespace {

const char kTestUrl[] = "http://tests/urlrequest";
const char kTestMessageName[] = "URLRequestTest";

// Implementation of CefURLRequestClient that stores response information. Only
// accessed on the UI thread.
class RequestClient : public CefURLRequestClient {
 public:
  // Callback to be executed on request completion.
  typedef base::Callback<void(CefURLRequest::ErrorCode /*error_code*/,
                              const std::string& /*download_data*/)> Callback;

  explicit RequestClient(const Callback& callback)
      : callback_(callback) {
    CEF_REQUIRE_UI_THREAD();
    DCHECK(!callback_.is_null());
  }

  void Detach() {
    CEF_REQUIRE_UI_THREAD();
    if (!callback_.is_null())
      callback_.Reset();
  }

  void OnRequestComplete(CefRefPtr<CefURLRequest> request) OVERRIDE {
    CEF_REQUIRE_UI_THREAD();
    if (!callback_.is_null()) {
      callback_.Run(request->GetRequestError(), download_data_);
      callback_.Reset();
    }
  }

  void OnUploadProgress(CefRefPtr<CefURLRequest> request,
                        int64 current,
                        int64 total) OVERRIDE {
  }

  void OnDownloadProgress(CefRefPtr<CefURLRequest> request,
                          int64 current,
                          int64 total) OVERRIDE {
  }

  void OnDownloadData(CefRefPtr<CefURLRequest> request,
                      const void* data,
                      size_t data_length) OVERRIDE {
    CEF_REQUIRE_UI_THREAD();
    download_data_ += std::string(static_cast<const char*>(data), data_length);
  }

   bool GetAuthCredentials(bool isProxy,
                           const CefString& host,
                           int port,
                           const CefString& realm,
                           const CefString& scheme,
                           CefRefPtr<CefAuthCallback> callback) OVERRIDE {
     return false;
   }

 private:
  Callback callback_;
  std::string download_data_;

  IMPLEMENT_REFCOUNTING(RequestClient);
  DISALLOW_COPY_AND_ASSIGN(RequestClient);
};

// Handle messages in the browser process. Only accessed on the UI thread.
class Handler : public CefMessageRouterBrowserSide::Handler {
 public:
  Handler() {
    CEF_REQUIRE_UI_THREAD();
  }

  ~Handler() {
    CancelPendingRequest();
  }

  // Called due to cefQuery execution in urlrequest.html.
  bool OnQuery(CefRefPtr<CefBrowser> browser,
               CefRefPtr<CefFrame> frame,
               int64 query_id,
               const CefString& request,
               bool persistent,
               CefRefPtr<Callback> callback) OVERRIDE {
    CEF_REQUIRE_UI_THREAD();

    // Only handle messages from the test URL.
    const std::string& url = frame->GetURL();
    if (url.find(kTestUrl) != 0)
      return false;

    const std::string& message_name = request;
    if (message_name.find(kTestMessageName) == 0) {
      const std::string& url = message_name.substr(sizeof(kTestMessageName));

      CancelPendingRequest();

      DCHECK(!callback_.get());
      DCHECK(!urlrequest_.get());

      callback_ = callback;

      // Create a CefRequest for the specified URL.
      CefRefPtr<CefRequest> request = CefRequest::Create();
      request->SetURL(url);
      request->SetMethod("GET");

      // Callback to be executed on request completion.
      // It's safe to use base::Unretained() here because there is only one
      // RequestClient pending at any given time and we explicitly detach the
      // callback in the Handler destructor.
      const RequestClient::Callback& callback =
          base::Bind(&Handler::OnRequestComplete, base::Unretained(this));

      // Create and start the new CefURLRequest.
      urlrequest_ = CefURLRequest::Create(request,
                                          new RequestClient(callback),
                                          NULL);

      return true;
    }

    return false;
  }

 private:
  // Cancel the currently pending URL request, if any.
  void CancelPendingRequest() {
    CEF_REQUIRE_UI_THREAD();

    if (urlrequest_.get()) {
      // Don't execute the callback when we explicitly cancel the request.
      static_cast<RequestClient*>(urlrequest_->GetClient().get())->Detach();

      urlrequest_->Cancel();
      urlrequest_ = NULL;
    }

    if (callback_.get()) {
      // Must always execute |callback_| before deleting it.
      callback_->Failure(ERR_ABORTED, test_runner::GetErrorString(ERR_ABORTED));
      callback_ = NULL;
    }
  }

  void OnRequestComplete(CefURLRequest::ErrorCode error_code,
                         const std::string& download_data) {
    CEF_REQUIRE_UI_THREAD();

    if (error_code == ERR_NONE)
      callback_->Success(download_data);
    else
      callback_->Failure(error_code, test_runner::GetErrorString(error_code));

    callback_ = NULL;
    urlrequest_ = NULL;
  }

  CefRefPtr<Callback> callback_;
  CefRefPtr<CefURLRequest> urlrequest_;

  DISALLOW_COPY_AND_ASSIGN(Handler);
};

}  // namespace

void CreateMessageHandlers(test_runner::MessageHandlerSet& handlers) {
  handlers.insert(new Handler());
}

}  // namespace urlrequest_test
}  // namespace client


text:
package de.baywa.tecb2bwebgwt.client.ui.page.articleupload;

import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.ui.Widget;
import com.gwtplatform.mvp.client.ViewImpl;

import javax.inject.Inject;

/**
 * View of the page, gwt implementation.
 *
 * @author Manfred Tremmel
 * @version $Rev$, $Date$
 *
 */
public class ArticleUploadViewImpl extends ViewImpl implements ArticleUploadPresenter.MyView {

  interface Binder extends UiBinder<Widget, ArticleUploadViewImpl> {
  }

  @Inject
  public ArticleUploadViewImpl(final Binder puiBinder) {
    super();
    this.initWidget(puiBinder.createAndBindUi(this));
  }
}


text:
package io.shaoshuai.rms.system.po;

import java.io.Serializable;
import java.util.Date;

public class DictionaryValue implements Serializable {
    private Integer dictionaryValueId;

    private Integer dictionaryId;

    private String dictionaryValue;

    private String dictionaryValueName;

    private Integer parentId;

    private Short sequenceNumber;

    private Date createTime;

    private Date updateTime;

    private Short isDelete;

    private static final long serialVersionUID = 1L;

    public Integer getDictionaryValueId() {
        return dictionaryValueId;
    }

    public void setDictionaryValueId(Integer dictionaryValueId) {
        this.dictionaryValueId = dictionaryValueId;
    }

    public Integer getDictionaryId() {
        return dictionaryId;
    }

    public void setDictionaryId(Integer dictionaryId) {
        this.dictionaryId = dictionaryId;
    }

    public String getDictionaryValue() {
        return dictionaryValue;
    }

    public void setDictionaryValue(String dictionaryValue) {
        this.dictionaryValue = dictionaryValue == null ? null : dictionaryValue.trim();
    }

    public String getDictionaryValueName() {
        return dictionaryValueName;
    }

    public void setDictionaryValueName(String dictionaryValueName) {
        this.dictionaryValueName = dictionaryValueName == null ? null : dictionaryValueName.trim();
    }

    public Integer getParentId() {
        return parentId;
    }

    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }

    public Short getSequenceNumber() {
        return sequenceNumber;
    }

    public void setSequenceNumber(Short sequenceNumber) {
        this.sequenceNumber = sequenceNumber;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public Short getIsDelete() {
        return isDelete;
    }

    public void setIsDelete(Short isDelete) {
        this.isDelete = isDelete;
    }
}


text:
(function() {

  "use strict";

  var _ = require("underscore");

  function keyFor(example) {
    return example.file_path + ":" + example.line_number;
  }

  function resultsToProgress(results, runNumber) {
    var examplesMap = {},
        failingSpecsList = [],
        progress = {
          "summaryLine": results.summary_line,
          "summary": results.summary,
          "examples": examplesMap,
          "failingSpecs": failingSpecsList
        };
    results.examples.forEach(function(example) {
      examplesMap[keyFor(example)] = example;
      if (example.status === "passed") {
        example.successfulOnTry = runNumber;
      } else if (example.status === "failed") {
        failingSpecsList.push(keyFor(example));
      }
    });
    return progress;
  }

  function mergeProgress(existingProgress, newProgress) {
    _.extend(existingProgress.examples, newProgress.examples);
    _.extend(existingProgress.summary, newProgress.summary);
    existingProgress.failingSpecs = newProgress.failingSpecs;
    existingProgress.summaryLine = newProgress.summaryLine;
    return existingProgress;
  }

  module.exports.resultsToProgress = resultsToProgress;
  module.exports.mergeProgress = mergeProgress;

})();


text:
"""Functional tests for fused batch norm operations."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

from tensorflow.compiler.tests.xla_test import XLATestCase
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_nn_ops
from tensorflow.python.ops import nn
from tensorflow.python.platform import test

class FusedBatchNormTest(XLATestCase):

  def _reference_training(self, x, scale, offset, epsilon, data_format):
    if data_format != "NHWC":
      raise ValueError("data_format must be NHWC, got %s." % data_format)
    x_square = x * x
    x_square_sum = np.sum(x_square, (0, 1, 2))
    x_sum = np.sum(x, axis=(0, 1, 2))
    element_count = np.size(x) / int(np.shape(x)[0])
    mean = x_sum / element_count
    var = x_square_sum / element_count - mean * mean
    normalized = (x - mean) / np.sqrt(var + epsilon)
    return (normalized * scale + offset), mean, var

  def _reference_grad(self, x, grad_y, scale, mean, var, epsilon, data_format):
    if data_format != "NHWC":
      raise ValueError("data_format must be NHWC, got %s." % data_format)
    grad_x = grad_y * scale * np.sqrt(var + epsilon)
    grad_scale = np.sum(
        grad_y * (x - mean) * np.sqrt(var + epsilon), axis=(0, 1, 2))
    grad_offset = np.sum(grad_y, axis=(0, 1, 2))
    return grad_x, grad_scale, grad_offset

  def testBasic(self):
    x_shape = [2, 2, 6, 2]
    scale_shape = [2]
    x_val = np.random.random_sample(x_shape).astype(np.float32)
    scale_val = np.random.random_sample(scale_shape).astype(np.float32)

    offset_val = np.random.random_sample(scale_shape).astype(np.float32)
    mean_val = np.random.random_sample(scale_shape).astype(np.float32)
    var_val = np.random.random_sample(scale_shape).astype(np.float32)
    data_format = "NHWC"
    with self.test_session() as sess, self.test_scope():
      # To avoid constant folding
      t_val = array_ops.placeholder(np.float32, shape=x_shape, name="x")
      scale = array_ops.placeholder(np.float32, shape=[2], name="scale")
      offset = array_ops.placeholder(np.float32, shape=[2], name="offset")
      epsilon = 0.001
      y, mean, var = nn.fused_batch_norm(
          t_val,
          scale,
          offset,
          mean=None,
          variance=None,
          epsilon=epsilon,
          data_format=data_format,
          is_training=True)
      y_val, mean_val, var_val = sess.run(
          [y, mean, var], {t_val: x_val,
                           scale: scale_val,
                           offset: offset_val})
      y_ref, mean_ref, var_ref = self._reference_training(
          x_val, scale_val, offset_val, epsilon, data_format)
      self.assertAllClose(mean_val, mean_ref, atol=1e-3)
      self.assertAllClose(y_val, y_ref, atol=1e-3)
      self.assertAllClose(var_val, var_ref, atol=1e-3)

  def testGradient(self):
    # TODO(b/64270657): Use gradient_checker here in addition to comparing with
    # this reference implementation.
    x_shape = [2, 2, 6, 2]
    scale_shape = [2]
    grad_val = np.random.random_sample(x_shape).astype(np.float32)
    x_val = np.random.random_sample(x_shape).astype(np.float32)
    scale_val = np.random.random_sample(scale_shape).astype(np.float32)
    mean_val = np.random.random_sample(scale_shape).astype(np.float32)
    var_val = np.random.random_sample(scale_shape).astype(np.float32)
    epsilon = 0.001

    with self.test_session() as sess, self.test_scope():
      grad = array_ops.placeholder(np.float32, shape=x_shape, name="grad")
      x = array_ops.placeholder(np.float32, shape=x_shape, name="x")
      mean = array_ops.placeholder(np.float32, shape=scale_shape, name="mean")
      var = array_ops.placeholder(np.float32, shape=scale_shape, name="var")
      scale = array_ops.placeholder(np.float32, shape=scale_shape, name="scale")
      grad_x, grad_scale, grad_offset, _, _ = gen_nn_ops.fused_batch_norm_grad(
          grad, x, scale, mean, var, data_format="NHWC")
      grad_x_val, grad_scale_val, grad_offset_val = sess.run(
          [grad_x, grad_scale, grad_offset], {
              grad: grad_val,
              x: x_val,
              mean: mean_val,
              var: var_val,
              scale: scale_val
          })

      grad_x_ref, grad_scale_ref, grad_offset_ref = self._reference_grad(
          x_val, grad_val, scale_val, mean_val, var_val, epsilon, "NHWC")

      self.assertAllClose(grad_x_val, grad_x_ref, atol=1e-2)
      self.assertAllClose(grad_scale_val, grad_scale_ref, atol=1e-2)
      self.assertAllClose(grad_offset_val, grad_offset_ref, atol=1e-3)

if __name__ == "__main__":
  test.main()


text:
import scala.reflect.macros.whitebox.Context
import scala.language.experimental.macros
import scala.annotation.StaticAnnotation

object doublerMacro {
  def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
    import c.universe._
    val result = {
      def double[T <: Name](name: T): T = {
        val sdoubled = name.toString + name.toString
        val doubled  = if (name.isTermName) TermName(sdoubled) else TypeName(sdoubled)
        doubled.asInstanceOf[T]
      }
      annottees.map(_.tree).toList match {
        case ClassDef(mods, name, tparams, impl) :: rest =>
          ClassDef(mods, double(name), tparams, impl) :: rest
        case ModuleDef(mods, name, impl) :: rest => ModuleDef(mods, double(name), impl) :: rest
        case DefDef(mods, name, tparams, vparamss, tpt, rhs) :: rest =>
          DefDef(mods, double(name), tparams, vparamss, tpt, rhs) :: rest
        case TypeDef(mods, name, tparams, rhs) :: rest =>
          TypeDef(mods, double(name), tparams, rhs) :: rest
        case ValDef(mods, name, tpt, rhs) :: rest => ValDef(mods, double(name), tpt, rhs) :: rest
      }
    }
    c.Expr[Any](Block(result, Literal(Constant(()))))
  }
}

class doubler extends StaticAnnotation {
  def macroTransform(annottees: Any*): Any = macro doublerMacro.impl
}

package pkg {
  class doubler extends StaticAnnotation {
    def macroTransform(annottees: Any*): Any = macro doublerMacro.impl
  }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Lehrbuch die Niederen Kryptogamen (Stuttgart) 256, 257, 263 (1892)

#### Original name
Eupenicillium F. Ludw.

### Remarks
null