text:
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis.select;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNull;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.AggregatingAttributeMapper;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.testutil.TestConstants;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Unit tests for {@link AggregatingAttributeMapper}.
 */
@RunWith(JUnit4.class)
public class AggregatingAttributeMapperTest extends AbstractAttributeMapperTest {

  @Before
  public final void createMapper() throws Exception {
    // Run AbstractAttributeMapper tests through an AggregatingAttributeMapper.
    mapper = AggregatingAttributeMapper.of(rule);
  }

  /**
   * Tests that {@link AggregatingAttributeMapper#visitAttribute} returns an
   * attribute's sole value when declared directly (i.e. not as a configurable dict).
   */
  @Test
  public void testGetPossibleValuesDirectAttribute() throws Exception {
    Rule rule = createRule("a", "myrule",
        "sh_binary(name = 'myrule',",
        "          srcs = ['a.sh'])");
    assertThat(AggregatingAttributeMapper.of(rule).visitAttribute("srcs", BuildType.LABEL_LIST))
        .containsExactlyElementsIn(ImmutableList.of(ImmutableList.of(Label.create("@//a", "a.sh"))));
  }

  /**
   * Tests that {@link AggregatingAttributeMapper#visitAttribute} returns
   * every possible value that a configurable attribute can resolve to.
   */
  @Test
  public void testGetPossibleValuesConfigurableAttribute() throws Exception {
    Rule rule = createRule("a", "myrule",
        "sh_binary(name = 'myrule',",
        "          srcs = select({",
        "              '//conditions:a': ['a.sh'],",
        "              '//conditions:b': ['b.sh'],",
        "              '" + BuildType.Selector.DEFAULT_CONDITION_KEY + "': ['default.sh'],",
        "          }))");
    assertThat(AggregatingAttributeMapper.of(rule).visitAttribute("srcs", BuildType.LABEL_LIST))
        .containsExactlyElementsIn(
            ImmutableList.of(
                ImmutableList.of(Label.create("@//a", "a.sh")),
                ImmutableList.of(Label.create("@//a", "b.sh")),
                ImmutableList.of(Label.create("@//a", "default.sh"))));
  }

  @Test
  public void testGetPossibleValuesWithConcatenatedSelects() throws Exception {
    Rule rule = createRule("a", "myrule",
        "sh_binary(name = 'myrule',",
        "          srcs = select({",
        "                  '//conditions:a1': ['a1.sh'],",
        "                  '//conditions:b1': ['b1.sh']})",
        "              + select({",
        "                  '//conditions:a2': ['a2.sh'],",
        "                  '//conditions:b2': ['b2.sh']})",
        "          )");
    assertThat(AggregatingAttributeMapper.of(rule).visitAttribute("srcs", BuildType.LABEL_LIST))
        .containsExactlyElementsIn(
            ImmutableList.of(
                ImmutableList.of(Label.create("@//a", "a1.sh"), Label.create("@//a", "a2.sh")),
                ImmutableList.of(Label.create("@//a", "a1.sh"), Label.create("@//a", "b2.sh")),
                ImmutableList.of(Label.create("@//a", "b1.sh"), Label.create("@//a", "a2.sh")),
                ImmutableList.of(Label.create("@//a", "b1.sh"), Label.create("@//a", "b2.sh"))));
  }

  /**
   * Given a large number of selects, we expect better than the naive
   * exponential performance from evaluating select1 x select2 x select3 x ...
   */
  @Test
  public void testGetPossibleValuesWithManySelects() throws Exception {
    String pattern = " + select({'//conditions:a1': '%c', '//conditions:a2': '%s'})";
    StringBuilder ruleDef = new StringBuilder();
    ruleDef.append("genrule(name = 'gen', srcs = [], outs = ['gen.out'], cmd = ''");
    for (char c : "abcdefghijklmnopqrstuvwxyz".toCharArray()) {
      ruleDef.append(String.format(pattern, c, Character.toUpperCase(c)));
    }
    ruleDef.append(")");
    Rule rule = createRule("a", "gen", ruleDef.toString());
    // Naive evaluation would visit 2^26 cases and either overflow memory or timeout the test.
    assertThat(AggregatingAttributeMapper.of(rule).visitAttribute("cmd", Type.STRING))
        .containsExactly("abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
  }

  /**
   * Tests that, on rule visitation, {@link AggregatingAttributeMapper} visits *every* possible
   * value in a configurable attribute (including configuration key labels).
   */
  @Test
  public void testVisitationConfigurableAttribute() throws Exception {
    Rule rule = createRule("a", "myrule",
        "sh_binary(name = 'myrule',",
        "          srcs = select({",
        "              '//conditions:a': ['a.sh'],",
        "              '//conditions:b': ['b.sh'],",
        "              '" + BuildType.Selector.DEFAULT_CONDITION_KEY + "': ['default.sh'],",
        "          }))");

    VisitationRecorder recorder = new VisitationRecorder();
    AggregatingAttributeMapper.of(rule).visitLabels(recorder);
    assertThat(recorder.labelsVisited)
        .containsExactlyElementsIn(
            ImmutableList.of(
                "//a:a.sh", "//a:b.sh", "//a:default.sh", "//conditions:a", "//conditions:b"));
  }

  @Test
  public void testGetReachableLabels() throws Exception {
    Rule rule = createRule("x", "main",
        "cc_binary(",
        "    name = 'main',",
        "    srcs = select({",
        "        '//conditions:a': ['a.cc'],",
        "        '//conditions:b': ['b.cc']})",
        "    + ",
        "        ['always.cc']",
        "    + ",
        "         select({",
        "        '//conditions:c': ['c.cc'],",
        "        '//conditions:d': ['d.cc'],",
        "        '" + BuildType.Selector.DEFAULT_CONDITION_KEY + "': ['default.cc'],",
        "    }))");

    ImmutableList<Label> valueLabels = ImmutableList.of(
        Label.create("@//x", "a.cc"), Label.create("@//x", "b.cc"),
        Label.create("@//x", "always.cc"), Label.create("@//x", "c.cc"),
        Label.create("@//x", "d.cc"), Label.create("@//x", "default.cc"));
    ImmutableList<Label> keyLabels = ImmutableList.of(
        Label.create("@//conditions", "a"), Label.create("@//conditions", "b"),
        Label.create("@//conditions", "c"), Label.create("@//conditions", "d"));

    AggregatingAttributeMapper mapper = AggregatingAttributeMapper.of(rule);
    assertThat(mapper.getReachableLabels("srcs", true))
        .containsExactlyElementsIn(Iterables.concat(valueLabels, keyLabels));
    assertThat(mapper.getReachableLabels("srcs", false)).containsExactlyElementsIn(valueLabels);
  }

  @Test
  public void testDuplicateCheckOnNullValues() throws Exception {
    if (TestConstants.THIS_IS_BAZEL) {
      return;
    }
    Rule rule = createRule("x", "main",
        "java_binary(",
        "    name = 'main',",
        "    srcs = ['main.java'])");
    AggregatingAttributeMapper mapper = AggregatingAttributeMapper.of(rule);
    Attribute launcherAttribute = mapper.getAttributeDefinition("launcher");
    assertNull(mapper.get(launcherAttribute.getName(), launcherAttribute.getType()));
    assertThat(mapper.checkForDuplicateLabels(launcherAttribute))
        .containsExactlyElementsIn(ImmutableList.of());
  }
}


text:
// Copyright 2016 Twitter. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.twitter.heron.scheduler;

import java.util.logging.Logger;

import com.twitter.heron.api.generated.TopologyAPI;
import com.twitter.heron.proto.system.ExecutionEnvironment;
import com.twitter.heron.proto.system.PackingPlans;
import com.twitter.heron.scheduler.dryrun.SubmitDryRunResponse;
import com.twitter.heron.scheduler.utils.LauncherUtils;
import com.twitter.heron.scheduler.utils.Runtime;
import com.twitter.heron.spi.common.Config;
import com.twitter.heron.spi.common.Context;
import com.twitter.heron.spi.packing.PackingException;
import com.twitter.heron.spi.packing.PackingPlan;
import com.twitter.heron.spi.packing.PackingPlanProtoSerializer;
import com.twitter.heron.spi.scheduler.ILauncher;
import com.twitter.heron.spi.scheduler.LauncherException;
import com.twitter.heron.spi.statemgr.SchedulerStateManagerAdaptor;

/**
 * Runs Launcher and launch topology. Also Uploads launch state to state manager.
 */
public class LaunchRunner {
  private static final Logger LOG = Logger.getLogger(LaunchRunner.class.getName());

