text:
/**
 */
package org.vilang.vilang;

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

import org.eclipse.emf.common.util.Enumerator;

/**
 *
 * A representation of the literals of the enumeration 'File Char',
 * and utility methods for working with them.
 *
 * @see org.vilang.vilang.VilangPackage#getFileChar()
 * @model
 * @generated
 */
public enum FileChar implements Enumerator
{
  /**
   * The 'COLON' literal object.
   *
   *
   * @see #COLON_VALUE
   * @generated
   * @ordered
   */
  COLON(0, "COLON", "COLON"),

  /**
   * The 'COMMA' literal object.
   *
   *
   * @see #COMMA_VALUE
   * @generated
   * @ordered
   */
  COMMA(1, "COMMA", "COMMA"),

  /**
   * The 'DOT' literal object.
   *
   *
   * @see #DOT_VALUE
   * @generated
   * @ordered
   */
  DOT(2, "DOT", "DOT"),

  /**
   * The 'SEMICOLON' literal object.
   *
   *
   * @see #SEMICOLON_VALUE
   * @generated
   * @ordered
   */
  SEMICOLON(3, "SEMICOLON", "SEMICOLON"),

  /**
   * The 'SPACE' literal object.
   *
   *
   * @see #SPACE_VALUE
   * @generated
   * @ordered
   */
  SPACE(4, "SPACE", "SPACE"),

  /**
   * The 'QUESTION TAG' literal object.
   *
   *
   * @see #QUESTION_TAG_VALUE
   * @generated
   * @ordered
   */
  QUESTION_TAG(5, "QUESTION_TAG", "QUESTION_TAG");

  /**
   * The 'COLON' literal value.
   *
   *

   * If the meaning of 'COLON' literal object isn't clear,
   * there really should be more of a description here...
   *

   *
   * @see #COLON
   * @model
   * @generated
   * @ordered
   */
  public static final int COLON_VALUE = 0;

  /**
   * The 'COMMA' literal value.
   *
   *

   * If the meaning of 'COMMA' literal object isn't clear,
   * there really should be more of a description here...
   *

   *
   * @see #COMMA
   * @model
   * @generated
   * @ordered
   */
  public static final int COMMA_VALUE = 1;

  /**
   * The 'DOT' literal value.
   *
   *

   * If the meaning of 'DOT' literal object isn't clear,
   * there really should be more of a description here...
   *

   *
   * @see #DOT
   * @model
   * @generated
   * @ordered
   */
  public static final int DOT_VALUE = 2;

  /**
   * The 'SEMICOLON' literal value.
   *
   *

   * If the meaning of 'SEMICOLON' literal object isn't clear,
   * there really should be more of a description here...
   *

   *
   * @see #SEMICOLON
   * @model
   * @generated
   * @ordered
   */
  public static final int SEMICOLON_VALUE = 3;

  /**
   * The 'SPACE' literal value.
   *
   *

   * If the meaning of 'SPACE' literal object isn't clear,
   * there really should be more of a description here...
   *

   *
   * @see #SPACE
   * @model
   * @generated
   * @ordered
   */
  public static final int SPACE_VALUE = 4;

  /**
   * The 'QUESTION TAG' literal value.
   *
   *

   * If the meaning of 'QUESTION TAG' literal object isn't clear,
   * there really should be more of a description here...
   *

   *
   * @see #QUESTION_TAG
   * @model
   * @generated
   * @ordered
   */
  public static final int QUESTION_TAG_VALUE = 5;

  /**
   * An array of all the 'File Char' enumerators.
   *
   *
   * @generated
   */
  private static final FileChar[] VALUES_ARRAY =
    new FileChar[]
    {
      COLON,
      COMMA,
      DOT,
      SEMICOLON,
      SPACE,
      QUESTION_TAG,
    };

  /**
   * A public read-only list of all the 'File Char' enumerators.
   *
   *
   * @generated
   */
  public static final List<FileChar> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));

  /**
   * Returns the 'File Char' literal with the specified literal value.
   *
   *
   * @param literal the literal.
   * @return the matching enumerator or null.
   * @generated
   */
  public static FileChar get(String literal)
  {
    for (int i = 0; i < VALUES_ARRAY.length; ++i)
    {
      FileChar result = VALUES_ARRAY[i];
      if (result.toString().equals(literal))
      {
        return result;
      }
    }
    return null;
  }

  /**
   * Returns the 'File Char' literal with the specified name.
   *
   *
   * @param name the name.
   * @return the matching enumerator or null.
   * @generated
   */
  public static FileChar getByName(String name)
  {
    for (int i = 0; i < VALUES_ARRAY.length; ++i)
    {
      FileChar result = VALUES_ARRAY[i];
      if (result.getName().equals(name))
      {
        return result;
      }
    }
    return null;
  }

  /**
   * Returns the 'File Char' literal with the specified integer value.
   *
   *
   * @param value the integer value.
   * @return the matching enumerator or null.
   * @generated
   */
  public static FileChar get(int value)
  {
    switch (value)
    {
      case COLON_VALUE: return COLON;
      case COMMA_VALUE: return COMMA;
      case DOT_VALUE: return DOT;
      case SEMICOLON_VALUE: return SEMICOLON;
      case SPACE_VALUE: return SPACE;
      case QUESTION_TAG_VALUE: return QUESTION_TAG;
    }
    return null;
  }

  /**
   *
   *
   * @generated
   */
  private final int value;

  /**
   *
   *
   * @generated
   */
  private final String name;

  /**
   *
   *
   * @generated
   */
  private final String literal;

  /**
   * Only this class can construct instances.
   *
   *
   * @generated
   */
  private FileChar(int value, String name, String literal)
  {
    this.value = value;
    this.name = name;
    this.literal = literal;
  }

  /**
   *
   *
   * @generated
   */
  public int getValue()
  {
    return value;
  }

  /**
   *
   *
   * @generated
   */
  public String getName()
  {
    return name;
  }

  /**
   *
   *
   * @generated
   */
  public String getLiteral()
  {
    return literal;
  }

  /**
   * Returns the literal value of the enumerator, which is its string representation.
   *
   *
   * @generated
   */
  @Override
  public String toString()
  {
    return literal;
  }

} //FileChar


text:
compass_config do |config|
  # Require any additional compass plugins here.
  config.add_import_path "bower_components/foundation/scss"

  config.output_style = :compact
end

###
# Page options, layouts, aliases and proxies
###

# Per-page layout changes:
#
# With no layout
# page "/path/to/file.html", :layout => false
#
# With alternative layout
# page "/path/to/file.html", :layout => :otherlayout
#
# A path which all have the same layout
# with_layout :admin do
#   page "/admin/*"
# end

# Proxy pages (http://middlemanapp.com/basics/dynamic-pages/)
# proxy "/this-page-has-no-template.html", "/template-file.html", :locals => {
#  :which_fake_page => "Rendering a fake page with a local variable" }

###
# Helpers
###

# Automatic image dimensions on image_tag helper
# activate :automatic_image_sizes

# Reload the browser automatically whenever files change
# configure :development do
#   activate :livereload
# end

# Methods defined in the helpers block are available in templates
# helpers do
#   def some_helper
#     "Helping"
#   end
# end

# Add bower's directory to sprockets asset path
after_configuration do
  @bower_config = JSON.parse(IO.read("#{root}/.bowerrc"))
  sprockets.append_path File.join "#{root}", @bower_config["directory"]
end

set :css_dir, 'css'

set :js_dir, 'js'

set :images_dir, 'img'

# Build-specific configuration
configure :build do
  # For example, change the Compass output style for deployment
  # activate :minify_css

  # Minify Javascript on build
  # activate :minify_javascript

  # Enable cache buster
  # activate :asset_hash

  # Use relative URLs
  # activate :relative_assets

  # Or use a different image path
  # set :http_prefix, "/Content/images/"
end

redpajama_set_name: RedPajamaGithub


text:
// -----------------------------------------------------------------------
// <copyright file="PointerPressEventArgs.cs" company="Steven Kirk">
// Copyright 2013 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------

namespace Perspex.Input
{
    public class PointerPressEventArgs : PointerEventArgs
    {
        public int ClickCount { get; set; }
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@interface ApptentiveMessageCenterProfileView : UIView

@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UITextField *nameField;
@property (weak, nonatomic) IBOutlet UITextField *emailField;
@property (weak, nonatomic) IBOutlet UIButton *skipButton;
@property (weak, nonatomic) IBOutlet UIButton *saveButton;
@property (strong, nonatomic) UIColor *borderColor;

@end

NS_ASSUME_NONNULL_END


text:
package io.cattle.platform.agent.instance.process;

import io.cattle.platform.agent.instance.service.AgentInstanceManager;
import io.cattle.platform.core.model.Nic;
import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.handler.ProcessPreListener;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.process.common.handler.AbstractObjectProcessLogic;
import io.cattle.platform.util.type.Priority;

import javax.inject.Inject;

public class AgentInstanceNicActivate extends AbstractObjectProcessLogic implements ProcessPreListener, Priority {

    AgentInstanceManager agentInstanceManager;

    @Override
    public String[] getProcessNames() {
        return new String[] { "nic.activate" };
    }

    @Override
    public HandlerResult handle(ProcessState state, ProcessInstance process) {
        agentInstanceManager.getAgentInstances((Nic) state.getResource());

        return null;
    }

    @Override
    public int getPriority() {
        return Priority.PRE;
    }

    public AgentInstanceManager getAgentInstanceManager() {
        return agentInstanceManager;
    }