  private Config config;
  private Config runtime;

  private ILauncher launcher;

  public LaunchRunner(Config config, Config runtime) {

    this.config = config;
    this.runtime = runtime;
    this.launcher = Runtime.launcherClassInstance(runtime);
  }

  public ExecutionEnvironment.ExecutionState createExecutionState() {
    String releaseUsername = Context.buildUser(config);
    // TODO(mfu): Currently we leave release tag empty
    String releaseTag = "";
    String releaseVersion = Context.buildVersion(config);

    TopologyAPI.Topology topology = Runtime.topology(runtime);

    ExecutionEnvironment.ExecutionState.Builder builder =
        ExecutionEnvironment.ExecutionState.newBuilder();

    // set the topology name, id, submitting user and time
    builder.setTopologyName(topology.getName()).
        setTopologyId(topology.getId())
        .setSubmissionTime(System.currentTimeMillis() / 1000)
        .setSubmissionUser(Context.submitUser(config))
        .setCluster(Context.cluster(config))
        .setRole(Context.role(config))
        .setEnviron(Context.environ(config));

    // build the heron release state
    ExecutionEnvironment.HeronReleaseState.Builder releaseBuilder =
        ExecutionEnvironment.HeronReleaseState.newBuilder();

    releaseBuilder.setReleaseUsername(releaseUsername);
    releaseBuilder.setReleaseTag(releaseTag);
    releaseBuilder.setReleaseVersion(releaseVersion);

    builder.setReleaseState(releaseBuilder);
    if (builder.isInitialized()) {
      return builder.build();
    } else {
      throw new RuntimeException("Failed to create execution state");
    }
  }

  /**
   * Trim the topology definition for storing into state manager.
   * This is because the user generated spouts and bolts
   * might be huge.
   *
   * @return trimmed topology
   */
  public TopologyAPI.Topology trimTopology(TopologyAPI.Topology topology) {

    // create a copy of the topology physical plan
    TopologyAPI.Topology.Builder builder = TopologyAPI.Topology.newBuilder().mergeFrom(topology);

    // clear the state of user spout java objects - which can be potentially huge
    for (TopologyAPI.Spout.Builder spout : builder.getSpoutsBuilderList()) {
      spout.getCompBuilder().clearSerializedObject();
    }

    // clear the state of user spout java objects - which can be potentially huge
    for (TopologyAPI.Bolt.Builder bolt : builder.getBoltsBuilderList()) {
      bolt.getCompBuilder().clearSerializedObject();
    }

    return builder.build();
  }

  private PackingPlans.PackingPlan createPackingPlan(PackingPlan packingPlan) {
    PackingPlanProtoSerializer serializer = new PackingPlanProtoSerializer();
    return serializer.toProto(packingPlan);
  }

  /**
   * Call launcher to launch topology
   *
   * @throws LauncherException
   * @throws PackingException
   * @throws SubmitDryRunResponse
   */
  public void call() throws LauncherException, PackingException, SubmitDryRunResponse {
    SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime);
    TopologyAPI.Topology topology = Runtime.topology(runtime);
    String topologyName = Context.topologyName(config);

    PackingPlan packedPlan = LauncherUtils.getInstance().createPackingPlan(config, runtime);

    if (Context.dryRun(config)) {
      throw new SubmitDryRunResponse(topology, config, packedPlan);
    }

    // initialize the launcher
    launcher.initialize(config, runtime);

    // Set topology def first since we determine whether a topology is running
    // by checking the existence of topology def
    // store the trimmed topology definition into the state manager
    // TODO(rli): log-and-false anti-pattern is too nested on this path. will not refactor
    Boolean result = statemgr.setTopology(trimTopology(topology), topologyName);
    if (result == null || !result) {
      throw new LauncherException(String.format(
          "Failed to set topology definition for topology '%s'", topologyName));
    }

    result = statemgr.setPackingPlan(createPackingPlan(packedPlan), topologyName);
    if (result == null || !result) {
      statemgr.deleteTopology(topologyName);
      throw new LauncherException(String.format(
          "Failed to set packing plan for topology '%s'", topologyName));
    }

    // store the execution state into the state manager
    ExecutionEnvironment.ExecutionState executionState = createExecutionState();

    result = statemgr.setExecutionState(executionState, topologyName);
    if (result == null || !result) {
      statemgr.deletePackingPlan(topologyName);
      statemgr.deleteTopology(topologyName);
      throw new LauncherException(String.format(
          "Failed to set execution state for topology '%s'", topologyName));
    }