    @Inject
    public void setAgentInstanceManager(AgentInstanceManager agentInstanceManager) {
        this.agentInstanceManager = agentInstanceManager;
    }

}


text:
Ehdotan
=======

A collection of useful Vaadin things that "I suggest" you use.

https://vaadin.com/

NOTE: Ehdotan is for Vaadin 6.
It has not been tested with Vaadin 7.


text:
using testing::Combine;
using testing::HasSubstr;
using ::testing::TestParamInfo;
using testing::Values;

namespace Envoy {
namespace Extensions {
namespace NetworkFilters {
namespace ThriftProxy {

class ThriftConnManagerIntegrationTest
    : public testing::TestWithParam<std::tuple<TransportType, ProtocolType, bool, bool>>,
      public BaseThriftIntegrationTest {
public:
  static void SetUpTestSuite() { // NOLINT(readability-identifier-naming)
    thrift_config_ = absl::StrCat(ConfigHelper::baseConfig(), R"EOF(
    filter_chains:
      filters:
        - name: thrift
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.network.thrift_proxy.v3.ThriftProxy
            stat_prefix: thrift_stats
            route_config:
              name: "routes"
              routes:
                - match:
                    service_name: "svcname"
                  route:
                    cluster: "cluster_0"
                - match:
                    method_name: "execute"
                    headers:
                    - name: "x-header-1"
                      string_match:
                        exact: "x-value-1"
                    - name: "x-header-2"
                      string_match:
                        safe_regex:
                          regex: "0.[5-9]"
                    - name: "x-header-3"
                      range_match:
                        start: 100
                        end: 200
                    - name: "x-header-4"
                      string_match:
                        prefix: "user_id:"
                    - name: "x-header-5"
                      string_match:
                        suffix: "asdf"
                  route:
                    cluster: "cluster_1"
                - match:
                    method_name: "execute"
                  route:
                    cluster: "cluster_2"
                - match:
                    method_name: "poke"
                  route:
                    cluster: "cluster_3"
      )EOF");
  }

  void initializeCall(DriverMode mode) {
    std::tie(transport_, protocol_, multiplexed_, std::ignore) = GetParam();

    absl::optional<std::string> service_name;
    if (multiplexed_) {
      service_name = "svcname";
    }

    std::vector<std::pair<std::string, std::string>> headers;
    if (transport_ == TransportType::Header) {
      headers.push_back(std::make_pair("x-header-1", "x-value-1"));
      headers.push_back(std::make_pair("x-header-2", "0.6"));
      headers.push_back(std::make_pair("x-header-3", "150"));
      headers.push_back(std::make_pair("x-header-4", "user_id:10"));
      headers.push_back(std::make_pair("x-header-5", "garbage_asdf"));
    }

    PayloadOptions options(transport_, protocol_, mode, service_name, "execute", {}, headers);
    preparePayloads(options, request_bytes_, response_bytes_);
    ASSERT(request_bytes_.length() > 0);
    ASSERT(response_bytes_.length() > 0);
    initializeCommon();
  }

  void initializeOneway() {
    std::tie(transport_, protocol_, multiplexed_, std::ignore) = GetParam();

    absl::optional<std::string> service_name;
    if (multiplexed_) {
      service_name = "svcname";
    }

    PayloadOptions options(transport_, protocol_, DriverMode::Success, service_name, "poke");
    preparePayloads(options, request_bytes_, response_bytes_);
    ASSERT(request_bytes_.length() > 0);
    ASSERT(response_bytes_.length() == 0);
    initializeCommon();
  }

  void tryInitializePassthrough() {
    std::tie(std::ignore, std::ignore, std::ignore, payload_passthrough_) = GetParam();

    if (payload_passthrough_) {
      config_helper_.addFilterConfigModifier<
          envoy::extensions::filters::network::thrift_proxy::v3::ThriftProxy>(
          "thrift", [](Protobuf::Message& filter) {
            auto& conn_manager =
                dynamic_cast<envoy::extensions::filters::network::thrift_proxy::v3::ThriftProxy&>(
                    filter);
            conn_manager.set_payload_passthrough(true);
          });
    }
  }

  // We allocate as many upstreams as there are clusters, with each upstream being allocated
  // to clusters in the order they're defined in the bootstrap config.
  void initializeCommon() {
    setUpstreamCount(4);

    config_helper_.addConfigModifier([](envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
      for (int i = 1; i < 4; i++) {
        auto* c = bootstrap.mutable_static_resources()->add_clusters();
        c->MergeFrom(bootstrap.static_resources().clusters()[0]);
        c->set_name(absl::StrCat("cluster_", i));
      }
    });

    tryInitializePassthrough();

    BaseThriftIntegrationTest::initialize();
  }

protected:
  // Multiplexed requests are handled by the service name route match,
  // while oneway's are handled by the "poke" method. All other requests
  // are handled by "execute".
  FakeUpstream* getExpectedUpstream(bool oneway) {
    int upstreamIdx = getExpectedUpstreamIdx(oneway);
    return fake_upstreams_[upstreamIdx].get();
  }

  int getExpectedUpstreamIdx(bool oneway) {
    int upstreamIdx = 2;
    if (multiplexed_) {
      upstreamIdx = 0;
    } else if (oneway) {
      upstreamIdx = 3;
    } else if (transport_ == TransportType::Header) {
      upstreamIdx = 1;
    }

    return upstreamIdx;
  }

  TransportType transport_;
  ProtocolType protocol_;
  bool multiplexed_;
  bool payload_passthrough_;

  std::string result_;

  Buffer::OwnedImpl request_bytes_;
  Buffer::OwnedImpl response_bytes_;
};

static std::string
paramToString(const TestParamInfo<std::tuple<TransportType, ProtocolType, bool, bool>>& params) {
  TransportType transport;
  ProtocolType protocol;
  bool multiplexed;
  bool passthrough;
  std::tie(transport, protocol, multiplexed, passthrough) = params.param;

  std::string transport_name = transportNameForTest(transport);
  std::string protocol_name = protocolNameForTest(protocol);

  std::string result;

  if (multiplexed) {
    result = fmt::format("{}{}Multiplexed", transport_name, protocol_name);
  } else {
    result = fmt::format("{}{}", transport_name, protocol_name);
  }
  if (passthrough) {
    result = fmt::format("{}Passthrough", result);
  }
  return result;
}

INSTANTIATE_TEST_SUITE_P(TransportAndProtocol, ThriftConnManagerIntegrationTest,
                         Combine(Values(TransportType::Framed, TransportType::Unframed,
                                        TransportType::Header),
                                 Values(ProtocolType::Binary, ProtocolType::Compact),
                                 Values(false, true), Values(false, true)),
                         paramToString);

TEST_P(ThriftConnManagerIntegrationTest, Success) {
  initializeCall(DriverMode::Success);

  IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("listener_0"));
  ASSERT_TRUE(tcp_client->write(request_bytes_.toString()));

  FakeRawConnectionPtr fake_upstream_connection;
  FakeUpstream* expected_upstream = getExpectedUpstream(false);
  ASSERT_TRUE(expected_upstream->waitForRawConnection(fake_upstream_connection));
  std::string data;
  ASSERT_TRUE(fake_upstream_connection->waitForData(request_bytes_.length(), &data));
  Buffer::OwnedImpl upstream_request(data);
  EXPECT_EQ(request_bytes_.toString(), upstream_request.toString());

  ASSERT_TRUE(fake_upstream_connection->write(response_bytes_.toString()));

  tcp_client->waitForData(response_bytes_.toString());
  tcp_client->close();

  EXPECT_TRUE(TestUtility::buffersEqual(Buffer::OwnedImpl(tcp_client->data()), response_bytes_));

  Stats::CounterSharedPtr counter = test_server_->counter("thrift.thrift_stats.request_call");
  EXPECT_EQ(1U, counter->value());
  int upstream_idx = getExpectedUpstreamIdx(false);
  counter = test_server_->counter(
      fmt::format("cluster.cluster_{}.thrift.upstream_rq_call", upstream_idx));
  EXPECT_EQ(1U, counter->value());
  if (payload_passthrough_ &&
      (transport_ == TransportType::Framed || transport_ == TransportType::Header) &&
      protocol_ != ProtocolType::Twitter) {
    counter = test_server_->counter("thrift.thrift_stats.response_passthrough");
    EXPECT_EQ(1U, counter->value());
  } else {
    counter = test_server_->counter("thrift.thrift_stats.response_passthrough");
    EXPECT_EQ(0U, counter->value());
  }
  counter = test_server_->counter("thrift.thrift_stats.response_reply");
  EXPECT_EQ(1U, counter->value());
  counter = test_server_->counter("thrift.thrift_stats.response_success");
  EXPECT_EQ(1U, counter->value());
  counter = test_server_->counter(
      fmt::format("cluster.cluster_{}.thrift.upstream_resp_reply", upstream_idx));
  EXPECT_EQ(1U, counter->value());
  counter = test_server_->counter(
      fmt::format("cluster.cluster_{}.thrift.upstream_resp_success", upstream_idx));
  EXPECT_EQ(1U, counter->value());
}

TEST_P(ThriftConnManagerIntegrationTest, IDLException) {
  DISABLE_UNDER_WINDOWS; // https://github.com/envoyproxy/envoy/issues/21017
  initializeCall(DriverMode::IDLException);

  IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("listener_0"));
  ASSERT_TRUE(tcp_client->write(request_bytes_.toString()));

  FakeUpstream* expected_upstream = getExpectedUpstream(false);
  FakeRawConnectionPtr fake_upstream_connection;
  ASSERT_TRUE(expected_upstream->waitForRawConnection(fake_upstream_connection));
  std::string data;
  ASSERT_TRUE(fake_upstream_connection->waitForData(request_bytes_.length(), &data));
  Buffer::OwnedImpl upstream_request(data);
  EXPECT_EQ(request_bytes_.toString(), upstream_request.toString());

  ASSERT_TRUE(fake_upstream_connection->write(response_bytes_.toString()));

  tcp_client->waitForData(response_bytes_.toString());
  tcp_client->close();

  EXPECT_TRUE(TestUtility::buffersEqual(Buffer::OwnedImpl(tcp_client->data()), response_bytes_));

  Stats::CounterSharedPtr counter = test_server_->counter("thrift.thrift_stats.request_call");
  EXPECT_EQ(1U, counter->value());
  int upstream_idx = getExpectedUpstreamIdx(false);
  counter = test_server_->counter(
      fmt::format("cluster.cluster_{}.thrift.upstream_rq_call", upstream_idx));
  if (payload_passthrough_ &&
      (transport_ == TransportType::Framed || transport_ == TransportType::Header) &&
      protocol_ != ProtocolType::Twitter) {
    counter = test_server_->counter("thrift.thrift_stats.response_passthrough");
    EXPECT_EQ(1U, counter->value());
  } else {
    counter = test_server_->counter("thrift.thrift_stats.response_passthrough");
    EXPECT_EQ(0U, counter->value());
  }
  counter = test_server_->counter("thrift.thrift_stats.response_reply");
  EXPECT_EQ(1U, counter->value());
  counter = test_server_->counter("thrift.thrift_stats.response_error");
  EXPECT_EQ(1U, counter->value());
  counter = test_server_->counter(
      fmt::format("cluster.cluster_{}.thrift.upstream_resp_reply", upstream_idx));
  EXPECT_EQ(1U, counter->value());
  counter = test_server_->counter(
      fmt::format("cluster.cluster_{}.thrift.upstream_resp_error", upstream_idx));
  EXPECT_EQ(1U, counter->value());
}

TEST_P(ThriftConnManagerIntegrationTest, Exception) {
  DISABLE_UNDER_WINDOWS; // https://github.com/envoyproxy/envoy/issues/21017
  initializeCall(DriverMode::Exception);

  IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("listener_0"));
  ASSERT_TRUE(tcp_client->write(request_bytes_.toString()));

  FakeUpstream* expected_upstream = getExpectedUpstream(false);
  FakeRawConnectionPtr fake_upstream_connection;
  ASSERT_TRUE(expected_upstream->waitForRawConnection(fake_upstream_connection));
  std::string data;
  ASSERT_TRUE(fake_upstream_connection->waitForData(request_bytes_.length(), &data));
  Buffer::OwnedImpl upstream_request(data);
  EXPECT_EQ(request_bytes_.toString(), upstream_request.toString());

  ASSERT_TRUE(fake_upstream_connection->write(response_bytes_.toString()));

  tcp_client->waitForData(response_bytes_.toString());
  tcp_client->close();

  EXPECT_TRUE(TestUtility::buffersEqual(Buffer::OwnedImpl(tcp_client->data()), response_bytes_));

  Stats::CounterSharedPtr counter = test_server_->counter("thrift.thrift_stats.request_call");
  EXPECT_EQ(1U, counter->value());
  int upstream_idx = getExpectedUpstreamIdx(false);
  counter = test_server_->counter(
      fmt::format("cluster.cluster_{}.thrift.upstream_rq_call", upstream_idx));
  EXPECT_EQ(1U, counter->value());
  counter = test_server_->counter("thrift.thrift_stats.response_exception");
  EXPECT_EQ(1U, counter->value());
  counter = test_server_->counter(
      fmt::format("cluster.cluster_{}.thrift.upstream_resp_exception", upstream_idx));
  EXPECT_EQ(1U, counter->value());
}

TEST_P(ThriftConnManagerIntegrationTest, EarlyClose) {
  initializeCall(DriverMode::Success);

  const std::string partial_request =
      request_bytes_.toString().substr(0, request_bytes_.length() - 5);

  FakeUpstream* expected_upstream = getExpectedUpstream(false);

  IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("listener_0"));
  ASSERT_TRUE(tcp_client->write(partial_request));
  tcp_client->close();

  FakeRawConnectionPtr fake_upstream_connection;
  ASSERT_TRUE(expected_upstream->waitForRawConnection(fake_upstream_connection));

  test_server_->waitForCounterGe("thrift.thrift_stats.cx_destroy_remote_with_active_rq", 1);

  Stats::CounterSharedPtr counter =
      test_server_->counter("thrift.thrift_stats.cx_destroy_remote_with_active_rq");
  EXPECT_EQ(1U, counter->value());
}

// Tests when the downstream client closes before completing a request but an upstream has already
// been connected/assigned.
TEST_P(ThriftConnManagerIntegrationTest, EarlyCloseWithUpstream) {
  initializeCall(DriverMode::Success);

  const std::string partial_request =
      request_bytes_.toString().substr(0, request_bytes_.length() - 5);

  IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("listener_0"));
  ASSERT_TRUE(tcp_client->write(partial_request));

  FakeUpstream* expected_upstream = getExpectedUpstream(false);
  FakeRawConnectionPtr fake_upstream_connection;
  ASSERT_TRUE(expected_upstream->waitForRawConnection(fake_upstream_connection));

  tcp_client->close();

  test_server_->waitForCounterGe("thrift.thrift_stats.cx_destroy_remote_with_active_rq", 1);

  Stats::CounterSharedPtr counter =
      test_server_->counter("thrift.thrift_stats.cx_destroy_remote_with_active_rq");
  EXPECT_EQ(1U, counter->value());
}

// Regression test for https://github.com/envoyproxy/envoy/issues/9037.
TEST_P(ThriftConnManagerIntegrationTest, EarlyUpstreamClose) {
  initializeCall(DriverMode::Success);

  const std::string partial_request =
      request_bytes_.toString().substr(0, request_bytes_.length() - 5);

  IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("listener_0"));
  ASSERT_TRUE(tcp_client->write(request_bytes_.toString()));

  FakeUpstream* expected_upstream = getExpectedUpstream(false);
  FakeRawConnectionPtr fake_upstream_connection;
  ASSERT_TRUE(expected_upstream->waitForRawConnection(fake_upstream_connection));

  std::string data;
  ASSERT_TRUE(fake_upstream_connection->waitForData(request_bytes_.length(), &data));
  Buffer::OwnedImpl upstream_request(data);
  EXPECT_EQ(request_bytes_.toString(), upstream_request.toString());

  ASSERT_TRUE(fake_upstream_connection->close());

  tcp_client->waitForDisconnect();

  EXPECT_THAT(tcp_client->data(), HasSubstr("connection failure"));

  Stats::CounterSharedPtr counter = test_server_->counter("thrift.thrift_stats.request_call");
  EXPECT_EQ(1U, counter->value());
  int upstream_idx = getExpectedUpstreamIdx(false);
  counter = test_server_->counter(
      fmt::format("cluster.cluster_{}.thrift.upstream_rq_call", upstream_idx));
  EXPECT_EQ(1U, counter->value());
  counter = test_server_->counter("thrift.thrift_stats.response_exception");
  EXPECT_EQ(1U, counter->value());
}

TEST_P(ThriftConnManagerIntegrationTest, Oneway) {
  initializeOneway();

  IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("listener_0"));
  ASSERT_TRUE(tcp_client->write(request_bytes_.toString()));

  FakeUpstream* expected_upstream = getExpectedUpstream(true);
  FakeRawConnectionPtr fake_upstream_connection;
  ASSERT_TRUE(expected_upstream->waitForRawConnection(fake_upstream_connection));
  std::string data;
  ASSERT_TRUE(fake_upstream_connection->waitForData(request_bytes_.length(), &data));
  Buffer::OwnedImpl upstream_request(data);
  EXPECT_TRUE(TestUtility::buffersEqual(upstream_request, request_bytes_));
  EXPECT_EQ(request_bytes_.toString(), upstream_request.toString());

  tcp_client->close();

  Stats::CounterSharedPtr counter = test_server_->counter("thrift.thrift_stats.request_oneway");
  EXPECT_EQ(1U, counter->value());
}

TEST_P(ThriftConnManagerIntegrationTest, OnewayEarlyClose) {
  initializeOneway();

  IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("listener_0"));
  ASSERT_TRUE(tcp_client->write(request_bytes_.toString()));
  tcp_client->close();

  FakeUpstream* expected_upstream = getExpectedUpstream(true);
  FakeRawConnectionPtr fake_upstream_connection;
  ASSERT_TRUE(expected_upstream->waitForRawConnection(fake_upstream_connection));
  std::string data;
  ASSERT_TRUE(fake_upstream_connection->waitForData(request_bytes_.length(), &data));
  Buffer::OwnedImpl upstream_request(data);
  EXPECT_EQ(request_bytes_.toString(), upstream_request.toString());

  Stats::CounterSharedPtr counter = test_server_->counter("thrift.thrift_stats.request_oneway");
  EXPECT_EQ(1U, counter->value());
}

TEST_P(ThriftConnManagerIntegrationTest, OnewayEarlyClosePartialRequest) {
  initializeOneway();

  const std::string partial_request =
      request_bytes_.toString().substr(0, request_bytes_.length() - 1);

  FakeUpstream* expected_upstream = getExpectedUpstream(true);

  IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("listener_0"));
  ASSERT_TRUE(tcp_client->write(partial_request));
  tcp_client->close();

  FakeRawConnectionPtr fake_upstream_connection;
  ASSERT_TRUE(expected_upstream->waitForRawConnection(fake_upstream_connection));

  test_server_->waitForCounterGe("thrift.thrift_stats.cx_destroy_remote_with_active_rq", 1);

  Stats::CounterSharedPtr counter =
      test_server_->counter("thrift.thrift_stats.cx_destroy_remote_with_active_rq");
  EXPECT_EQ(1U, counter->value());
}

} // namespace ThriftProxy
} // namespace NetworkFilters
} // namespace Extensions
} // namespace Envoy


text:
'''
Take HTML input from either specified file(s), or STDIN and replace all of the
  images with embedded base64, and embed all the linked JS and CSS.
This allows the HTML file to be distributed as a standalone file.
The resulting HTML is printed to STDOUT.
Relative paths are from the CWD, not from the any input files.
'''

import sys

def embed_raster(filename, img_format):
    '''Take image path and return HTML encode string.
Source filename should be a relative or absolute path/URL.
Image format should be a string like 'png', or 'jpg'.
    '''
    if int(sys.version[0]) < 3:
        from urllib import quote
    else:
        from urllib.parse import quote
    import base64
    img = open(filename, "rb").read()
    img_b64 = base64.b64encode(img)
    encoded = quote(img_b64)
    return 'data:image/%s;base64,%s' % (img_format, encoded)

def embed_svg(filename):
    '''Take image path and return SVG string.
Source filename should be a relative or absolute path/URL.
    '''
    return open(filename, "r").read()

def embed_css(filename):
    '''Take stylesheet path and return CSS string.
Source filename should be a relative or absolute path/URL.
    '''
    return '<style type="text/css">%s</style>' % open(filename, "r").read()

def embed_js(filename):
    '''Take script path and return JS string.
Source filename should be a relative or absolute path/URL.
    '''
    return '<script type="text/javascript">%s</script>' % open(filename, "r").read()

def html_unlink(s=''):
    '''Take an HTML string and return it with linked features embedded.
PNG and JPG files are embedded as data URIs.
SVG files are embedded directly.
CSS links are embedded directly in <style> tags.
External JS scripts are embedded directly in <script> tags.
    '''
    import re

    # Find all link tags and the href attributes.
    # Assumes <link ... /> tags which have no children.
    # Ignores other attributes and relies on .css file extension.
    link_re = re.compile(r'(<link\s+[^>]*href=[\'"]?([^\'" ]+)[^>]*>)')
    i = 0
    while i < len(s):
        link_match = link_re.search(s, i)
        if link_match == None: break
        i = link_match.end(0)
        href_val = link_match.group(2)
        extension = href_val[-4:].lower()
        if extension == '.css':
            link_start = link_match.start(0)
            link_end = link_match.end(0)
            s_pre = s[:link_start]
            s_post = s[link_end:]
            new_link = embed_css(href_val)
            i = link_start + len(new_link) # Skip regex over new data.
            s = ''.join([s_pre, new_link, s_post])

    # Find all script tags with src attributes.
    # Assumes <script ... /> tags which have no children, as per HTML standard.
    # Ignores other attributes and relies on .js file extension.
    script_re = re.compile(r'(<script\s+[^>]*src=[\'"]?([^\'" ]+)[^>]*>)')
    i = 0
    while i < len(s):
        script_match = script_re.search(s, i)
        if script_match == None: break
        i = script_match.end(0)
        src_val = script_match.group(2)
        extension = src_val[-3:].lower()
        if extension == '.js':
            script_start = script_match.start(0)
            script_end = script_match.end(0)
            s_pre = s[:script_start]
            s_post = s[script_end:]
            new_script = embed_js(src_val)
            i = script_start + len(new_script) # Skip regex over new data.
            s = ''.join([s_pre, new_script, s_post])

    # Find all img tags and the src attributes.
    # Assumes <img ... /> tags which have no children.
    img_re = re.compile(r'(<img\s+[^>]*src=[\'"]?([^\'" ]+)[^>]*>)')
    i = 0
    while i < len(s):
        img_match = img_re.search(s, i)
        if img_match == None: break
        i = img_match.end(0)
        src_val = img_match.group(2)
        extension = src_val[-4:].lower()

        # Embed SVGs.
        if extension == '.svg':
            img_start = img_match.start(0)
            img_end = img_match.end(0)
            s_pre = s[:img_start]
            s_post = s[img_end:]
            new_img = embed_svg(src_val)
            i = img_start + len(new_img) # Skip regex over new data.
            s = ''.join([s_pre, new_img, s_post])

        # Embed PNGs and JPGs.
        # Anything else is ignored.
        elif extension in ['.png', '.jpg']:
            src_start = img_match.start(2)
            src_end = img_match.end(2)
            s_pre = s[:src_start]
            s_post = s[src_end:]
            new_src = embed_raster(src_val, extension[1:])
            i += len(new_src) - len(src_val) # Skip regex over new data.
            s = ''.join([s_pre, new_src, s_post])
    return s

if __name__ == '__main__':

    # Build command line interface.
    import argparse
    parser = argparse.ArgumentParser()

    parser.add_argument('input',
                        nargs='*',
                        default='STDIN',
                        help='HTML input')
    args = vars(parser.parse_args())

    # Read input from STDIN or files into a single string.
    import fileinput
    if args['input'] == 'STDIN':
        input_src = fileinput.input()
    else:
        input_src = fileinput.input(args['input'])
    input_str = ''.join(input_src)

    # Process the input and put it on STDOUT.
    print(html_unlink(input_str))