    // launch the topology, clear the state if it fails
    if (!launcher.launch(packedPlan)) {
      statemgr.deleteExecutionState(topologyName);
      statemgr.deletePackingPlan(topologyName);
      statemgr.deleteTopology(topologyName);
      throw new LauncherException(String.format(
          "Failed to launch topology '%s'", topologyName));
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
#region Copyright

// <copyright file="ChannelBarViewModelCommon.cs">
//     Copyright (c) 2013-2015, Justin Kadrovach, All rights reserved.
//
//     This source is subject to the Simplified BSD License.
//     Please see the License.txt file for more information.
//     All other rights reserved.
//
//     THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
//     KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//     IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//     PARTICULAR PURPOSE.
// </copyright>

#endregion

namespace slimCat.ViewModels
{
    #region Usings

    using Models;
    using Services;

    #endregion

    /// <summary>
    ///     Contains some things the channelbar viewmodels have in common
    /// </summary>
    public class ChannelbarViewModelCommon : ViewModelBase
    {
        #region Constructors and Destructors

        protected ChannelbarViewModelCommon(IChatState chatState)
            : base(chatState)
        {
            ChatModel.SelectedChannelChanged += (s, e) => OnPropertyChanged("HasUsers");
        }

        #endregion

        #region Fields

        #endregion

        #region Public Properties

        public bool HasUsers
        {
            get
            {
                if (ChatModel.CurrentChannel == null)
                    return false;

                return (ChatModel.CurrentChannel.Type != ChannelType.PrivateMessage)
                       && ChatModel.CurrentChannel.Type != ChannelType.Utility;
            }
        }

        public GenericSearchSettingsModel SearchSettings { get; } = new GenericSearchSettingsModel();

        #endregion
    }
}


text:
using namespace std;
using namespace gdg::srl;

namespace {

string build_request(gdg::srl::string_view_t host, gdg::srl::string_view_t resource) {
    return "GET " + string(resource) + " HTTP/1.1\r\nHost: " + string(host)
        + "\r\nConnection: close\r\n\r\n";
}

TEST_CASE("build request") {
    CHECK(build_request("www.vandal.net", "/") ==
          "GET / HTTP/1.1\r\nHost: www.vandal.net\r\nConnection: close\r\n\r\n");

    CHECK(build_request("www.publico.es", "/") ==
          "GET / HTTP/1.1\r\nHost: www.publico.es\r\nConnection: close\r\n\r\n");

    CHECK(build_request("www.boost.org", "/LICENSE_1_0.txt") ==
          "GET /LICENSE_1_0.txt HTTP/1.1\r\nHost: www.boost.org\r\nConnection: close\r\n\r\n");

}

vector<gdg::srl::byte_t> async_read_fixed_body(gdg::srl::net::ip::tcp::socket & s,
                                               gdg::srl::net::streambuf & buf,
                                               size_t sizeInBytes,
                                               gdg::srl::net::yield_context yield) {
    boost::system::error_code ec{};

    auto bytesRead =
        net::async_read
        (s, buf,
         net::transfer_exactly(sizeInBytes),
         yield[ec]);
    if (ec && ec != net::error::eof)
        throw boost::system::system_error{ec};

    istream is(&buf);
    is >> noskipws;
    vector<byte_t> result(sizeInBytes);

    std::size_t i = 0;
    copy_n(istream_iterator<byte_t>{is},
           sizeInBytes, result.begin());

    return result;
}

vector<byte_t> async_read_chunked_body(net::ip::tcp::socket & s,
                                       net::streambuf & buf,
                                       net::yield_context yield) {
    size_t bytesRead{};
    size_t chunkSize{};
    istream is(&buf);
    is >> noskipws;
    boost::system::error_code ec{};
    vector<byte_t> result;
    while (true) {
        //Read the chunk size into the buffer
        bytesRead =
            net::async_read_until(s, buf, "\r\n",
                                  yield[ec]);

        if (ec && ec != net::error::eof)
            throw boost::system::system_error{ec};
        string chunkSizeStr;

        //Put chunk size in a string
        getline(is, chunkSizeStr);

        //Convert hex chunksize into a decimal number
        chunkSize = stoi(chunkSizeStr,
                         nullptr, 16);
        if (!chunkSize) {
            bytesRead = net::async_read
                (s, buf,
                 net::transfer_exactly(2),
                 yield[ec]);
            if (ec && ec != net::error::eof)
                throw boost::system::system_error{ec};
            break;
        }

        auto chunkBytesToRead = chunkSize;
        //read exactly chunkSize
        bytesRead = net::async_read
            (s, buf,
             net::transfer_exactly(chunkBytesToRead),
             yield[ec]);
        if (ec && ec != net::error::eof)
            throw boost::system::system_error{ec};

        copy_n(istream_iterator<char>{is},
               chunkBytesToRead,
               back_inserter(result));

        //Read trailing \r\n after the data
        bytesRead = net::async_read
            (s, buf,
             net::transfer_exactly(2),
             yield[ec]);
        if (ec && ec != net::error::eof)
            throw boost::system::system_error{ec};

        //Discard the \r\n after the data
        is.ignore(2);
    }
    return result;
}

vector<byte_t> async_read_body(net::ip::tcp::socket & s,
                               net::streambuf & buf,
                               bool readInChunks,
                               net::yield_context yield,
                               int contentLength = 0) {
    vector<byte_t> result;
    if (!readInChunks) {
        result = async_read_fixed_body(s, buf, contentLength, yield);
    }
    else {
        result = async_read_chunked_body(s, buf, yield);
    }
    return result;
}

unordered_map<string, string> get_headers(istream & input) {
    static const regex spaces("\\s*");
    string line;
    unordered_map<string, string> headers;

    while (getline(input, line) && !regex_match(line, spaces)) {
        auto const separatorIt = find(line.begin(), line.end(), ':');
        auto fieldName = string(line.begin(), separatorIt);
        transform(fieldName.begin(), fieldName.end(), fieldName.begin(), &::tolower);
        headers[fieldName] =
            string(find_if(next(separatorIt),
                           line.end(),
                           [](auto c) {
                               return !isspace(c); }),
                   line.end());
    }
    return headers;
}

TEST_CASE("get headers") {
    string const headersStr =
        R"--(Date: Mon, 27 Jan 2017 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT
Content-Length: 88
Content-Type: text/html
Connection: Closed)--";

    istringstream headersStream(headersStr);
    auto headers = get_headers(headersStream);

    CHECK(headers.size() == 6);
    auto it = headers.find("content-length");
    CHECK(it->second == "88");

    auto it2 = headers.find("date");
    CHECK(it2->second == "Mon, 27 Jan 2017 12:28:53 GMT");
}

} //anon namespace

namespace gdg {

namespace srl {

net::io_service & get_default_loop() {
    static net::io_service & svc =
        []() -> net::io_service & {
        static auto io = std::make_unique<net::io_service>();
        static net::io_service::work work{*io};
        shared_ptr<future<void>> f = make_shared<future<void>>();

        *f = std::async(std::launch::async,
                        [f] {
                            io->run();
                        });
        return *io;
    }();
    return svc;
}

future<pair<int, vector<byte_t>>> async_http_get(string_view_t host,
                                                 string_view_t resource,
                                                 chrono::steady_clock::duration timeOut) {
    return async_http_get(get_default_loop(),
                          host, resource, timeOut);
}

future<pair<int, vector<byte_t>>> async_http_get(net::io_service & io,
                                                 string_view_t host,
                                                 string_view_t resource,
                                                 chrono::steady_clock::duration timeOut) {
    promise<pair<int, vector<byte_t>>> result_promise;
    auto result = result_promise.get_future();
    net::spawn
        (io,
         [&io, hoststr=string(host), timeOut = timeOut,
          result_promise = move(result_promise), host, resource]
         (net::yield_context yield) mutable {
            ip::tcp::socket socket(io);

            try {
                atomic<bool> timeoutReached{false};
                net::steady_timer timer(io);
                timer.expires_from_now(timeOut);
                timer.async_wait([&timeoutReached](auto ec) {
                        if (ec != net::error::operation_aborted) {
                            timeoutReached = true;
                        }
                    });
                ip::tcp::resolver::query q(hoststr, "http");
                ip::tcp::resolver resolver(io);
                net::async_connect(socket, resolver.async_resolve(q, yield), yield);
                string const request = build_request(host, resource);

                net::async_write(socket, net::buffer(request), yield);
                net::streambuf buf;

                net::async_read_until(socket, buf, "\r\n\r\n",
                                      yield);

                if (timeoutReached) {
                    result_promise.set_exception(make_exception_ptr(timeout_exception{}));
                    return;
                }
                istream response(&buf);
                string httpVersion, retCode, retString;
                response >> httpVersion >> retCode;
                getline(response, retString);
                auto retCodeInt = std::stoi(retCode);
                if (retCodeInt != 200)
                    throw bad_request_exception(retCodeInt);
                string line;
                getline(response, line);

                auto const headers = get_headers(response);
                bool const readInChunks = [&headers]() {
                    if (headers.find("transfer-encoding") != headers.end())
                        return true;
                    else
                        return false;
                }();

                if (readInChunks) {
                    if (timeoutReached) {
                        result_promise.set_exception(make_exception_ptr(timeout_exception{}));
                        return;
                    }
                    result_promise.set_value({200, async_read_body(socket, buf, readInChunks, yield)});

                }
                else {
                    auto itContentLength = headers.find("content-length");
                    if (itContentLength == headers.end())
                        throw runtime_error
                            ("Cannot parse HTTP response -> "
                             "not supported: missing both content-length and transfer-encoding headers");
                    if (stoi(itContentLength->second) == 0) {
                        result_promise.set_value({200, {}});
                    }
                    else {
                        if (timeoutReached) {
                            result_promise.set_exception(make_exception_ptr(timeout_exception{}));
                            return;
                        }
                        result_promise.set_value
                            ({200,async_read_body(socket, buf, readInChunks, yield,
                                                  std::stoi(itContentLength->second))});
                    }
                }
                timer.cancel();
                if (timeoutReached)
                    result_promise.set_exception(make_exception_ptr(timeout_exception{}));
            }
            catch (...) {
                socket.close();
                result_promise.set_exception(current_exception());
            }
        });
    return result;
}

TEST_CASE("async http get without timeout") {
    net::io_service svc;
    net::io_service::work wk{svc};
    thread t([&svc] { svc.run(); });
    //CHECK_NOTHROW((async_http_get(svc, "http://fossilinsects.myspecies.info", "/", 8s).get()));
    async_http_get(svc, "http://fossilinsects.myspecies.info", "/", 8s).get();
    svc.stop();
    t.join();
}

TEST_CASE("async http get timeouts") {
    net::io_service svc;
    net::io_service::work wk{svc};
    thread t([&svc] { svc.run(); });
    CHECK_THROWS_AS(async_http_get(svc,
                                   "www.boost.org",
                                   "/LICENSE_1_0.txt",
                                   0ms).get(),
                    timeout_exception);
    svc.stop();
    t.join();
}

} //namespace srl

} //namespace gdg


text:
chain
=====

_bioinformatic pipelines with minimal effort_

## Warning

This project is pre-alpha. Please don't use the code for anything serious or post issues until we reach alpha.

## Introduction

**chain** is a tool for rapid development, exploration, and use of bioinformatic pipelines. **chain** lets you create and run new pipelines in seconds. Because you can store, share and modify chains, pipeline optimisation becomes easy and reproducible analysis is trivial. Programs can be added with a small amount of code. **chain** comes with several commonly-used bioinformatics tools built in.

### Example workflow

Let's see how it works with some high-throughput RNA sequencing examples.

Designing a reads-to-expression pipeline for de-novo transcriptomics, using default settings, can be as simple as:

```
chain --name denovotrans \
 --description "a gold-standard de-novo transcriptomics pipeline" \
 --define trimmomatic:khmer:velvetoases:gapfiller:cap3:chiminus:transrate:express`
```

Pipeline definitions are stored in plaintext .chain files, so you can share them, import them, or define them directly in the file. The same pipeline would be defined in plaintext as:

```
name = denovotrans
description = "a gold-standard de-novo transcriptomics pipeline, ideal for first pass analysis of a new species"
programs = trimmomatic:khmer:velvetoases:gapfiller:cap3:chiminus:tada:express
```

Running the chain you just designed is then trivial:

`chain --run denovotrans --left l.fastq --right r.fastq`

You can store as many pipelines as you like. Let's save a very simple reference-based RNA-Seq pipeline in which we trim, map and quantify reads:

`chain --name rnaseq --define trimmomatic:express`

Running the RNA-Seq pipeline:

`chain --run rnaseq --left l.fastq --right r.fastq --reference rice_transcriptome.fa`

**chain** knows what inputs each program requires, and can figure out whether the correct ones will be generated by the pipeline. If there's likely to be a problem, you find out right away.

```
> chain --run rnaseq --left l.fastq --right r.fastq
error: the eXpress step requires a reference file, and none of the preceding steps will generate one.
please re-run the chain specifying a reference with the --reference option
```

To review the chains you've stored:

`chain --list`

To get a detailed protocol for a particular pipeline:

`chain --protocol denovotrans`

Maybe you want to vary the settings of one program in the pipeline. First you list the settings available for that program:

`chain --detail velvetoases`

...then create a child pipeline with some settings changed:

`chain --name denovotrans2 --inherit denovotrans --options velvetoases:k=21-71,step=10,mergek=27`


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.ui.laf.darcula;

import com.intellij.openapi.ui.GraphicsConfig;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.JBColor;
import com.intellij.ui.paint.LinePainter2D;
import com.intellij.util.ui.JBValue;

import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicTableHeaderUI;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.util.Enumeration;

/**
 * @author Konstantin Bulenkov
 */
public class DarculaTableHeaderUI extends BasicTableHeaderUI {

  @SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"})
  public static ComponentUI createUI(JComponent c) {
    return new DarculaTableHeaderUI();
  }

  @Override
  public void paint(Graphics g2, JComponent c) {
    final Graphics2D g = (Graphics2D)g2;
    final GraphicsConfig config = new GraphicsConfig(g);
    final Color bg = c.getBackground();
    g.setPaint(bg);

    TableColumnModel model = ((JTableHeader)c).getColumnModel();

    final int h = c.getHeight();
    final int w = model.getTotalColumnWidth();
    g.fillRect(0, 0, w, h);
    JBColor bottomSeparatorColor = JBColor.namedColor("TableHeader.bottomSeparatorColor", ColorUtil.shift(bg, 0.75));
    g.setPaint(bottomSeparatorColor);
    LinePainter2D.paint((Graphics2D)g, 0, h - 1, w, h - 1);

    final Enumeration<TableColumn> columns = model.getColumns();

    final Color lineColor = JBColor.namedColor("TableHeader.separatorColor", ColorUtil.shift(bg, 0.7));
    int offset = 0;
    while (columns.hasMoreElements()) {
      final TableColumn column = columns.nextElement();
      if (columns.hasMoreElements() && column.getWidth() > 0) {
        offset += column.getWidth();
        g.setColor(lineColor);
        LinePainter2D.paint((Graphics2D)g, offset - 1, 1, offset - 1, h - 3);
      }
    }

    config.restore();

    super.paint(g, c);
  }

  @Override
  public Dimension getPreferredSize(JComponent c) {
    Dimension size = super.getPreferredSize(c);
    if (size.height == 0) return size;
    JBValue.UIInteger height = new JBValue.UIInteger("TableHeader.height", 25);
    return new Dimension(size.width, Math.max(height.get(), size.height));
  }
}


text:
package nl.rivm.cib.epidemes.geodb.voorz;

/**
 * {@link NursingHomeDao}
 *
 * @version $Id$
 * @author Rick van Krevelen
 */
public class NursingHomeDao
{

}


text:
using System.Runtime.InteropServices;

namespace NuGet.VisualStudio
{
    [ComImport]
    [Guid("65E435C1-6970-4BBF-8842-5DBCB0707711")]
    public interface IVsPackageInstallerEvents
    {
        event VsPackageEventHandler PackageInstalling;
        event VsPackageEventHandler PackageInstalled;
        event VsPackageEventHandler PackageUninstalling;
        event VsPackageEventHandler PackageUninstalled;
        event VsPackageEventHandler PackageReferenceAdded;
        event VsPackageEventHandler PackageReferenceRemoved;
    }
}


text:
module Guacamole
  # Build a query for ArangoDB
  class Query
    include Enumerable
    # Connection to the database
    #
    # @return [Ashikawa::Core::Collection]
    attr_reader :connection

    # The mapper class
    #
    # @return [Class]
    attr_reader :mapper

    # The example to search for
    #
    # @return [Hash] the example
    attr_accessor :example

    # Currently set options
    #
    # @return [Hash]
    # @api private
    attr_accessor :options

    # Create a new Query
    #
    # @param [Ashikawa::Core::Collection] connection The collection to use to talk to the database
    # @param [Class] mapper the class of the mapper to use
    def initialize(connection, mapper)
      @connection = connection
      @mapper = mapper
      @options = {}
    end

    # Iterate over the result of the query
    #
    # This will execute the query you have build
    def each(&block)
      return to_enum(__callee__) unless block_given?

      perfom_query ->(document) { block.call mapper.document_to_model(document) }, &block
    end

    # Limit the results of the query
    #
    # @param [Fixnum] limit
    # @return [self]
    def limit(limit)
      options[:limit] = limit
      self
    end

    # The number of results to skip
    #
    # @param [Fixnum] skip
    # @return [self]
    def skip(skip)
      options[:skip] = skip
      self
    end

    # Is this {Query} equal to another {Query}
    #
    # Two {Query} objects are equal if their examples are equal
    #
    # @param [Query] other The query to compare to
    def ==(other)
      other.instance_of?(self.class) &&
        example == other.example
    end
    alias_method :eql?, :==

    private

    # Performs the query against the database connection.
    #
    # This can be changed by subclasses to implement other types
    # of queries, such as AQL queries.
    #
    # @param [Lambda] iterator To be called on each document returned from
    #                 the database
    def perfom_query(iterator, &block)
      if example
        connection.by_example(example, options).each(&iterator)
      else
        connection.all(options).each(&iterator)
      end
    end
  end
end


text:
from __future__ import absolute_import
from __future__ import print_function

import mock
from typing import Any, Union, Mapping, Callable

from zerver.lib.actions import do_create_user
from zerver.lib.test_classes import ZulipTestCase
from zerver.models import (
    get_realm_by_email_domain,
    UserProfile,
    Recipient,
)

BOT_TYPE_TO_QUEUE_NAME = {
    UserProfile.OUTGOING_WEBHOOK_BOT: 'outgoing_webhooks',
    UserProfile.EMBEDDED_BOT: 'embedded_bots',
}

class TestServiceBotEventTriggers(ZulipTestCase):

    def setUp(self):
        # type: () -> None
        self.user_profile = self.example_user("othello")
        self.bot_profile = do_create_user(email="foo-bot@zulip.com",
                                          password="test",
                                          realm=get_realm_by_email_domain("zulip.com"),
                                          full_name="FooBot",
                                          short_name="foo-bot",
                                          bot_type=UserProfile.OUTGOING_WEBHOOK_BOT,
                                          bot_owner=self.user_profile)
        self.second_bot_profile = do_create_user(email="bar-bot@zulip.com",
                                                 password="test",
                                                 realm=get_realm_by_email_domain("zulip.com"),
                                                 full_name="BarBot",
                                                 short_name="bar-bot",
                                                 bot_type=UserProfile.OUTGOING_WEBHOOK_BOT,
                                                 bot_owner=self.user_profile)

        # TODO: In future versions this won't be required
        self.subscribe_to_stream(self.bot_profile.email, 'Denmark')

    @mock.patch('zerver.lib.actions.queue_json_publish')
    def test_trigger_on_stream_mention_from_user(self, mock_queue_json_publish):
        # type: (mock.Mock) -> None
        for bot_type, expected_queue_name in BOT_TYPE_TO_QUEUE_NAME.items():
            self.bot_profile.bot_type = bot_type
            self.bot_profile.save()

            content = u'@**FooBot** foo bar!!!'
            recipient = 'Denmark'
            trigger = 'mention'
            message_type = Recipient._type_names[Recipient.STREAM]

            def check_values_passed(queue_name, trigger_event, x):
                # type: (Any, Union[Mapping[Any, Any], Any], Callable[[Any], None]) -> None
                self.assertEqual(queue_name, expected_queue_name)
                self.assertEqual(trigger_event["failed_tries"], 0)
                self.assertEqual(trigger_event["message"]["content"], content)
                self.assertEqual(trigger_event["message"]["display_recipient"], recipient)
                self.assertEqual(trigger_event["message"]["sender_email"], self.user_profile.email)
                self.assertEqual(trigger_event["message"]["type"], message_type)
                self.assertEqual(trigger_event['trigger'], trigger)
                self.assertEqual(trigger_event['user_profile_id'], self.bot_profile.id)
            mock_queue_json_publish.side_effect = check_values_passed

            self.send_message(
                self.user_profile.email,
                'Denmark',
                Recipient.STREAM,
                content)
            self.assertTrue(mock_queue_json_publish.called)

    @mock.patch('zerver.lib.actions.queue_json_publish')
    def test_no_trigger_on_stream_message_without_mention(self, mock_queue_json_publish):
        # type: (mock.Mock) -> None
        sender_email = self.user_profile.email
        recipients = "Denmark"
        message_type = Recipient.STREAM
        self.send_message(sender_email, recipients, message_type)
        self.assertFalse(mock_queue_json_publish.called)

    @mock.patch('zerver.lib.actions.queue_json_publish')
    def test_no_trigger_on_stream_mention_from_bot(self, mock_queue_json_publish):
        # type: (mock.Mock) -> None
        for bot_type in BOT_TYPE_TO_QUEUE_NAME:
            self.bot_profile.bot_type = bot_type
            self.bot_profile.save()

            self.send_message(
                self.second_bot_profile.email,
                'Denmark',
                Recipient.STREAM,
                u'@**FooBot** foo bar!!!')
            self.assertFalse(mock_queue_json_publish.called)

    @mock.patch('zerver.lib.actions.queue_json_publish')
    def test_trigger_on_personal_message_from_user(self, mock_queue_json_publish):
        # type: (mock.Mock) -> None
        for bot_type, expected_queue_name in BOT_TYPE_TO_QUEUE_NAME.items():
            self.bot_profile.bot_type = bot_type
            self.bot_profile.save()

            sender_email = self.user_profile.email
            recipient_email = self.bot_profile.email
            message_type = Recipient.PERSONAL

            def check_values_passed(queue_name, trigger_event, x):
                # type: (Any, Union[Mapping[Any, Any], Any], Callable[[Any], None]) -> None
                self.assertEqual(queue_name, expected_queue_name)
                self.assertEqual(trigger_event["user_profile_id"], self.bot_profile.id)
                self.assertEqual(trigger_event["trigger"], "private_message")
                self.assertEqual(trigger_event["failed_tries"], 0)
                self.assertEqual(trigger_event["message"]["sender_email"], sender_email)
                display_recipients = [
                    trigger_event["message"]["display_recipient"][0]["email"],
                    trigger_event["message"]["display_recipient"][1]["email"],
                ]
                self.assertTrue(sender_email in display_recipients)
                self.assertTrue(recipient_email in display_recipients)
            mock_queue_json_publish.side_effect = check_values_passed

            self.send_message(sender_email, recipient_email, message_type, subject='', content='test')
            self.assertTrue(mock_queue_json_publish.called)

    @mock.patch('zerver.lib.actions.queue_json_publish')
    def test_no_trigger_on_personal_message_from_bot(self, mock_queue_json_publish):
        # type: (mock.Mock) -> None
        for bot_type in BOT_TYPE_TO_QUEUE_NAME:
            self.bot_profile.bot_type = bot_type
            self.bot_profile.save()

            sender_email = self.second_bot_profile.email
            recipient_email = self.bot_profile.email
            message_type = Recipient.PERSONAL
            self.send_message(sender_email, recipient_email, message_type)
            self.assertFalse(mock_queue_json_publish.called)

    @mock.patch('zerver.lib.actions.queue_json_publish')
    def test_trigger_on_huddle_message_from_user(self, mock_queue_json_publish):
        # type: (mock.Mock) -> None
        for bot_type, expected_queue_name in BOT_TYPE_TO_QUEUE_NAME.items():
            self.bot_profile.bot_type = bot_type
            self.bot_profile.save()

            self.second_bot_profile.bot_type = bot_type
            self.second_bot_profile.save()

            sender_email = self.user_profile.email
            recipient_emails = [self.bot_profile.email, self.second_bot_profile.email]
            message_type = Recipient.HUDDLE
            profile_ids = [self.bot_profile.id, self.second_bot_profile.id]

            def check_values_passed(queue_name, trigger_event, x):
                # type: (Any, Union[Mapping[Any, Any], Any], Callable[[Any], None]) -> None
                self.assertEqual(queue_name, expected_queue_name)
                self.assertIn(trigger_event["user_profile_id"], profile_ids)
                profile_ids.remove(trigger_event["user_profile_id"])
                self.assertEqual(trigger_event["trigger"], "private_message")
                self.assertEqual(trigger_event["failed_tries"], 0)
                self.assertEqual(trigger_event["message"]["sender_email"], sender_email)
                self.assertEqual(trigger_event["message"]["type"], u'private')
            mock_queue_json_publish.side_effect = check_values_passed

            self.send_message(sender_email, recipient_emails, message_type, subject='', content='test')
            self.assertEqual(mock_queue_json_publish.call_count, 2)
            mock_queue_json_publish.reset_mock()

    @mock.patch('zerver.lib.actions.queue_json_publish')
    def test_no_trigger_on_huddle_message_from_bot(self, mock_queue_json_publish):
        # type: (mock.Mock) -> None
        for bot_type in BOT_TYPE_TO_QUEUE_NAME:
            self.bot_profile.bot_type = bot_type
            self.bot_profile.save()

            sender_email = self.second_bot_profile.email
            recipient_emails = [self.user_profile.email, self.bot_profile.email]
            message_type = Recipient.HUDDLE
            self.send_message(sender_email, recipient_emails, message_type)
            self.assertFalse(mock_queue_json_publish.called)


text:
mainApp.controller('HomeCtrl', ['$scope','$http', 'todoFactory',function($scope, $http, todoFactory){
	$scope.WelcomeMessage = "Welcome!";
	$scope.smallinfo = "From Angular (HOME) Controller";
	var todos = todoFactory.getTodos();
	todos.success(function handleSuccess(data,status){
		console.log(data);
	});
}]);
/*

*/


text:
"""
The ``@mech`` connector reads the current mech status and generates an inventory
for any running VMs.

.. code:: python

    # Run on all hosts
    pyinfra @mech ...

    # Run on a specific VM
    pyinfra @mech/my-vm-name ...

    # Run on multiple named VMs
    pyinfra @mech/my-vm-name,@mech/another-vm-name ...
"""

import json
from os import path
from queue import Queue
from threading import Thread

from pyinfra import local, logger
from pyinfra.api.exceptions import InventoryError
from pyinfra.api.util import memoize
from pyinfra.progress import progress_spinner

def _get_mech_ssh_config(queue, progress, target):
    logger.debug("Loading SSH config for %s", target)

    # Note: We have to work-around the fact that "mech ssh-config somehost"
    # does not return the correct "Host" value. When "mech" fixes this
    # issue we can simply this code.
    lines = local.shell(
        "mech ssh-config {0}".format(target),
        splitlines=True,
    )

    newlines = []
    for line in lines:
        if line.startswith("Host "):
            newlines.append("Host " + target)
        else:
            newlines.append(line)

    queue.put(newlines)

    progress(target)

@memoize
def get_mech_config(limit=None):
    logger.info("Getting Mech config...")

    if limit and not isinstance(limit, (list, tuple)):
        limit = [limit]

    # Note: There is no "--machine-readable" option to 'mech status'
    with progress_spinner({"mech ls"}) as progress:
        output = local.shell(
            "mech ls",
            splitlines=True,
        )
        progress("mech ls")

    targets = []

    for line in output:

        address = ""

        data = line.split()
        target = data[0]

        if len(data) == 5:
            address = data[1]

        # Skip anything not in the limit
        if limit is not None and target not in limit:
            continue

        # For each vm that has an address, fetch it's SSH config in a thread
        if address != "" and address[0].isdigit():
            targets.append(target)

    threads = []
    config_queue = Queue()

    with progress_spinner(targets) as progress:
        for target in targets:
            thread = Thread(
                target=_get_mech_ssh_config,
                args=(config_queue, progress, target),
            )
            threads.append(thread)
            thread.start()

    for thread in threads:
        thread.join()

    queue_items = list(config_queue.queue)

    lines = []
    for output in queue_items:
        lines.extend(output)

    return lines

@memoize
def get_mech_options():
    if path.exists("@mech.json"):
        with open("@mech.json", "r", encoding="utf-8") as f:
            return json.loads(f.read())
    return {}

def _make_name_data(host):
    mech_options = get_mech_options()
    mech_host = host["Host"]

    data = {
        "ssh_hostname": host["HostName"],
    }

    for config_key, data_key in (
        ("Port", "ssh_port"),
        ("User", "ssh_user"),
        ("IdentityFile", "ssh_key"),
    ):
        if config_key in host:
            data[data_key] = host[config_key]

    # Update any configured JSON data
    if mech_host in mech_options.get("data", {}):
        data.update(mech_options["data"][mech_host])

    # Work out groups
    groups = mech_options.get("groups", {}).get(mech_host, [])

    if "@mech" not in groups:
        groups.append("@mech")

    return "@mech/{0}".format(host["Host"]), data, groups

def make_names_data(limit=None):
    mech_ssh_info = get_mech_config(limit)

    logger.debug("Got Mech SSH info: \n%s", mech_ssh_info)

    hosts = []
    current_host = None

    for line in mech_ssh_info:
        if not line:
            if current_host:
                hosts.append(_make_name_data(current_host))

            current_host = None
            continue

        key, value = line.strip().split(" ", 1)

        if key == "Host":
            if current_host:
                hosts.append(_make_name_data(current_host))

            # Set the new host
            current_host = {
                key: value,
            }

        elif current_host:
            current_host[key] = value

        else:
            logger.debug("Extra Mech SSH key/value (%s=%s)", key, value)

    if current_host:
        hosts.append(_make_name_data(current_host))

    if not hosts:
        raise InventoryError("No running Mech instances found!")

    return hosts


text:
package io.vertx.test.codegen.testapi;

import io.vertx.codegen.annotations.VertxGen;

/**
 * @author Tim Fox
 */
@VertxGen
public interface VertxGenClass1 {

  void foo(String str);
}


text:
<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet href="test-to-html.xsl" type="text/xml"?>

<!--

Copyright (c) 2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, Institut National de
Recherche en Informatique et en Automatique, Keio University).  All
Rights Reserved.  This program is distributed under the W3C's Software
Intellectual Property License.  This program is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.

See W3C License http://www.w3.org/Consortium/Legal/ for more details.

-->

<!DOCTYPE test SYSTEM "dom3.dtd">
<test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-3" name="infoset08">
<metadata>
<title>infoset08</title>
<creator>Curt Arnold</creator>
<description>
Attempt to load a namespace invalid document with infoset = true.
</description>
<date qualifier="created">2004-03-30</date>
<subject resource="http://www.w3.org/TR/2004/REC-DOM-Level-3-LS-20040407/load-save#LS-LSParser-parseURI"/>
<subject resource="http://www.w3.org/TR/2004/REC-DOM-Level-3-LS-20040407/load-save#parameter-infoset"/>
</metadata>
<var name="doc" type="Document"/>
<var name="node" type="Node"/>
<var name="nodeType" type="int"/>
<var name="domConfig" type="DOMConfiguration"/>
<var name="domImplLS" type="DOMImplementationLS"/>
<var name="lsParser" type="LSParser"/>
<var name="nullSchemaType" type="DOMString" isNull="true"/>
<var name="resourceURI" type="DOMString"/>
<implementation var="domImplLS"/>
<createLSParser var="lsParser" obj="domImplLS" mode="1" schemaType="nullSchemaType"/>
<domConfig obj="lsParser" var="domConfig" interface="LSParser"/>
<setParameter obj="domConfig" name='"infoset"' value="true"/>
<getResourceURI var="resourceURI" href='"namespaces1"' contentType="text/xml"/>
<assertLSException id="throw_PARSE_ERR">
	<PARSE_ERR>
		<parseURI var="doc" obj="lsParser" uri="resourceURI"/>
	</PARSE_ERR>
</assertLSException>
</test>


text:
1. Copy `StartTerminator.vbs` and `Terminator.ico` into `%USERPROFILE%` (`c:\User\liusha`)
2. Copy `StartTerminator.lnk` into desktop

If the shortcut does not work, set the following shortcut properties

1. target: `wscript.exe %USERPROFILE%\StartTerminator.vbs`
2. start in: `%USERPROFILE%`
3. `Change Icon` and set the icon file


text:
//
//  ZBChatroom.m
//  Pods
//
//  Created by lip on 16/8/24.
//
//

#import "ZBChatroom.h"
#import "LiRivalKit.h"
#import "ZBConversationEvent.h"
#import "LRException.h"
#import "ZBErrorCode.h"
#import "ZBMessageModel.h"
#import "ZBApplicationCenter.h"
#import "ZBCloudData.h"
#import "MJExtension/MJExtension.h"

@interface ZBChatroom ()
/** 聊天核心 */
@property (weak, nonatomic) LiRivalKit *liRivalKit;

@end

@implementation ZBChatroom

- (instancetype)init {
    if (self = [super init]) {
        self.liRivalKit = [LiRivalKit coreKit];
    }
    return self;
}

- (void)joinChatroom:(NSNumber *)chatroomID password:(NSString *)password completion:(void (^)(id, NSError *))completion {
    NSDictionary *messageBody = nil;
    if (password) {
        messageBody = @{@"cid": chatroomID, @"pwd": password};
    } else {
        messageBody = @{@"cid": chatroomID};
    }

    if (chatroomID == nil) {
        completion(nil, [ZBErrorCode errorCreateWithErrorCode:ZBErrorCodeStatusEmptyParameter]);
    }

    [self.liRivalKit sendMessageWithMessageEvent:ZBConversationEventChatroomJoin messageBody:messageBody messageIdentity:@(self.liRivalKit.sendMessageIdentity) completion:^(NSArray *respondData, NSError *error) {
        if (completion) {
            if (error) {
                completion(nil, error);
            } else {
                if ([respondData[0] isEqualToString:ZBConversationEventChatroomJoin]) {
                    [ZBApplicationCenter defaultCenter].chatroomIdentity = chatroomID;
                    completion(respondData[1], nil);
                } else {
                    LRException *exception = [LRException raiseWithLRExceptionCode:LRExceptionInvalidArgument];
                    [exception raise];
                }
            }
        }
    }];
}

- (void)checkUser:(NSString *)userIdentity sendIMStatusCompletion:(void(^)(id respondData, NSError *error))completion {
    if (userIdentity == nil) {
        completion(nil, [ZBErrorCode errorCreateWithErrorCode:ZBErrorCodeStatusUnInitialize]);
        return;
    }

    [ZBCloudData getZBCloudDataWithApi:@"ZBCloud_Im_Stream_status" parameter:@{@"usid": userIdentity} success:^(id data) {
        completion(data, nil);
    } fail:^(NSError *fail) {
        completion(nil, fail);
    }];
}

- (void)disableChatroomUserIdentity:(NSString *)userIdentity sendMessageWithTime:(NSUInteger)disableTime completion:(void(^)(id respondData, NSError *error))completion {
    if (userIdentity == nil) {
        completion(nil, [ZBErrorCode errorCreateWithErrorCode:ZBErrorCodeStatusUnInitialize]);
        return;
    }
    if (disableTime == 0) {
        [ZBCloudData getZBCloudDataWithApi:@"ZBCloud_Im_Stream_Disable" parameter:@{@"usid": userIdentity, @"time": @(disableTime)} success:^(id data) {
            completion(data, nil);
        } fail:^(NSError *fail) {
            completion(nil, fail);
        }];
        return;
    }
    NSUInteger disableTimestamp = (long)[[NSDate date] timeIntervalSince1970];
    disableTimestamp += disableTime;
    [ZBCloudData getZBCloudDataWithApi:@"ZBCloud_Im_Stream_Disable" parameter:@{@"usid": userIdentity, @"time": @(disableTimestamp)} success:^(id data) {
        completion(data, nil);
    } fail:^(NSError *fail) {
        completion(nil, fail);
    }];
}

- (void)enableChatroomUserIdentity:(NSString *)userIdentity sendMessageCompletion:(void(^)(id respondData, NSError *error))completion {
    if (userIdentity == nil) {
        completion(nil, [ZBErrorCode errorCreateWithErrorCode:ZBErrorCodeStatusUnInitialize]);
        return;
    }
    [ZBCloudData getZBCloudDataWithApi:@"ZBCloud_Im_Stream_Enable" parameter:@{@"usid": userIdentity} success:^(id data) {
        completion(data, nil);
    } fail:^(NSError *fail) {
        completion(nil, fail);
    }];
}

- (void)getChatroom:(NSNumber *)chatroomID viewerCountCompletion:(void (^)(id, NSError *))completion {
    if (chatroomID == nil) {
        completion(nil, [ZBErrorCode errorCreateWithErrorCode:ZBErrorCodeStatusEmptyParameter]);
    }

    NSDictionary *messageBody = @{@"cid": chatroomID, @"field": @"mc"};

    [self.liRivalKit sendMessageWithMessageEvent:ZBConversationEventGetConversationDetailInfo messageBody:messageBody messageIdentity:@(self.liRivalKit.sendMessageIdentity) completion:^(NSArray *respondData, NSError *error) {
        if (completion) {
            if (error) {
                completion(nil, error);
            } else {
                if ([respondData[0] isEqualToString:ZBConversationEventGetConversationDetailInfo]) {
                    completion(respondData[1], nil);
                } else {
                    LRException *exception = [LRException raiseWithLRExceptionCode:LRExceptionInvalidArgument];
                    [exception raise];
                }
            }
        }
    }];
}

- (void)leaveChatroom:(NSNumber *)chatroomID password:(NSString *)password completion:(void (^)(id, NSError *))completion {
    NSDictionary *messageBody = nil;
    if (password) {
        messageBody = @{@"cid": chatroomID, @"pwd": password};
    } else {
        messageBody = @{@"cid": chatroomID};
    }

    if (chatroomID == nil) {
        completion(nil, [ZBErrorCode errorCreateWithErrorCode:ZBErrorCodeStatusEmptyParameter]);
    }

    ZBMessageModel *messageModel = [[ZBMessageModel alloc] init];
    messageModel.conversationIdentity = chatroomID;
    messageModel.type = @(ZBMessageModelTypeCoustomAvailable);
    NSString *ZBUSID = [ZBApplicationCenter defaultCenter].userAuthenticityModel.businessUserIdentity;
    messageModel.extend = @{@"ZBUSID": ZBUSID, @"customID" : @(50400)};

    [self.liRivalKit sendMessageWithMessageEvent:ZBConversationEventChatroomLeave messageBody:messageBody messageIdentity:@(self.liRivalKit.sendMessageIdentity) completion:^(NSArray *respondData, NSError *error) {
        if (completion) {
            if (error) {
                completion(nil, error);
            } else {
                if ([respondData[0] isEqualToString:ZBConversationEventChatroomLeave]) {
                    completion(respondData[1], nil);
                } else {
                    LRException *exception = [LRException raiseWithLRExceptionCode:LRExceptionInvalidArgument];
                    [exception raise];
                }
            }
        }
    }];
}

@end


text:
require ("lib.yanecos.Data")
require ("lib.yanecos.DataBase")
require ("lib.yanecos.EntityManager")
require ("lib.yanecos.System")
require ("lib.yanecos.SystemManager")


text:
A Framework that gives you access to the powerful Mesosfer cloud platform from your iOS app.
For more information about Mesosfer and its features, see [Mesosfer Website][mesosfer.com] and [Mesosfer Documentations][docs].

## Mesosfer Data
Storing data on Mesosfer is built around the `MFData`. Each `MFData` contains key-value pairs of JSON-compatible data. This data is using schema, which means that you need to specify ahead of time what keys exist on each `MFData` from our [Mesosfer Cloud][cloud]. Then you can simply set a key-value pairs you want to save, and our backend will store it.

For example, let's say you're set a Beacon parameters. A single `MFData` could contain :

```json
{
    "isActive":true,
    "major":1,
    "name":"Beacon One",
    "minor":284,
    "proximityUUID":"CB10023F-A318-3394-4199-A8730C7C1AEC"
}
```

Keys must be alphanumeric strings. Values can be `String`s, `Number`s, `Date`s, `Boolean`s, or even `Array`s and `Object`s - anything that can be JSON-encoded.

## Saving data
Let's say you want to save the Beacon described above to the [Mesosfer Cloud][cloud]. The interface is similar to a Map, plus the `saveAsync` method:

```swift
let data = MFData(withBucket: "Beacon")

// set data
data["name"] = "Beacon One"
data["proximityUUID"] = "CB10023F-A318-3394-4199-A8730C7C1AEC"
data["major"] = 1
data["minor"] = 284
data["isActive"] = true
data["timestamp"] = NSDate()

// execute save data
data.saveAsync { (succeeded, error) in
    if succeeded {
        // data saved, show success message
    } else {
        // failed to save data, show error message
    }
}
```

## Deleting Data
To delete a data from the Mesosfer Cloud, use method `deleteAsync`:

```swift
data.deleteAsync { (succeeded, error) in
    if succeeded {
        // data deleted, show success message
    } else {
        // failed to delete data, show error message
    }
}
```

## License
    Copyright (c) 2016, Mesosfer.
    All rights reserved.

    This source code is licensed under the BSD-style license found in the
    LICENSE file in the root directory of this source tree.

[mesosfer.com]:https://mesosfer.com
[docs]:https://docs.mesosfer.com/
[cloud]:https://cloud.mesosfer.com/
[framework]:https://github.com/mesosfer/Mesosfer-iOS/releases/latest


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>mapsV3key</title>

<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="css/jquery.mobile-1.4.3.min.css" />

  			<button data-inline="true" data-icon="camera" id='cameraBtn'>&#46</button>
  			<button data-inline="true" data-icon="refresh" id='refreshBtn'>&#46</button>
  			<button data-inline="true" data-icon="search" id='navigateBtn'>&#46</button>
        <button data-inline="true" data-icon="eye" id='eyeBtn'>&#46</button>

      <button data-inline="true" id='infoButton' data-icon="info" >tap me</button>

<!-      ----------------------------------------------------------------------------- -->
<!-      ----------------------------------------------------------------------------- -->
<!-      ----------------------------------------------------------------------------- -->

      Mystery solved! (at least for iOS in version 1 of this cookbook)

      Pure html5 apps using a private google maps v3 API key via phonegapBuild.

      <button data-inline="true" id="infoBackBtn" data-icon="back" >tap me</button>

<!-      ----------------------------------------------------------------------------- -->
<!-      ----------------------------------------------------------------------------- -->
<!-      ----------------------------------------------------------------------------- -->


text:
package org.meaningfulweb.cext.processors;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.meaningfulweb.cext.HtmlContentProcessor;
import org.meaningfulweb.util.XMLUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Text;
import org.jdom.xpath.XPath;

public class XPathProcessor
  extends HtmlContentProcessor {

  public static final Log LOG = LogFactory.getLog(XPathProcessor.class);

  private Set<String> xpaths = new LinkedHashSet<String>();
  private boolean cleaning = false;
  private boolean extractHtml = true;
  private boolean extractText = true;

  @Override
  public boolean processContent(Document document) {

    if (xpaths != null && xpaths.size() > 0) {

      List<Element> selectedList = new ArrayList<Element>();

      for (String xpath : xpaths) {
        List selNodes = null;
        try {
          XPath xp = XPath.newInstance(xpath);
          selNodes = xp.selectNodes(document);
        }
        catch (JDOMException e) {
          e.printStackTrace();
        }
        if (selNodes != null && selNodes.size() > 0) {
          for (Object objNode : selNodes) {
            if (objNode instanceof Element) {
              Element selElem = (Element)objNode;
              if (extractHtml) {
                addExtractedValue(xpath, XMLUtils.toHtml(selElem));
              }
              if (extractText) {
                addExtractedValue(xpath + ".text", XMLUtils.toText(selElem));
              }
              if (cleaning) {
                selectedList.add(selElem);
              }
            }
            else if (objNode instanceof Text) {
              addExtractedValue(xpath, ((Text)objNode).getTextNormalize());
            }
            else if (objNode instanceof Comment) {
              addExtractedValue(xpath, ((Comment)objNode).getText());
            }
          }
        }
      }

      if (cleaning && selectedList.size() > 0) {
        Element root = document.getRootElement();
        for (Element connected : selectedList) {
          connected.detach();
        }
        root.setContent(selectedList);
      }
    }

    return true;
  }

  public Collection<String> getXpaths() {
    return xpaths;
  }

  public void setXpaths(Collection<String> xpaths) {

    if (xpaths != null) {
      if (xpaths instanceof Set) {
        this.xpaths = (Set<String>)xpaths;
      }
      else {
        Set<String> newXpaths = new HashSet<String>();
        newXpaths.addAll(xpaths);
        this.xpaths = newXpaths;
      }
    }
  }

  public boolean isExtractHtml() {
    return extractHtml;
  }

  public void setExtractHtml(boolean extractHtml) {
    this.extractHtml = extractHtml;
  }

  public boolean isExtractText() {
    return extractText;
  }

  public void setExtractText(boolean extractText) {
    this.extractText = extractText;
  }

  public boolean isCleaning() {
    return cleaning;
  }

  public void setCleaning(boolean cleaning) {
    this.cleaning = cleaning;
  }

}


text:
package org.apache.eagle.alert.engine.spark.model;

import kafka.message.MessageAndMetadata;
import org.apache.eagle.alert.engine.spark.accumulator.MapToMapAccum;
import org.apache.spark.Accumulator;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

public class SiddhiState implements Serializable {
    private static final Logger LOG = LoggerFactory.getLogger(SiddhiState.class);
    private static final long serialVersionUID = -2180409299871716057L;
    private AtomicReference<Map<Integer, Map<String, byte[]>>> siddhiSnapshot = new AtomicReference<>();
    private Accumulator<Map<Integer, Map<String, byte[]>>> siddhiSnapShotAccum;

    public SiddhiState() {
    }

    public void initailSiddhiState(JavaRDD<MessageAndMetadata<String, String>> rdd) {
        Accumulator<Map<Integer, Map<String, byte[]>>> siddhiSnapShotAccum = StateInstance.getInstance(new JavaSparkContext(rdd.context()), "siddhiSnapShotState", new MapToMapAccum());
        this.siddhiSnapShotAccum = siddhiSnapShotAccum;
    }

    public void recover(JavaRDD<MessageAndMetadata<String, String>> rdd) {
        initailSiddhiState(rdd);
        siddhiSnapshot.set(siddhiSnapShotAccum.value());
        LOG.debug("---------siddhiSnapshot----------" + siddhiSnapshot.get());
    }

    public void store(byte[] snapShot, String boltId, int partitionNum) {
        Map<Integer, Map<String, byte[]>> siddhiSnapShot = new HashMap<>();
        Map<String, byte[]> boltIdToSnapShot = new HashMap<>();
        boltIdToSnapShot.put(boltId, snapShot);
        siddhiSnapShot.put(partitionNum, boltIdToSnapShot);
        LOG.debug("---------store---siddhiSnapshot----------" + siddhiSnapShot);
        siddhiSnapShotAccum.add(siddhiSnapShot);
    }

    public byte[] getSiddhiSnapShotByBoltIdAndPartitionNum(String boltId, int partitionNum) {
        Map<Integer, Map<String, byte[]>> partitionToSnapShot = siddhiSnapshot.get();
        LOG.debug("---SiddhiState----getSiddhiSnapShotByPartition----------" + (partitionToSnapShot));
        Map<String, byte[]> boltIdToSnapShot = partitionToSnapShot.get(partitionNum);
        byte[] siddhiSnapshot = null;
        if (boltIdToSnapShot != null) {
            siddhiSnapshot = boltIdToSnapShot.get(boltId);
        }
        return siddhiSnapshot;
    }
}


text:
class ClientDetail < ActiveRecord::Base
  belongs_to :order
end


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>Documentation Global</title>

	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.cerulean.css">

		Documentation
		<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation">

        </button>

				Classes

AuthContext

configuration

				Global

Global

                <form class="navbar-form" role="search">

                        <input type="text" class="form-control" placeholder="Search" name="q" id="search-input">

                            <button class="btn btn-default" id="search-submit"></button>

                </form>

Global

Type Definitions

authorizeCallback(error, token)

Parameters:

        Name

        Type

        Description

                error

string

contains error description if error state, null if no error present

                token

string

authorization token resulting from renew or login request, null if error

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

Search results

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

	Documentation generated by JSDoc 3.4.3

		on March 10th 2017, 11:01:10 am

	using the DocStrap template.


text:
/**
 *
 */
package com.cardpay.pccredit.postLoan.filter;

import java.util.List;

import com.cardpay.pccredit.manager.web.AccountManagerParameterForm;
import com.wicresoft.jrad.base.web.filter.BaseQueryFilter;

/**
 * @author shaoming
 *
 * 2014年11月11日   下午3:03:58
 */
public class PostLoanFilter extends BaseQueryFilter{
	private String zjhm;
	private String jjh;
	private String busiCode;
	private String cardNum;

	private String customerName;

	private String userId;
	private String customerManagerName;

	private String startDate;
	private String endDate;

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public String getCustomerManagerName() {
		return customerManagerName;
	}

	public void setCustomerManagerName(String customerManagerName) {
		this.customerManagerName = customerManagerName;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getCustomerName() {
		return customerName;
	}

	public void setCustomerName(String customerName) {
		this.customerName = customerName;
	}

	public String getCardNum() {
		return cardNum;
	}

	public void setCardNum(String cardNum) {
		this.cardNum = cardNum;
	}

	public String getBusiCode() {
		return busiCode;
	}

	public void setBusiCode(String busiCode) {
		this.busiCode = busiCode;
	}

	public String getZjhm() {
		return zjhm;
	}

	public void setZjhm(String zjhm) {
		this.zjhm = zjhm;
	}

	public String getJjh() {
		return jjh;
	}

	public void setJjh(String jjh) {
		this.jjh = jjh;
	}

}