text:
require 'cgi'
require 'open-uri'

module Alipay
  module Service
    GATEWAY_URL = 'https://mapi.alipay.com/gateway.do'

    CREATE_PARTNER_TRADE_BY_BUYER_REQUIRED_OPTIONS = %w( service partner _input_charset out_trade_no subject payment_type logistics_type logistics_fee logistics_payment seller_email price quantity )
    # alipayescow
    def self.create_partner_trade_by_buyer_url(options)
      options = {
        'service'        => 'create_partner_trade_by_buyer',
        '_input_charset' => 'utf-8',
        'partner'        => Alipay.pid,
        'seller_email'   => Alipay.seller_email,
        'payment_type'   => '1'
      }.merge(Utils.stringify_keys(options))

      check_required_options(options, TRADE_CREATE_BY_BUYER_REQUIRED_OPTIONS)

      "#{GATEWAY_URL}?#{query_string(options)}"
    end

    TRADE_CREATE_BY_BUYER_REQUIRED_OPTIONS = %w( service partner _input_charset out_trade_no subject payment_type logistics_type logistics_fee logistics_payment seller_email price quantity )
    # alipaydualfun
    def self.trade_create_by_buyer_url(options = {})
      options = {
        'service'        => 'trade_create_by_buyer',
        '_input_charset' => 'utf-8',
        'partner'        => Alipay.pid,
        'seller_email'   => Alipay.seller_email,
        'payment_type'   => '1'
      }.merge(Utils.stringify_keys(options))

      check_required_options(options, TRADE_CREATE_BY_BUYER_REQUIRED_OPTIONS)

      "#{GATEWAY_URL}?#{query_string(options)}"
    end

    CREATE_DIRECT_PAY_BY_USER_REQUIRED_OPTIONS = %w( service partner _input_charset out_trade_no subject payment_type seller_email )
    # direct
    def self.create_direct_pay_by_user_url(options)
      options = {
        'service'        => 'create_direct_pay_by_user',
        '_input_charset' => 'utf-8',
        'partner'        => Alipay.pid,
        'seller_email'   => Alipay.seller_email,
        'payment_type'   => '1'
      }.merge(Utils.stringify_keys(options))

      check_required_options(options, CREATE_DIRECT_PAY_BY_USER_REQUIRED_OPTIONS)

      if options['total_fee'].nil? and (options['price'].nil? || options['quantity'].nil?)
        warn("Ailpay Warn: total_fee or (price && quantiry) must have one")
      end

      "#{GATEWAY_URL}?#{query_string(options)}"
    end

    CREATE_REFUND_URL_REQUIRED_OPTIONS = %w( batch_no data notify_url )
    # 支付宝即时到帐批量退款有密接口(此为异步接口,有密指通过此接口打开 url 后需要用户输入支付宝的支付密码进行退款)
    def self.create_refund_url(options)
      options = Utils.stringify_keys(options)
      check_required_options(options, CREATE_REFUND_URL_REQUIRED_OPTIONS)

      data = options.delete('data')
      detail_data = data.map do|item|
        item = Utils.stringify_keys(item)
        "#{item['trade_no']}^#{item['amount']}^#{item['reason']}"
      end.join('#')

      options = {
        'service'        => 'refund_fastpay_by_platform_pwd',  # 接口名称
        '_input_charset' => 'utf-8',
        'partner'        => Alipay.pid,
        'seller_email'   => Alipay.seller_email,
        'refund_date'    => Time.now.strftime('%Y-%m-%d %H:%M:%S'), # 申请退款时间
        'batch_num'      => data.size,                              # 总笔数
        'detail_data'    => detail_data                             # 转换后的单笔数据集字符串
      }.merge(options)

      "#{GATEWAY_URL}?#{query_string(options)}"
    end

    SEND_GOODS_CONFIRM_BY_PLATFORM_REQUIRED_OPTIONS = %w( service partner _input_charset trade_no logistics_name )
    def self.send_goods_confirm_by_platform(options)
      options = {
        'service'        => 'send_goods_confirm_by_platform',
        'partner'        => Alipay.pid,
        '_input_charset' => 'utf-8'
      }.merge(Utils.stringify_keys(options))

      check_required_options(options, SEND_GOODS_CONFIRM_BY_PLATFORM_REQUIRED_OPTIONS)

      if options['transport_type'].nil? and options['create_transport_type'].nil?
        warn("Ailpay Warn: transport_type or create_transport_type must have one")
      end

      open("#{GATEWAY_URL}?#{query_string(options)}").read
    end

    def self.query_string(options)
      options.merge('sign_type' => 'MD5', 'sign' => Alipay::Sign.generate(options)).map do |key, value|
        "#{CGI.escape(key.to_s)}=#{CGI.escape(value.to_s)}"
      end.join('&')
    end

    def self.check_required_options(options, names)
      names.each do |name|
        warn("Ailpay Warn: missing required option: #{name}") unless options.has_key?(name)
      end
    end
  end
end


text:
namespace {

const int kMaxSymbolNameLength = 128;

class DbgHelp {
 public:
  DbgHelp(HANDLE process = nullptr)
   : module_(LoadLibrary("DbgHelp.dll")),
     process_(process),
     initialized_(false)
  {
    if (process_ == nullptr) {
      process_ = GetCurrentProcess();
    }
    if (module_ != nullptr) {
      InitFunctions();
      if (SymInitialize != nullptr) {
        initialized_ = SymInitialize(process_, nullptr, TRUE) != FALSE;
      }
    }
  }

  DbgHelp(const DbgHelp &) = delete;
  DbgHelp &operator=(const DbgHelp &) = delete;

  ~DbgHelp() {
    if (module_ != nullptr) {
      if (initialized_ && SymCleanup != nullptr) {
        SymCleanup(process_);
      }
      FreeLibrary(module_);
    }
  }

  typedef BOOL (WINAPI *SymInitializePtr)(
    HANDLE hProcess,
    PCSTR UserSearchPath,
    BOOL fInvadeProcess
  );
  SymInitializePtr SymInitialize;

  typedef BOOL (WINAPI *SymCleanupPtr)(HANDLE hProcess);
  SymCleanupPtr SymCleanup;

  typedef BOOL (WINAPI *SymFromAddrPtr)(
    HANDLE hProcess,
    DWORD64 Address,
    PDWORD64 Displacement,
    PSYMBOL_INFO Symbol
  );
  SymFromAddrPtr SymFromAddr;

  typedef DWORD (WINAPI *SymGetOptionsPtr)();
  SymGetOptionsPtr SymGetOptions;

  typedef BOOL (WINAPI *SymSetOptionsPtr)(DWORD SymOptions);
  SymSetOptionsPtr SymSetOptions;

  typedef BOOL (WINAPI *SymGetModuleInfo64Ptr)(
    HANDLE hProcess,
    DWORD64 dwAddr,
    PIMAGEHLP_MODULE64 ModuleInfo
  );
  SymGetModuleInfo64Ptr SymGetModuleInfo64;

  typedef BOOL (WINAPI *StackWalk64Ptr)(
    DWORD MachineType,
    HANDLE hProcess,
    HANDLE hThread,
    LPSTACKFRAME64 StackFrame,
    LPVOID ContextRecord,
    PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
    PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
    PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
    PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
  );
  StackWalk64Ptr StackWalk64;

  bool is_loaded() const {
    return module_ != nullptr;
  }

  bool is_initialized() const {
    return initialized_;
  }

  void InitFunctions() {
    #define INIT_FUNC(Name) Name = (Name##Ptr)GetProcAddress(module_, #Name);
    INIT_FUNC(SymInitialize);
    INIT_FUNC(SymFromAddr);
    INIT_FUNC(SymCleanup);
    INIT_FUNC(SymGetOptions);
    INIT_FUNC(SymSetOptions);
    INIT_FUNC(SymGetModuleInfo64);
    INIT_FUNC(StackWalk64);
    #undef INIT_FUNC
  }

 private:
  HMODULE module_;
  HANDLE process_;
  bool initialized_;
};

} // anonymous namespace

void GetStackTrace(std::vector<StackFrame> &frames, void *context_ptr) {
  CONTEXT context = {0};
  if (context_ptr != nullptr) {
    context = *reinterpret_cast<PCONTEXT>(context_ptr);
  } else {
    RtlCaptureContext(&context);
  }

  HANDLE process = GetCurrentProcess();
  DbgHelp dbghelp(process);
  if (!dbghelp.is_loaded()) {
    return;
  }

  STACKFRAME64 stack_frame;
  ZeroMemory(&stack_frame, sizeof(stack_frame));

  // http://stackoverflow.com/a/136942/249230
  stack_frame.AddrPC.Offset = context.Eip;
  stack_frame.AddrReturn.Offset = context.Eip;
  stack_frame.AddrPC.Mode = AddrModeFlat;
  stack_frame.AddrFrame.Offset = context.Ebp;
  stack_frame.AddrFrame.Mode = AddrModeFlat;
  stack_frame.AddrStack.Offset = context.Esp;
  stack_frame.AddrStack.Mode = AddrModeFlat;

  if (dbghelp.StackWalk64 == nullptr) {
    return;
  }

  SYMBOL_INFO *symbol = nullptr;

  if (dbghelp.is_initialized()) {
    SIZE_T size = sizeof(SYMBOL_INFO) + kMaxSymbolNameLength + 1;
    DWORD flags = HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS;
    SYMBOL_INFO *symbol = static_cast<SYMBOL_INFO*>(HeapAlloc(GetProcessHeap(),
                                                              flags,
                                                              size));
    if (symbol == nullptr) {
      return;
    }

    symbol->SizeOfStruct = sizeof(*symbol);
    symbol->MaxNameLen = kMaxSymbolNameLength;

    if (dbghelp.SymGetOptions != nullptr && dbghelp.SymSetOptions != nullptr) {
      DWORD options = dbghelp.SymGetOptions();
      options |= SYMOPT_FAIL_CRITICAL_ERRORS;
      dbghelp.SymSetOptions(options);
    }
  }

  while (true) {
    DWORD64 address = stack_frame.AddrReturn.Offset;
    if (address == 0 || address & 0x80000000) {
      break;
    }

    bool have_symbols = true;
    if (dbghelp.SymGetModuleInfo64) {
      IMAGEHLP_MODULE64 module;
      ZeroMemory(&module, sizeof(IMAGEHLP_MODULE64));
      module.SizeOfStruct = sizeof(IMAGEHLP_MODULE64);
      if (dbghelp.SymGetModuleInfo64(process, address, &module)) {
        if (!module.GlobalSymbols) {
          have_symbols = false;
        }
      }
    }

    const char *name = "";
    if (have_symbols) {
      if (dbghelp.is_initialized()
          && dbghelp.SymFromAddr != nullptr
          && symbol != nullptr) {
        if (dbghelp.SymFromAddr(process, address, nullptr, symbol)) {
          name = symbol->Name;
        }
      }
    }

    frames.push_back(StackFrame(reinterpret_cast<void*>(address), name));

    if (!dbghelp.StackWalk64(IMAGE_FILE_MACHINE_I386,
                             process,
                             GetCurrentThread(),
                             &stack_frame,
                             (PVOID)&context,
                             nullptr,
                             nullptr,
                             nullptr,
                             nullptr)) {
      break;
    }
  }

  HeapFree(GetProcessHeap(), 0, symbol);
  dbghelp.SymCleanup(process);
}


text:
hg pull -u
REM %comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"" x86
call "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"
msbuild "Bloom VS2010.sln"
cd output/debug
Bloom.exe


text:
from django.db import models
from archfinch.main.models import Item, SlicedRawManager
from archfinch.users.models import User
from archfinch.links.thresholds import *

class LinkManager(SlicedRawManager):
    def recommended_generic(self, category=None, tags=None, new=False):
        '''
        Fetches links recommended generally (not for a specific user).
        '''

        where = []
        params = {}

        if category is not None:
            where.append('mi.category_id = %(category_id)s')
            params['category_id'] = category.id

        if tags:
            for tag in tags:
                where.append('EXISTS (SELECT 1 FROM main_tagged mtgd WHERE mi.id = mtgd.item_id AND mtgd.tag_id = %d)' % (int(tag.id)))

        elif not new:
            # front page
            where.append('wilson_score(mi.id, true) >= %(threshold_frontpage)s')
            params['threshold_frontpage'] = threshold_frontpage

        if where:
            where = 'WHERE '+' AND '.join(where)
        else:
            where = ''

        # Select items in order of their recommendation to self
        #
        # recommendation =
        #    sum (rating-3)*similarity for all similar users
        #
        #    where
        #      rating: what the user has rated the item
        #      similarity: similarity between the user and self
        recommended = Link.objects.slicedraw("""
            SELECT * FROM (SELECT mi.id, mi.category_id, mi.parent_id, mi.name, ll.item_ptr_id, ll.time,

             mc.element_singular AS category_element
             FROM main_item mi
             INNER JOIN main_category mc
              ON mc.id=mi.category_id
             INNER JOIN links_link ll
              ON ll.item_ptr_id=mi.id

             """+where+"""
            ORDER BY time DESC) AS recommended""",
            params)

        return recommended

    def recommended(self, user, category=None, category_id=None, tags=None, followed=False, new=False):
        '''
        Fetches links recommended for the user.
        '''

        where = ''
        joins = ''
        params = {'user_id': user.id}
        if category is not None and category:
            category_id = category.id

        if category_id is not None:
            where += ' AND mi.category_id = %(category_id)s'
            params['category_id'] = category_id

        followed_or = False
        show_submissions = False

        if tags:
            for tag in tags:
                where += ' AND EXISTS (SELECT 1 FROM main_tagged mtgd WHERE mi.id = mtgd.item_id AND mtgd.tag_id = %d)' % (int(tag.id))

        elif not followed and not new:
            # front page
            where += ' AND wilson_score(mi.id, true) >= %(threshold_frontpage)s'
            params['threshold_frontpage'] = threshold_frontpage

            # add the user's follows to their frontpage
            followed = True
            followed_or = True
            show_submissions = True

        if followed and user.tagfollow_set.exists():
            if followed_or:
                where += ' OR'
            else:
                where += ' AND'
            where += ' EXISTS (SELECT 1 FROM main_tagged mtgd WHERE mi.id = mtgd.item_id AND mtgd.tag_id in %(followed_tag_ids)s)'
            params['followed_tag_ids'] = tuple(map(lambda follow: follow.tag.id, user.tagfollow_set.all()))

        if show_submissions:
            where += ' OR mi.submitter_id = %(user_id)s'

        # Select items in order of their recommendation to self
        #
        # recommendation =
        #    sum (rating-3)*similarity for all similar users
        #
        #    where
        #      rating: what the user has rated the item
        #      similarity: similarity between the user and self
        recommended = Link.objects.slicedraw("""
            SELECT mi.id, mi.category_id, mi.parent_id, mi.name, ll.item_ptr_id, ll.time,
             mis.comment_count, mis.popular_tags as _popular_tags, url, image, submitter_id,
             au.username AS submitter_username,

             COALESCE((SELECT rating FROM main_opinion mo WHERE mo.user_id=%(user_id)s AND mo.item_id=mi.id)) AS rating,

             mc.element_singular AS category_element
             FROM main_item mi
             INNER JOIN main_category mc
              ON mc.id=mi.category_id
             INNER JOIN links_link ll
              ON ll.item_ptr_id=mi.id
             INNER JOIN main_itemstats mis
              ON mi.id=mis.item_id
             INNER JOIN auth_user au
              ON au.id=mi.submitter_id
            WHERE
             NOT EXISTS (SELECT 1 FROM main_tagblock mtb, main_tagged mtgd WHERE mtgd.tag_id=mtb.tag_id AND mtb.user_id=%(user_id)s AND mtgd.item_id=ll.item_ptr_id)
             """+where+"""
            ORDER BY time DESC
            """,
            params)

        return recommended

class ImageURLField(models.CharField):
    """Image URL field, stored as url,width,height in the database"""
    __metaclass__ = models.SubfieldBase

    def to_python(self, value):
        if value is None: return
        if not isinstance(value, basestring): return value
        fields = value.split(',')
        if len(fields) < 3:
            return {'url': fields[0]}
        return {'url': fields[0], 'width': int(fields[1]), 'height': int(fields[2])}

    def get_prep_value(self, value):
        if value is None: return
        try:
            return ','.join([value['url'], str(value['width']), str(value['height'])])
        except KeyError:
            return value['url']

class Link(Item):
    url = models.URLField(verify_exists=False, max_length=1000, blank=True, null=True)
    time = models.DateTimeField(auto_now_add=True, unique=False)

    thumbnail = ImageURLField(max_length=1000, blank=True, null=True)
    image = ImageURLField(max_length=1000, blank=True, null=True)

    html = models.TextField(max_length=1000, blank=True, null=True)

    objects = LinkManager()

    def age(self):
        import datetime
        age = (datetime.datetime.now() - self.time)
        return age.seconds+age.days*60*60*24

    def views(self):
        age = self.age()
        multiplier = 113 + self.id % 20
        if age < 15*60:
            views = (age/900.)**2 * multiplier
        elif age < 60*60*24:
            views = (age/900.) * multiplier
        else:
            views = 96 * multiplier + age/360.

        return int(views)


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

package org.chromium.chrome.browser.webapps;

import static org.junit.Assert.assertEquals;

import android.content.Intent;
import android.net.Uri;

import androidx.test.filters.LargeTest;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.runner.RunWith;

import org.chromium.base.CommandLine;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.browser.browserservices.intents.WebappConstants;
import org.chromium.chrome.browser.browserservices.ui.controller.CurrentPageVerifier.VerificationStatus;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.browser.test.MockCertVerifierRuleAndroid;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.content_public.common.ContentSwitches;

/**
 * Tests the {@link CurrentPageVerifier} integration with PWAs added to the homescreen.
 */
@RunWith(ChromeJUnit4ClassRunner.class)
@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE})
public final class AddToHomescreenCurrentPageVerifierTest {
    public final WebappActivityTestRule mActivityTestRule = new WebappActivityTestRule();

    public MockCertVerifierRuleAndroid mCertVerifierRule =
            new MockCertVerifierRuleAndroid(0 /* net::OK */);

    @Rule
    public RuleChain mRuleChain = RuleChain.emptyRuleChain()
                                          .around(mActivityTestRule)
                                          .around(mCertVerifierRule);

    @Before
    public void setUp() {
        mActivityTestRule.getEmbeddedTestServerRule().setServerUsesHttps(true);
        Uri mapToUri =
                Uri.parse(mActivityTestRule.getEmbeddedTestServerRule().getServer().getURL("/"));
        CommandLine.getInstance().appendSwitchWithValue(
                ContentSwitches.HOST_RESOLVER_RULES, "MAP * " + mapToUri.getAuthority());
    }

    private void launchWebapp(String url) {
        Intent launchIntent = mActivityTestRule.createIntent();
        launchIntent.putExtra(WebappConstants.EXTRA_URL, url);
        mActivityTestRule.startWebappActivity(launchIntent);
    }

    private @VerificationStatus int getCurrentPageVerifierStatus() {
        WebappActivity webappActivity = mActivityTestRule.getActivity();
        return webappActivity.getComponent().resolveCurrentPageVerifier().getState().status;
    }

    /**
     * Tests that {@link CurrentPageVerifier} verification succeeds if the webapp navigates to a
     * page within the webapp origin.
     */
    @Test
    @LargeTest
    @Feature({"Webapps"})
    public void testInScope() {
        String page = "https://foo.com/chrome/test/data/android/customtabs/cct_header.html";
        String otherPageInScope = "https://foo.com/chrome/test/data/android/simple.html";
        launchWebapp(page);

        mActivityTestRule.loadUrl(otherPageInScope);
        assertEquals(VerificationStatus.SUCCESS, getCurrentPageVerifierStatus());
    }

    /**
     * Tests that {@link CurrentPageVerifier} verification fails if the webapp navigates to a
     * page with a different origin than the webapp.
     */
    @Test
    @LargeTest
    @Feature({"Webapps"})
    public void testDifferentOrigin() {
        String page = "https://foo.com/chrome/test/data/android/simple.html";
        String pageDifferentOrigin = "https://bar.com/chrome/test/data/android/simple.html";
        launchWebapp(page);

        mActivityTestRule.loadUrl(pageDifferentOrigin, 10 /* secondsToWait */);
        assertEquals(VerificationStatus.FAILURE, getCurrentPageVerifierStatus());
    }
}


text:
from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_AboutDialog(object):
    def setupUi(self, AboutDialog):
        AboutDialog.setObjectName(_fromUtf8("AboutDialog"))
        AboutDialog.resize(421, 288)
        AboutDialog.setStyleSheet(_fromUtf8("background: rgb(10, 80, 111);"))
        AboutDialog.setModal(True)
        self.buttonBox = QtGui.QDialogButtonBox(AboutDialog)
        self.buttonBox.setGeometry(QtCore.QRect(70, 250, 341, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
        self.aboutInfo = QtGui.QLabel(AboutDialog)
        self.aboutInfo.setGeometry(QtCore.QRect(20, 30, 371, 211))
        self.aboutInfo.setStyleSheet(_fromUtf8("color:white;background: rgb(10, 80, 111);"))
        self.aboutInfo.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.aboutInfo.setObjectName(_fromUtf8("aboutInfo"))

        self.retranslateUi(AboutDialog)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), AboutDialog.accept)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), AboutDialog.reject)
        QtCore.QMetaObject.connectSlotsByName(AboutDialog)

    def retranslateUi(self, AboutDialog):
        AboutDialog.setWindowTitle(QtGui.QApplication.translate("AboutDialog", "About Registron", None, QtGui.QApplication.UnicodeUTF8))
        self.aboutInfo.setText(QtGui.QApplication.translate("AboutDialog", "

About Registron

Registron is a speech based student registration system.

It uses the Python pyttsx module for providing a voice.

Graphical Interface built with Qt4

Website: https://bl4ckdu5t.github.io/registron

© 2014 ostrich-dev works

", None, QtGui.QApplication.UnicodeUTF8))

import app_rc


text:
package org.apache.guacamole.auth.jdbc.permission;

import org.apache.guacamole.net.auth.permission.ObjectPermission;

/**
 * Object representation of an object-related Guacamole permission, as
 * represented in the database.
 */
public class ObjectPermissionModel extends PermissionModel<ObjectPermission.Type> {

    /**
     * The unique identifier of the object affected by this permission.
     */
    private String objectIdentifier;

    /**
     * Creates a new, empty object permission.
     */
    public ObjectPermissionModel() {
    }

    /**
     * Returns the unique identifier of the object affected by this permission.
     *
     * @return
     *     The unique identifier of the object affected by this permission.
     */
    public String getObjectIdentifier() {
        return objectIdentifier;
    }

    /**
     * Sets the unique identifier of the object affected by this permission.
     *
     * @param objectIdentifier
     *     The unique identifier of the object affected by this permission.
     */
    public void setObjectIdentifier(String objectIdentifier) {
        this.objectIdentifier = objectIdentifier;
    }

}


text:
require "test_helper"

class Folio::Console::PrivateAttachments::SingleDropzoneCellTest < Folio::Console::CellTest
  class PageWithAttachments < Folio::Page
    has_one :private_attachment, class_name: "Folio::PrivateAttachment",
                                 as: :attachmentable,
                                 foreign_key: :attachmentable_id,
                                 dependent: :destroy

    accepts_nested_attributes_for :private_attachment, allow_destroy: true,
                                                       reject_if: :all_blank
  end

  test "show" do
    attachmentable = PageWithAttachments.create!(title: "PageWithAttachments")

    html = cell("folio/console/private_attachments/single_dropzone",
                attachmentable,
                name: "private_attachment",
                type: "Folio::PrivateAttachment",
                minimal: "1").(:show)
    assert html.has_css?(".f-c-private-attachments-single-dropzone--minimal")
    assert html.has_css?(".f-c-private-attachments-single-dropzone__upload-ico")

    html = cell("folio/console/private_attachments/single_dropzone",
                attachmentable,
                name: "private_attachment",
                type: "Folio::PrivateAttachment",
                minimal: false).(:show)
    assert_not html.has_css?(".f-c-private-attachments-single-dropzone--minimal")
    assert_not html.has_css?(".f-c-private-attachments-single-dropzone__upload-ico")
    assert html.has_css?(".f-c-private-attachments-single-dropzone__upload-btn")

    Folio::PrivateAttachment.create!(
      attachmentable:,
      file: Folio::Engine.root.join("test/fixtures/folio/test.gif")
    )
    attachmentable.reload

    html = cell("folio/console/private_attachments/single_dropzone",
                attachmentable,
                name: "private_attachment",
                type: "Folio::PrivateAttachment",
                minimal: "1").(:show)
    assert_not html.has_css?(".f-c-private-attachments-single-dropzone__destroy")

    html = cell("folio/console/private_attachments/single_dropzone",
                attachmentable,
                name: "private_attachment",
                type: "Folio::PrivateAttachment",
                minimal: false).(:show)
    assert_not html.has_css?(".f-c-private-attachments-single-dropzone__upload-btn")
    assert html.has_css?(".f-c-private-attachments-single-dropzone__upload-ico")
    assert html.has_css?(".f-c-private-attachments-single-dropzone__destroy")
  end
end


text:
name: Typography bug
about: Use this report when you think Typopo is not fixing typos as you would. expect.
title: ''
labels: bug
assignees: ''

---

**Provide your original text**

/provide your example here/

**Provide how Typopo fixed your text**

/provide output here/

**Provide how you expect Typopo should fix your text**

/provide output here/

**What language is affected (choose the one that applies)**
- English
- German
- Czech
- Slovak
- Rusyn

**Any further info?**


text:
sudo apt-mark hold grub*

#remove apache2 and php in-case they are already on the base box
sudo apt-get -y remove apache2 php*

#add the PPA for PHP 7
str="\n\ndeb http://ppa.launchpad.net/ondrej/php/ubuntu trusty main\ndeb-src http://ppa.launchpad.net/ondrej/php/ubuntu trusty main\n\n"
sudo chmod 0777 /etc/apt/sources.list
sudo echo -e "$str" >> /etc/apt/sources.list
sudo chmod 0644 /etc/apt/sources.list

#Update/Upgrade apt
sudo apt-get -y update && sudo apt-get -y upgrade

#install mysql
export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get -y install mysql-server

#install applications
sudo -E apt-get -y --force-yes install git php7.0 php7.0-bcmath php7.0-cli php7.0-curl php7.0-fpm php7.0-gd php7.0-json php7.0-mbstring php7.0-mcrypt php7.0-mysql php7.0-opcache php7.0-dev php7.0-zip nginx

#change permissions of this file so PHP error reporting can be enabled
sudo chmod 0666 /etc/php/7.0/fpm/php.ini

#the string of data that will be appended to the php.ini file
str="\n\nerror_reporting = E_ALL\ndisplay_errors = On\n"

#write the string to the php.ini
sudo echo -e "$str" >> /etc/php/7.0/fpm/php.ini

sudo rm -rf /etc/nginx/sites-available/* /etc/nginx/sites-enabled/*
sudo ln -s /vagrant/vagrant-setup-files/nginx/bedshop.local.conf /etc/nginx/sites-enabled/bedshop.local.conf

#restart apache to enable mod_rewrite & SSL
sudo service nginx restart

#clean the un-required packages
sudo apt-get -y autoremove && sudo apt-get -y autoclean

#change the file permission back to their original state
sudo chmod 0644 /etc/php/7.0/fpm/php.ini

#import the sql file to the database
mysql -uroot < /vagrant/vagrant-setup-files/database/import.sql

#create the anxiety user and grant all permissions
mysql -uroot -e "CREATE USER 'framework'@'localhost' IDENTIFIED BY 'framework';"
mysql -uroot -e "GRANT ALL PRIVILEGES ON * . * TO 'framework'@'localhost';"

#remove the current www folder
sudo rm -rf /var/www

#link the vagrant folder and change the links name to www
sudo ln -s /vagrant/public /var/
sudo mv /var/public /var/www

sudo mkdir -p /var/log/framework
sudo chmod 0777 /var/log/framework
sudo touch /var/log/framework/framework.log
sudo chmod 0666 /var/log/framework/framework.log

#setup composer
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === '92102166af5abdb03f49ce52a40591073a7b859a86e8ff13338cf7db58a19f7844fbc0bb79b2773bf30791e935dbd938') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
sudo php composer-setup.php  --install-dir=/usr/local/bin --filename=composer
php -r "unlink('composer-setup.php');"


text:
package de.tudarmstadt.lt.utilities.cli;

import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.lang.StringUtils;

public class CliUtils {

	private CliUtils(){ /* DO NOT INSTANTIATE */ }

	public static void print_usage(String cmd, Options opts, String message){
		print_usage(System.err, cmd, opts, "Options:", message);
	}

	public static void print_usage_quit(String cmd, Options opts, String message, int exit_code){
		print_usage_quit(System.err, cmd, opts, "Options:", message, exit_code);
	}

	public static void print_usage(PrintStream p, String cmd, Options opts, String header, String message){
		if(message != null)
			p.println(message);
		if(opts != null)
			new HelpFormatter().printHelp(new PrintWriter(p, true), 80, "... " + cmd + " <options>", header, opts, 2, 2, "======");
	}

	public static void print_usage_quit(PrintStream p, String cmd, Options opts, String header, String message, int exit_code){
		print_usage(p, cmd, opts, header, message);
		System.exit(exit_code);
	}

	public static Map<String, String> getOptionsMap(Option[] options){
		Map<String, String> map = new HashMap<>();
		for (Option option : options) {
			if(option.getValue().contains("=")){
				String[] split = option.getValue().split("=");
				map.put(split[0], split[1]);
			}else{
				map.put(option.getLongOpt(), StringUtils.join(option.getValuesList(), ","));
			}
		}
		return map;
	}

}


text:
import Audio from './Audio';
import { Vector3 } from 'three';
import Beat from './Beat';

export default class AmbientSound extends Beat {

    constructor(name, options) {
        super(name);
        //use options to choose whether have a loop or not.
        this.source.loop = options.loop || false;

        //creating panner, we need to update on object movements.
        this.panner = Audio.context.createPanner();
        //disconnecting from main volume, then connecting to panner and main volume again
        this.volumeNode.disconnect();
        this.volumeNode.connect(this.panner);
        this.panner.connect(Audio.volume);

        //storing body
        this.body = options.body;

        //if we set up an effect in our options, we need to create a convolver node
        if (options.effect) {

            this.convolver = Audio.context.createConvolver();
            this.mixer = Audio.context.createGain();
            this.panner.disconnect();
            this.panner.connect(this.mixer);
            //creating gains
            this.plainGain = Audio.context.createGain();
            this.convolverGain = Audio.context.createGain();
            //connect mixer to new gains
            this.mixer.connect(plainGain);
            this.mixer.connect(convolverGain);

            this.plainGain.connect(Audio.volume);
            this.convolverGain.connect(Audio.volume);

            this.convolver.buffer = Audio.get(options.effect);
            this.convolverGain.gain.value = 0.7;
            this.plainGain.gain.value = 0.3;

        }
        //autoplay option
        const autoplay = options.autoplay || false;
        if (autoplay) {
            this.play();
        }
        //adding this sound to Audio
        Audio.add(this);
    }

    update(dt) {

        // In the frame handler function, get the object's position.
        this.body.updateMatrixWorld();
        const p = new Vector3();
        p.setFromMatrixPosition(this.body.matrixWorld);

        // And copy the position over to the sound of the object.
        this.panner.setPosition(p.x, p.y, p.z);
    }

}


text:
<?php

namespace NewClubsORM\map;

use \RelationMap;
use \TableMap;

/**
 * This class defines the structure of the 'quarterly_data_old' table.
 *
 *
 *
 * This map class is used by Propel to do runtime db structure discovery.
 * For example, the createSelectSql() method checks the type of a given column used in an
 * ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
 * (i.e. if it's a text column type).
 *
 * @package    propel.generator.newclubs.map
 */
class QuarterlyDataOldTableMap extends TableMap
{

	/**
	 * The (dot-path) name of this class
	 */
	const CLASS_NAME = 'newclubs.map.QuarterlyDataOldTableMap';

	/**
	 * Initialize the table attributes, columns and validators
	 * Relations are not initialized by this method since they are lazy loaded
	 *
	 * @return     void
	 * @throws     PropelException
	 */
	public function initialize()
	{
		// attributes
		$this->setName('quarterly_data_old');
		$this->setPhpName('QuarterlyDataOld');
		$this->setClassname('NewClubsORM\\QuarterlyDataOld');
		$this->setPackage('newclubs');
		$this->setUseIdGenerator(false);
		// columns
		$this->addPrimaryKey('REPORT_ID', 'ReportId', 'INTEGER', true, 10, 0);
		$this->addPrimaryKey('ORG_ID', 'OrgId', 'INTEGER', true, 10, 0);
		$this->addColumn('CLUBNAME', 'Clubname', 'VARCHAR', true, 40, '');
		$this->addColumn('MEETING_PLACE', 'MeetingPlace', 'VARCHAR', true, 40, '');
		$this->addColumn('DAY', 'Day', 'VARCHAR', true, 10, '');
		$this->addColumn('TIME', 'Time', 'VARCHAR', true, 8, '');
		$this->addColumn('ACTIVE', 'Active', 'INTEGER', true, 4, 0);
		$this->addColumn('ASSOCIATE', 'Associate', 'INTEGER', true, 4, 0);
		$this->addColumn('ATTENDANCE', 'Attendance', 'INTEGER', true, 4, 0);
		$this->addColumn('COS', 'Cos', 'INTEGER', true, 3, 0);
		$this->addColumn('CIAS', 'Cias', 'INTEGER', true, 3, 0);
		$this->addColumn('COB', 'Cob', 'INTEGER', true, 3, 0);
		$this->addColumn('COE', 'Coe', 'INTEGER', true, 3, 0);
		$this->addColumn('CLA', 'Cla', 'INTEGER', true, 3, 0);
		$this->addColumn('NTID', 'Ntid', 'INTEGER', true, 3, 0);
		$this->addColumn('GCCIS', 'Gccis', 'INTEGER', true, 3, 0);
		$this->addColumn('CAST', 'Cast', 'INTEGER', true, 3, 0);
		$this->addColumn('NONRIT', 'Nonrit', 'INTEGER', true, 3, 0);
		$this->addColumn('ONE', 'One', 'INTEGER', true, 3, 0);
		$this->addColumn('TWO', 'Two', 'INTEGER', true, 3, 0);
		$this->addColumn('THREE', 'Three', 'INTEGER', true, 3, 0);
		$this->addColumn('FOUR', 'Four', 'INTEGER', true, 3, 0);
		$this->addColumn('FIVE', 'Five', 'INTEGER', true, 3, 0);
		$this->addColumn('G', 'G', 'INTEGER', true, 3, 0);
		$this->addColumn('OTHER_YEAR', 'OtherYear', 'INTEGER', true, 3, 0);
		$this->addColumn('ASIAN', 'Asian', 'INTEGER', true, 3, 0);
		$this->addColumn('AFRICAN', 'African', 'INTEGER', true, 3, 0);
		$this->addColumn('NATIVE', 'Native', 'INTEGER', true, 3, 0);
		$this->addColumn('LATINO', 'Latino', 'INTEGER', true, 3, 0);
		$this->addColumn('CAUCASIAN', 'Caucasian', 'INTEGER', true, 3, 0);
		$this->addColumn('INTERNATIONAL', 'International', 'INTEGER', true, 3, 0);
		$this->addColumn('OTHER', 'Other', 'INTEGER', true, 3, 0);
		$this->addColumn('MALE', 'Male', 'INTEGER', true, 3, 0);
		$this->addColumn('FEMALE', 'Female', 'INTEGER', true, 3, 0);
		$this->addColumn('EVENTS', 'Events', 'CLOB', true, null, null);
		$this->addColumn('UPCOMING', 'Upcoming', 'CLOB', true, null, null);
		$this->addColumn('MEMBERS', 'Members', 'CLOB', true, null, null);
		$this->addColumn('GOALS', 'Goals', 'LONGVARCHAR', true, null, null);
		$this->addColumn('REACHGOALS', 'Reachgoals', 'LONGVARCHAR', true, null, null);
		$this->addColumn('HELP', 'Help', 'LONGVARCHAR', true, null, null);
		$this->addColumn('ACCOMPLISHMENTS', 'Accomplishments', 'LONGVARCHAR', true, null, null);
		$this->addColumn('BOARDCHANGES', 'Boardchanges', 'LONGVARCHAR', true, null, null);
		$this->addColumn('SUBMITTED_BY', 'SubmittedBy', 'VARCHAR', true, 40, '');
		$this->addColumn('ADVISOR', 'Advisor', 'VARCHAR', true, 40, '');
		// validators
	} // initialize()

	/**
	 * Build the RelationMap objects for this table relationships
	 */
	public function buildRelations()
	{
	} // buildRelations()

} // QuarterlyDataOldTableMap


text:
Memory cache filter implementation for Clyde API gateway.

> Implementation is based on [node-cache][node-cache] module.

The filter works as an in memory `<key, value>` cache. For each request it caches response content, headers and status code as the *value* and using the `url` as the *key*.

If the property `ignoreQuery=true` the *key* will contain only the `path` part of the `url` and will ignore the `query`, for example, these URLs will be treated as the same: `/some_path?param1=a&param2=b`, `/some_path?abc` or `/some_path`.

<!-- TOC depth:6 withLinks:1 updateOnSave:1 orderedList:0 -->

- [Memory Cache Filter](#memory-cache-filter)
	- [Installation](#installation)
	- [Configuration](#configuration)
	- [Examples](#examples)
		- [Global cache with default configuration](#global-cache-with-default-configuration)
		- [Provider's cache ignoring URL query part and with a TTL of 5 minutes](#providers-cache-ignoring-url-query-part-and-with-a-ttl-of-5-minutes)
	- [Notes](#notes)
- [License](#license)
<!-- /TOC -->

## Installation

`npm install clydeio-memory-cache --save`

## Configuration

The memory cache filter accepts the next set of configuration options. Note, with the exception of `ignoreQuery` property all the rest properties are the same as the [node-cache][node-cache] module, because of this, the set of properties are passed directly to the internal module reference:

- `ignoreQuery`: *(default: `false`)* ignores the query part of the `url` when computing the cache `key`. Otherwise the full `url` is used.
- `stdTTL`: *(default: `0`)* the standard ttl as number in seconds for every generated cache element.
`0` = unlimited
- `checkperiod`: *(default: `600`)* The period in seconds, as a number, used for the automatic delete check interval.
`0` = no periodic check.
**Note:** If you use `checkperiod > 0` you script will not exit at the end, because a internal timeout will always be active.
- `useClones`: *(default: `true`)* en/disable cloning of variables. If `true` you'll get a copy of the cached variable. If `false` you'll save and get just the reference.
**Note:** `true` is recommended, because it'll behave like a sever-based caching. You should set `false` if you want to save complex varibale types like functions, promises, regexp, ...

## Examples

### Global cache with default configuration

```javascript
{
  "prefilters" : [
    {
      "id" : "memory-cache",
      "path" : "clydeio-memory-cache"
    }
  ],
  "providers": [
    ...
  ]
}
```

### Provider's cache ignoring URL query part and with a TTL of 5 minutes

```javascript
{
  "providers": [
    {
      "id" : "providerA",
      "context" : "/provider",
      "target" : "http://server_providerA",

      "prefilters" : [
        {
          "id" : "memory-cache",
          "path" : "clydeio-memory-cache",
          "config" : {
            "ignoreQuery" : true,
            "stdTTL" : 300
          }
        }
      ]
    }
  ]
}
```

## Notes

- Memory cache filter must be configured as a prefilter. Its is required to capture the requests before sent to the provider.

# License

The MIT License (MIT)

Copyright (c) 2015 Antonio Santiago (@acanimal)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

[node-cache]: https://github.com/tcs-de/nodecache


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.resourcemanager.appservice.models;

/**
 * Result of Kudu deployment.
 */
public final class KuduDeploymentResult {

    private final String deploymentId;

    /**
     * Creates a KuduDeploymentResult instance.
     *
     * @param deploymentId the deployment ID.
     */
    public KuduDeploymentResult(String deploymentId) {
        this.deploymentId = deploymentId;
    }

    /**
     * @return the deployment ID. It can be {@code null} if tracking deployment is disabled.
     */
    public String deploymentId() {
        return deploymentId;
    }
}


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_ACCESSIBILITY_AX_PROGRESS_INDICATOR_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_ACCESSIBILITY_AX_PROGRESS_INDICATOR_H_

#include "third_party/blink/renderer/modules/accessibility/ax_layout_object.h"

namespace blink {

class AXObjectCacheImpl;
class HTMLProgressElement;

class AXProgressIndicator final : public AXLayoutObject {
 public:
  AXProgressIndicator(LayoutObject*, AXObjectCacheImpl&);

  AXProgressIndicator(const AXProgressIndicator&) = delete;
  AXProgressIndicator& operator=(const AXProgressIndicator&) = delete;

 private:
  ax::mojom::blink::Role NativeRoleIgnoringAria() const final;

  bool IsProgressIndicator() const override { return true; }

  bool ValueForRange(float* out_value) const override;
  bool MaxValueForRange(float* out_value) const override;
  bool MinValueForRange(float* out_value) const override;

  HTMLProgressElement* GetProgressElement() const;
  bool ComputeAccessibilityIsIgnored(IgnoredReasons* = nullptr) const override;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_ACCESSIBILITY_AX_PROGRESS_INDICATOR_H_


text:
export NODE_PATH=/usr/lib/node_modules

# Output dir of scrapped sites
OUT="/data/scrapped"

# Creates if not exists
`mkdir -p "$OUT"`

# Now scrapte-it only supports .js format
OUTPUT_EXTENSION="js"

# Iterates over all *.js files inside the /data directory
for filepath in $(ls /data/*.js);
do
  # filename of site to scrap
  file=$(basename "$filepath")
  filename="${file%.*}"
  printf "Scrapping $filename: "
  (
    # Writes the scrapped output in $OUT folder with $filename name
    node "$filepath" > "${OUT}/${filename}.${OUTPUT_EXTENSION}"
  ) > /dev/null && echo "OK" || echo "FAIL"
done


text:
package org.ovirt.engine.ui.webadmin.section.main.presenter;

import org.ovirt.engine.ui.webadmin.auth.CurrentUser;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.configure.ConfigurePopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.utils.WebUtils;
import org.ovirt.engine.ui.webadmin.widget.tab.HeadlessTabPanel.TabWidgetHandler;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.GwtEvent.Type;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.PresenterWidget;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.ContentSlot;
import com.gwtplatform.mvp.client.proxy.RevealContentHandler;
import com.gwtplatform.mvp.client.proxy.RevealRootPopupContentEvent;

public class HeaderPresenterWidget extends PresenterWidget<HeaderPresenterWidget.ViewDef> implements TabWidgetHandler, MainTabBarOffsetUiHandlers {

    public interface ViewDef extends View, TabWidgetHandler, MainTabBarOffsetUiHandlers {

        void setUserNameLabel(String userName);

        HasClickHandlers getConfigureLink();

        HasClickHandlers getLogoutLink();

        HasClickHandlers getAboutLink();

        HasClickHandlers getGuideLink();

    }

    @ContentSlot
    public static final Type<RevealContentHandler<?>> TYPE_SetSearchPanel = new Type<RevealContentHandler<?>>();

    private final CurrentUser user;
    private final SearchPanelPresenterWidget searchPanel;
    private final AboutPopupPresenterWidget aboutPopup;
    private final ConfigurePopupPresenterWidget configurePopup;

    @Inject
    public HeaderPresenterWidget(EventBus eventBus,
            ViewDef view,
            CurrentUser user,
            SearchPanelPresenterWidget searchPanel,
            AboutPopupPresenterWidget aboutPopup,
            ConfigurePopupPresenterWidget configurePopup) {
        super(eventBus, view);
        this.user = user;
        this.searchPanel = searchPanel;
        this.aboutPopup = aboutPopup;
        this.configurePopup = configurePopup;
    }

    @Override
    public void addTabWidget(Widget tabWidget, int index) {
        getView().addTabWidget(tabWidget, index);
    }

    @Override
    public void removeTabWidget(Widget tabWidget) {
        getView().removeTabWidget(tabWidget);
    }

    @Override
    public void setMainTabBarOffset(int left) {
        getView().setMainTabBarOffset(left);
    }

    @Override
    protected void onBind() {
        super.onBind();

        registerHandler(getView().getConfigureLink().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                RevealRootPopupContentEvent.fire(HeaderPresenterWidget.this, configurePopup);
            }
        }));

        registerHandler(getView().getLogoutLink().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                user.logout();
            }
        }));

        registerHandler(getView().getAboutLink().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                RevealRootPopupContentEvent.fire(HeaderPresenterWidget.this, aboutPopup);
            }
        }));

        registerHandler(getView().getGuideLink().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                String url = com.google.gwt.user.client.Window.Location
                        .getProtocol()
                        + "//"
                        + com.google.gwt.user.client.Window.Location.getHost()
                        + "/rhev-docs/en-US/html/Administration_Guide/index.html";

                WebUtils.openUrlInNewWindow("ENGINE Web Admin Documentation", url);
            }
        }));
    }

    @Override
    protected void onReveal() {
        super.onReveal();

        setInSlot(TYPE_SetSearchPanel, searchPanel);
    }

    @Override
    protected void onReset() {
        super.onReset();

        getView().setUserNameLabel(user.getUserName());
    }

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Easy Viva XMP-Generator</title>

Easy Viva XMP-Generator

Mit diesem Programm können Viva-XMP Daten für den Formularmodus des Printplus Druckportal erzeugt werden.

    <form id="xmlHead">

Head Informationen

        viva:title:  <input type="text" id="inputVivaTitle" value="">

        viva:liste:
            <select id="inputVivaListe">
                <option value="1">Liste anzeigen</option>
                <option value="0">Liste nicht anzeigen</option>
            </select>

        viva:previewWidth:  <input type="text" id="inputVivaPreviewWidth" value="680">

        viva:previewHeight:  <input type="text" id="inputVivaPreviewHeight" value="">

        viva:formWidth:  <input type="text" id="inputVivaFormWidth" value="500">

        viva:productDescription:  <input type="text" id="inputVivaProductDescription" value="$Name.Vorname$ $Name.Name$" placeholder="">

    </form>

Neues Formularfeld hinzufügen

        <select id="newValueSortOf">
            <option value="text">Textfeld</option>
            <option value="hidden">Verstecktes Feld</option>
            <option value="email">E-Mail Feld</option>
            <option value="textarea">Mehrzeiliges Formularfeld</option>
            <option value="select">Auswahlliste</option>
            <option value="upload">File-Upload</option>
        </select>
        <button id="buttonFormularErstellen" onclick="neuesFormularfeld()">Formularfeld hinzufügen</button>

    <button id="buttonXMPdateiErstellen" onclick="elementeAbrufen()">XMP-Datei erstellen</button>

Schweben

        <textarea id="clipboardText" placeholder="Clipboard ..." rows="3"></textarea>

XMP-Datei:

V.1.6.1
24.12.2016


text:
import unittest
import sys
from os.path import abspath, join, dirname
try:
    from StringIO import StringIO
except:
    from io import StringIO
from collections import defaultdict
import names
from names.main import main

full_path = lambda filename: abspath(join(dirname(__file__), filename))

class patch_stdout(object):
    def __init__(self):
        self.stdout = StringIO()
        self.real_stdout = sys.stdout

    def __enter__(self):
        sys.stdout = self.stdout
        return sys.stdout

    def __exit__(self, exc_type, exc_value, traceback):
        sys.stdout.close()
        sys.stdout = self.real_stdout

class patch_file:

    def __init__(self, file_dict):
        self.files = file_dict

    def __enter__(self):
        self.old_files = names.FILES
        names.FILES = self.files

    def __exit__(self, type, value, traceback):
        names.FILES = self.old_files

test_files = {
    'first:male': full_path('test/male.txt'),
    'first:female': full_path('test/female.txt'),
    'last': full_path('test/last.txt'),
}

class NamesTest(unittest.TestCase):

    def test_get_name(self):
        counts = defaultdict(int)
        rounds = 5000.0
        test_file = full_path('test/file1.txt')
        for i in range(1, int(rounds)):
            counts[names.get_name(test_file)] += 1
        self.assertAlmostEqual(counts['Test1'] / rounds, 0.333, delta=0.05)
        self.assertAlmostEqual(counts['Test2'] / rounds, 0.277, delta=0.05)
        self.assertAlmostEqual(counts['Test3'] / rounds, 0.222, delta=0.05)
        self.assertAlmostEqual(counts['Test4'] / rounds, 0.166, delta=0.05)
        self.assertEqual(counts['Test5'] / rounds, 0)

    def test_random_gender(self):
        counts = defaultdict(int)
        rounds = 5000.0
        with patch_file(test_files):
            for i in range(int(rounds)):
                names.get_first_name()
                counts[names.get_first_name()] += 1
        self.assertAlmostEqual(counts['Male'] / rounds, 0.500, delta=0.05)
        self.assertAlmostEqual(counts['Female'] / rounds, 0.500, delta=0.05)

    def test_correct_files(self):
        with patch_file(test_files):
            self.assertEqual(names.get_first_name(gender='male'), "Male")
            self.assertEqual(names.get_first_name(gender='female'), "Female")
            self.assertEqual(names.get_last_name(), "Last")

    def test_empty_file(self):
        empty_files = {
            'first:male': full_path('test/empty.txt'),
            'first:female': full_path('test/empty.txt'),
            'last': full_path('test/empty.txt'),
        }
        with patch_file(empty_files):
            self.assertEqual(names.get_first_name(gender='male'), "")
            self.assertEqual(names.get_first_name(gender='female'), "")
            self.assertEqual(names.get_last_name(), "")

    def test_only_male_and_female_gender_are_supported(self):
        with self.assertRaises(ValueError):
            names.get_first_name(gender='other')

class CommandLineTest(unittest.TestCase):

    def test_cli(self):
        with patch_stdout() as stdout:
            with patch_file(test_files):
                main()
                self.assertIn(stdout.getvalue(),
                              ["Male Last\n", "Female Last\n"])

if __name__ == '__main__':
    unittest.main()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace DMT.Common.Rest
{
    public static class RestClientHelper
    {
        public static void SendRequestWithoutBody(HttpMethod method, string url)
        {
            using (CreateRequestWhithoutBody(method, url).GetResponse()) ;
        }

        public static Task SendRequestWithoutBodyAsync(HttpMethod method, string url)
        {
            return CreateRequestWhithoutBody(method, url).GetResponseAsync();
        }

        private static HttpWebRequest CreateRequestWhithoutBody(HttpMethod method, string url)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = method;
            req.ContentLength = 0;
            return req;
        }

    }
}


text:
package org.jeecg.modules.system.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.SqlInjectionUtil;
import org.jeecg.modules.system.mapper.SysDictMapper;
import org.jeecg.modules.system.model.DuplicateCheckVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @Title: DuplicateCheckAction
 * @Description: 重复校验工具
 * @Author 张代浩
 * @Date 2019-03-25
 * @Version V1.0
 */
@Slf4j
@RestController
@RequestMapping("/sys/duplicate")
@Api(tags="重复校验")
public class DuplicateCheckController {

	@Autowired
	SysDictMapper sysDictMapper;

	/**
	 * 校验数据是否在系统中是否存在
	 *
	 * @return
	 */
	@RequestMapping(value = "/check", method = RequestMethod.GET)
	@ApiOperation("重复校验接口")
	public Result<String> doDuplicateCheck(DuplicateCheckVo duplicateCheckVo, HttpServletRequest request) {
		Long num = null;

		log.info("----duplicate check------:"+ duplicateCheckVo.toString());
		//关联表字典(举例:sys_user,realname,id)
		//SQL注入校验(只限制非法串改数据库)
		final String[] sqlInjCheck = {duplicateCheckVo.getTableName(),duplicateCheckVo.getFieldName()};
		SqlInjectionUtil.filterContent(sqlInjCheck);
		// update-begin-author:taoyan date:20211227 for: JTC-25 【online报表】oracle 操作问题 录入弹框啥都不填直接保存 ①编码不是应该提示必填么?②报错也应该是具体文字提示,不是后台错误日志
		if(StringUtils.isEmpty(duplicateCheckVo.getFieldVal())){
			Result rs = new Result();
			rs.setCode(500);
			rs.setSuccess(true);
			rs.setMessage("数据为空,不作处理!");
			return rs;
		}
		// update-end-author:taoyan date:20211227 for: JTC-25 【online报表】oracle 操作问题 录入弹框啥都不填直接保存 ①编码不是应该提示必填么?②报错也应该是具体文字提示,不是后台错误日志
		if (StringUtils.isNotBlank(duplicateCheckVo.getDataId())) {
			// [2].编辑页面校验
			num = sysDictMapper.duplicateCheckCountSql(duplicateCheckVo);
		} else {
			// [1].添加页面校验
			num = sysDictMapper.duplicateCheckCountSqlNoDataId(duplicateCheckVo);
		}

		if (num == null || num == 0) {
			// 该值可用
			return Result.ok("该值可用!");
		} else {
			// 该值不可用
			log.info("该值不可用,系统中已存在!");
			return Result.error("该值不可用,系统中已存在!");
		}
	}
}


text:
<?php

namespace Victoire\DevTools\VacuumBundle\Entity\WordPress;

class SEO
{
    private $metaTitle;

    private $metaDescription;

    private $noIndex;

    private $noFollow;
}


text:
[Satis Composer repository manager](http://getcomposer.org/doc/articles/handling-private-packages-with-satis.md) with a simple web UI.

## Introduction

Satisfy provides:

* a Web UI: A CRUD to your manage satis configuration file
* a simple security layer with Google Open ID or a login form
* Satis itself

Satisfy ease your satis configuration management. It provides simple web UI over Satis to avoid a hand-editing of the satis.json configuration file. All repositories from a composer.lock file can also be imported via upload. It's secured with google open ID  and you can apply an google apps organization constraint (check `app/config.php.dist`).

## How it works ?

Basically, it just reads/writes the satis.json file and provides a web CRUD.

* On each HTTP request, the satis.json is loaded.
* If a write occurs in this file, a backup is made in app/data/

## Installation

### Composer

* Download composer `wget http://getcomposer.org/composer.phar`
* Install `php composer.phar create-project playbloom/satisfy --stability=dev`

### Satis configuration

Define your [default/existing satis configuration](http://getcomposer.org/doc/articles/handling-private-packages-with-satis.md).

By default, the `satis.json` file is expected at the project root.

### Application configuration

* Define your configuration `cp app/config.php.dist app/config.php`
* Customize `app/config.php` according to your needs.

### Security

You can restrict the access setting `auth.use_login_form` parameter (in `app/config.php`) to `true`. Set authorized users in `auth.users` config array.

Use the following command to encode the password you want to use:

```
php -r "echo hash('sha1', 'mypassword');"
```

## Satis packages definition generation

You still need to generate your packages definitions as mentioned in Satis documentation.
Satsify just provide a bin shortcut in bin/satis.

## Known limitation

Since it's an ultra-KISS project, it doesn't handle race conditions with several simultaneous writes.
This could be avoided by extending the project with a simple SQLite layer for example, but then you have to manage the auto-generation of the satis.json file...

## Author

Ludovic Fleury - <ludo.fleury@gmail.com> - <http://twitter.com/ludofleury>
Julius Beckmann - <satisfy@h4cc.de> - <https://twitter.com/h4cc>

## Credits

[KnpLabs](https://github.com/KnpLabs) and @ubermuda for the really KISS open-id layer in [the marketplace repository](https://github.com/KnpLabs/marketplace)

## License

Satisfy is licensed under the MIT License - see the LICENSE file for details

[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/ludofleury/satisfy/trend.png)](https://bitdeli.com/free "Bitdeli Badge")