text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

//----------------------------------------------------------
// Logging.cpp - Common logging and console output infrastructure
//----------------------------------------------------------

#include "standardpch.h"
#include "logging.h"
#include "errorhandling.h"
#include <time.h>

//
// NOTE: Since the logging system is at the core of the error handling infrastructure, any errors
// that occur while logging will print a message to the console. Fatal errors trigger a debugbreak.
//

bool Logger::s_initialized = false;
UINT32 Logger::s_logLevel = LOGMASK_DEFAULT;
HANDLE Logger::s_logFile = INVALID_HANDLE_VALUE;
char *Logger::s_logFilePath = nullptr;
CRITICAL_SECTION Logger::s_critSec;

//
// Initializes the logging subsystem. This must be called before invoking any of the logging functionality.
//
/* static */
void Logger::Initialize()
{
    if (!s_initialized)
    {
        InitializeCriticalSection(&s_critSec);
        s_initialized = true;
    }
}

//
// Shuts down the logging subsystem, freeing resources, closing handles, and such.
//
/* static */
void Logger::Shutdown()
{
    if (s_initialized)
    {
        DeleteCriticalSection(&s_critSec);
        CloseLogFile();
        s_initialized = false;
    }
}

//
// Opens a log file at the given path and enables file-based logging, if the given path is valid.
//
/* static */
void Logger::OpenLogFile(char *logFilePath)
{
    if (s_logFile == INVALID_HANDLE_VALUE && logFilePath != nullptr)
    {
        s_logFile = CreateFileA(logFilePath,
                                GENERIC_WRITE,
                                FILE_SHARE_READ | FILE_SHARE_DELETE,
                                NULL,
                                CREATE_ALWAYS,
                                FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
                                NULL);

        if (s_logFile != INVALID_HANDLE_VALUE)
        {
            // We may need the file path later in order to delete the log file
            s_logFilePath = _strdup(logFilePath);
        }
        else
        {
            fprintf(stderr, "WARNING: [Logger::OpenLogFile] Failed to open log file '%s'. GetLastError()=%u\n", logFilePath, GetLastError());
        }
    }
}

//
// Closes the currently open log file, if one is open.
//
/* static */
void Logger::CloseLogFile()
{
    if (s_logFile != INVALID_HANDLE_VALUE)
    {
        // Avoid polluting the file system with empty log files
        if (GetFileSize(s_logFile, nullptr) == 0 && s_logFilePath != nullptr)
        {
            // We can call this before closing the handle because DeleteFile just marks the file
            // for deletion, i.e. it does not actually get deleted until its last handle is closed.
            if (!DeleteFileA(s_logFilePath))
                fprintf(stderr, "WARNING: [Logger::CloseLogFile] DeleteFile failed. GetLastError()=%u\n", GetLastError());
        }

        if (!CloseHandle(s_logFile))
            fprintf(stderr, "WARNING: [Logger::CloseLogFile] CloseHandle failed. GetLastError()=%u\n", GetLastError());

        s_logFile = INVALID_HANDLE_VALUE;

        free(s_logFilePath);
        s_logFilePath = nullptr;
    }
}

//
// Returns a bitmask representing the logging levels that are specified by the given string. The string
// format is described explicitly in the command-line usage documentation for SuperPMI and MCS.
//
// In essence, each log level has a corresponding character representing it, and the presence of that
// character in the specifier string indicates that the log mask should include that log level. The
// "quiet" level will override any other level specified: that is, if a "q" is present in the string,
// all other levels specified will be disregarded.
//
// If "q" is not specified, and "a" is specified, then all log levels are enabled. This is a shorthand
// to avoid looking up all the log levels and enabling them all by specifying all the individual characters.
//
/* static */
UINT32 Logger::ParseLogLevelString(const char *specifierStr)
{
    UINT32 logLevelMask = LOGMASK_NONE;

    if (strchr(specifierStr, 'q') == nullptr)  // "Quiet" overrides all other specifiers
    {
        if (strchr(specifierStr, 'a') != nullptr)  // "All" overrides the other specifiers
        {
            logLevelMask |= LOGMASK_ALL;
        }
        else
        {
            if (strchr(specifierStr, 'e') != nullptr)
                logLevelMask |= LOGLEVEL_ERROR;

            if (strchr(specifierStr, 'w') != nullptr)
                logLevelMask |= LOGLEVEL_WARNING;

            if (strchr(specifierStr, 'm') != nullptr)
                logLevelMask |= LOGLEVEL_MISSING;

            if (strchr(specifierStr, 'i') != nullptr)
                logLevelMask |= LOGLEVEL_ISSUE;

            if (strchr(specifierStr, 'n') != nullptr)
                logLevelMask |= LOGLEVEL_INFO;

            if (strchr(specifierStr, 'v') != nullptr)
                logLevelMask |= LOGLEVEL_VERBOSE;

            if (strchr(specifierStr, 'd') != nullptr)
                logLevelMask |= LOGLEVEL_DEBUG;
        }
    }

    return logLevelMask;
}

/* static */
void Logger::LogPrintf(const char *function, const char *file, int line,
                       LogLevel level, const char *msg, ...)
{
    va_list argList;
    va_start(argList, msg);
    LogVprintf(function, file, line, level, argList, msg);
}

//
// Logs a message, if the given log level is enabled, to both the console and the log file. This is the
// main logging function that all other logging functions eventually funnel into.
//
/* static */
void Logger::LogVprintf(const char *function, const char *file, int line,
                        LogLevel level, va_list argList, const char *msg)
{
    if (!s_initialized)
    {
        fprintf(stderr, "ERROR: [Logger::LogVprintf] Invoked the logging system before initializing it.\n");
        __debugbreak();
    }

    // Capture this first to make the timestamp more accurately reflect the actual time of logging
    time_t timestamp = time(nullptr);

    int fullMsgLen = _vscprintf(msg, argList) + 1;  // This doesn't count the null terminator
    char *fullMsg = new char[fullMsgLen];

    _vsnprintf_s(fullMsg, fullMsgLen, fullMsgLen, msg, argList);
    va_end(argList);

    const char *logLevelStr = "INVALID_LOGLEVEL";
    switch (level)
    {
    case LOGLEVEL_ERROR:
        logLevelStr = "ERROR";
        break;

    case LOGLEVEL_WARNING:
        logLevelStr = "WARNING";
        break;

    case LOGLEVEL_MISSING:
        logLevelStr = "MISSING";
        break;

    case LOGLEVEL_ISSUE:
        logLevelStr = "ISSUE";
        break;

    case LOGLEVEL_INFO:
        logLevelStr = "INFO";
        break;

    case LOGLEVEL_VERBOSE:
        logLevelStr = "VERBOSE";
        break;

    case LOGLEVEL_DEBUG:
        logLevelStr = "DEBUG";
        break;
    }

    // NOTE: This implementation doesn't guarantee that log messages will be written in chronological
    // order, since Windows doesn't guarantee FIFO behavior when a thread relinquishes a lock. If
    // maintaining chronological order is crucial, then we can implement a priority queueing system
    // for log messages.

    EnterCriticalSection(&s_critSec);

    if (level & GetLogLevel())
    {
        // Sends error messages to stderr instead out stdout
        FILE *dest = (level <= LOGLEVEL_WARNING) ? stderr : stdout;

        if (level < LOGLEVEL_INFO)
            fprintf(dest, "%s: ", logLevelStr);

        fprintf(dest, "%s\n", fullMsg);

        if (s_logFile != INVALID_HANDLE_VALUE)
        {
#ifndef FEATURE_PAL // TODO: no localtime_s() or strftime() in PAL
            tm timeInfo;
            errno_t err = localtime_s(&timeInfo, &timestamp);
            if (err != 0)
            {
                fprintf(stderr, "WARNING: [Logger::LogVprintf] localtime failed with error %d.\n", err);
                goto CleanUp;
            }

            size_t timeStrBuffSize = 20 * sizeof(char);
            char *timeStr = (char *)malloc(timeStrBuffSize);  // Use malloc so we can realloc if necessary

            // This particular format string should always generate strings of the same size, but
            // for the sake of robustness, we shouldn't rely on that assumption.
            while (strftime(timeStr, timeStrBuffSize, "%Y-%m-%d %H:%M:%S", &timeInfo) == 0)
            {
                timeStrBuffSize *= 2;
                timeStr = (char *)realloc(timeStr, timeStrBuffSize);
            }
#else // FEATURE_PAL
            const char *timeStr = "";
#endif // FEATURE_PAL

            const char logEntryFmtStr[] = "%s - %s [%s:%d] - %s - %s\r\n";
            size_t logEntryBuffSize = sizeof(logEntryFmtStr) + strlen(timeStr) + strlen(function) +
                                      strlen(file) + 10 + strlen(logLevelStr) + strlen(fullMsg);

            char *logEntry = new char[logEntryBuffSize];
            sprintf_s(logEntry, logEntryBuffSize, logEntryFmtStr,
                      timeStr, function, file, line, logLevelStr, fullMsg);

            DWORD bytesWritten;

            if (!WriteFile(s_logFile, logEntry, (DWORD)logEntryBuffSize - 1, &bytesWritten, nullptr))
                fprintf(stderr, "WARNING: [Logger::LogVprintf] Failed to write to log file. GetLastError()=%u\n", GetLastError());

            if (!FlushFileBuffers(s_logFile))
                fprintf(stderr, "WARNING: [Logger::LogVprintf] Failed to flush log file. GetLastError()=%u\n", GetLastError());

            delete[] logEntry;

#ifndef FEATURE_PAL
            free((void*)timeStr);
#endif // !FEATURE_PAL
        }
    }

#ifndef FEATURE_PAL
CleanUp:
#endif // !FEATURE_PAL

    LeaveCriticalSection(&s_critSec);
    delete[] fullMsg;
}

//
// Special helper for logging exceptions. This logs the exception message given as a debug message.
//
/* static */
void Logger::LogExceptionMessage(const char *function, const char *file, int line,
                                 DWORD exceptionCode, const char *msg, ...)
{
    std::string fullMsg = "Exception thrown: ";
    fullMsg += msg;

    va_list argList;
    va_start(argList, msg);
    LogVprintf(function, file, line, LOGLEVEL_DEBUG, argList, fullMsg.c_str());
}

//
// Logger for JIT issues. Identifies the issue type and logs the given message normally.
//
/* static */
void IssueLogger::LogIssueHelper(const char *function, const char *file, int line,
                                 IssueType issue, const char *msg, ...)
{
    std::string fullMsg;

    switch (issue)
    {
    case ISSUE_ASSERT:
        fullMsg += "<ASSERT>";
        break;

    case ISSUE_ASM_DIFF:
        fullMsg += "<ASM_DIFF>";
        break;

    default:
        fullMsg += "<UNKNOWN_ISSUE_TYPE>";
        break;
    }

    fullMsg += " ";
    fullMsg += msg;

    va_list argList;
    va_start(argList, msg);
    Logger::LogVprintf(function, file, line, LOGLEVEL_ISSUE, argList, fullMsg.c_str());
}


text:
package com.intellij.xdebugger;

import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.execution.ui.RunnerLayoutUi;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.xdebugger.breakpoints.XBreakpoint;
import com.intellij.xdebugger.breakpoints.XLineBreakpoint;
import com.intellij.xdebugger.frame.XExecutionStack;
import com.intellij.xdebugger.frame.XStackFrame;
import com.intellij.xdebugger.frame.XSuspendContext;
import com.intellij.xdebugger.stepping.XSmartStepIntoHandler;
import com.intellij.xdebugger.stepping.XSmartStepIntoVariant;
import consulo.disposer.Disposable;
import consulo.ui.image.Image;
import consulo.util.dataholder.Key;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.event.HyperlinkListener;

/**
 * Instances of this class are created by the debugging subsystem when {@link XDebuggerManager#startSession} or
 * {@link XDebuggerManager#startSessionAndShowTab} method is called. It isn't supposed to be implemented by a plugin.
 *

 * Instance of this class can be obtained from {@link XDebugProcess#getSession()} method and used to control debugging process
 *
 * @author nik
 */
public interface XDebugSession extends AbstractDebuggerSession {
  Key<XDebugSession> DATA_KEY = Key.create("XDebugSessionTab.XDebugSession");

  @Nonnull
  Project getProject();

  @Nonnull
  XDebugProcess getDebugProcess();

  boolean isSuspended();

  @Nullable
  XStackFrame getCurrentStackFrame();

  XSuspendContext getSuspendContext();

  /**
   * Position from the current frame
   * @return
   */
  @Nullable
  XSourcePosition getCurrentPosition();

  /**
   * Position from the top frame
   * @return
   */
  @Nullable
  XSourcePosition getTopFramePosition();

  void stepOver(boolean ignoreBreakpoints);

  void stepInto();

  void stepOut();

  void forceStepInto();

  void runToPosition(@Nonnull XSourcePosition position, final boolean ignoreBreakpoints);

  void pause();

  void resume();

  void showExecutionPoint();

  void setCurrentStackFrame(@Nonnull XExecutionStack executionStack, @Nonnull XStackFrame frame, boolean isTopFrame);

  default void setCurrentStackFrame(@Nonnull XExecutionStack executionStack, @Nonnull XStackFrame frame) {
    setCurrentStackFrame(executionStack, frame, frame.equals(executionStack.getTopFrame()));
  }

  /**
   * Call this method to setup custom icon and/or error message (it will be shown in tooltip) for breakpoint
   *
   * @param breakpoint   breakpoint
   * @param icon         icon (null if default icon should be used). You can use icons from {@link com.intellij.icons.AllIcons.Debugger}
   * @param errorMessage an error message if breakpoint isn't successfully registered
   */
  void updateBreakpointPresentation(@Nonnull XLineBreakpoint<?> breakpoint, @Nullable Image icon, @Nullable String errorMessage);

  /**
   * Marks the provide breakpoint as verified in the current session
   */
  void setBreakpointVerified(@Nonnull XLineBreakpoint<?> breakpoint);

  /**
   * Marks the provide breakpoint as invalid in the current session
   */
  void setBreakpointInvalid(@Nonnull XLineBreakpoint<?> breakpoint, @Nullable String errorMessage);

  /**
   * Call this method when a breakpoint is reached if its condition ({@link XBreakpoint#getCondition()}) evaluates to {@code true}.
   *

   * The underlying debugging process should be suspended only if the method returns {@code true}.
   *
   * @param breakpoint             reached breakpoint
   * @param evaluatedLogExpression value of {@link XBreakpoint#getLogExpression()} evaluated in the current context
   * @param suspendContext         context
   * @return true if the debug process should be suspended
   */
  boolean breakpointReached(@Nonnull XBreakpoint<?> breakpoint,
                            @Nullable String evaluatedLogExpression,
                            @Nonnull XSuspendContext suspendContext);

  /**
   * @deprecated use {@link #breakpointReached(com.intellij.xdebugger.breakpoints.XBreakpoint, String, com.intellij.xdebugger.frame.XSuspendContext)} instead
   */
  boolean breakpointReached(@Nonnull XBreakpoint<?> breakpoint, @Nonnull XSuspendContext suspendContext);

  /**
   * Call this method when position is reached (e.g. after "Run to cursor" or "Step over" command)
   *
   * @param suspendContext context
   */
  void positionReached(@Nonnull XSuspendContext suspendContext);

  /**
   * Call this method when session resumed because of some external event, e.g. from the debugger console
   */
  void sessionResumed();

  void stop();

  void setBreakpointMuted(boolean muted);

  boolean areBreakpointsMuted();

  void addSessionListener(@Nonnull XDebugSessionListener listener, @Nonnull Disposable parentDisposable);

  void addSessionListener(@Nonnull XDebugSessionListener listener);

  void removeSessionListener(@Nonnull XDebugSessionListener listener);

  void reportError(@Nonnull String message);

  void reportMessage(@Nonnull String message, @Nonnull MessageType type);

  void reportMessage(@Nonnull String message, @Nonnull MessageType type, @Nullable HyperlinkListener listener);

  @Nonnull
  String getSessionName();

  @Nonnull
  RunContentDescriptor getRunContentDescriptor();

  @Nullable
  RunProfile getRunProfile();

  void setPauseActionSupported(boolean isSupported);

  void rebuildViews();

  <V extends XSmartStepIntoVariant> void smartStepInto(XSmartStepIntoHandler<V> handler, V variant);

  void updateExecutionPosition();

  void initBreakpoints();

  ConsoleView getConsoleView();

  RunnerLayoutUi getUI();
}

redpajama_set_name: RedPajamaGithub


text:
PROGS=scatterguess
CGIPROGS=target-cgi
APACHECONFIG=target-server
CFLAGS=-c -g -I../include -Wall -Werror
LDFLAGS=-g
INSTALLROOT=../opt/scatterguess

all:	${PROGS}

clean:
	rm -rf ${PROGS} tester *.o core

build:	all
	mkdir -p ${INSTALLROOT}/bin
	cp ${PROGS} ${INSTALLROOT}/bin
	mkdir -p ${INSTALLROOT}/cgi-bin
	cp ${CGIPROGS} ${INSTALLROOT}/cgi-bin
	mkdir -p ${INSTALLROOT}/etc/apache2/sites-enabled
	cp ${APACHECONFIG} ${INSTALLROOT}/etc/apache2/sites-enabled
	mkdir -p ${INSTALLROOT}/www
	cp testtarget.html ${INSTALLROOT}/www

display-guesses.o:	display-guesses.c
	clang ${CFLAGS} display-guesses.c

scatterguess:	scatterguess.o display-guesses.o Makefile
	clang -o scatterguess ${LDFLAGS} scatterguess.o display-guesses.o

scatterguess.o:	scatterguess.c
	clang ${CFLAGS} scatterguess.c


text:
cask 'boostnote' do
  version '0.8.14'
  sha256 'f5cb7a5fb1237c591e0b687239744261e42d0a90bd644230deca036e5b346c86'

  # github.com/BoostIO/boost-releases was verified as official when first introduced to the cask
  url "https://github.com/BoostIO/boost-releases/releases/download/v#{version}/Boostnote-mac.dmg"
  appcast 'https://github.com/BoostIO/boost-releases/releases.atom',
          checkpoint: '6573fa3c0e9a360c7d5dcc088d8092b0586f7e41bbe32cf25a642e730ff5e374'
  name 'Boostnote'
  homepage 'https://boostnote.io/'

  depends_on macos: '>= :mavericks'

  app 'Boostnote.app'

  uninstall signal: [
                      ['TERM', 'com.maisin.boost.helper'],
                      ['TERM', 'com.maisin.boost'],
                    ]

  zap delete: '~/Library/Saved Application State/com.maisin.boost.savedState',
      trash:  [
                '~/Library/Application Support/boost',
                '~/Library/Preferences/com.maisin.boost.plist',
                '~/Library/Preferences/com.maisin.boost.helper.plist',
              ]
end


text:
package org.scapemod.accessor;

public interface IItemDefinition extends ICacheableNode {

    String[] getGroundActions();

    String[] getInterfaceActions();

    String getName();
}


text:
#include <memory>

#include "envoy/config/bootstrap/v3/bootstrap.pb.h"

#include "test/integration/integration.h"
#include "test/test_common/network_utility.h"

namespace Envoy {
namespace {

class UdpProxyIntegrationTest : public testing::TestWithParam<Network::Address::IpVersion>,
                                public BaseIntegrationTest {
public:
  UdpProxyIntegrationTest() : BaseIntegrationTest(GetParam(), configToUse()) {}

  static std::string configToUse() {
    return absl::StrCat(ConfigHelper::baseUdpListenerConfig(), R"EOF(
    listener_filters:
      name: udp_proxy
      typed_config:
        '@type': type.googleapis.com/envoy.config.filter.udp.udp_proxy.v2alpha.UdpProxyConfig
        stat_prefix: foo
        cluster: cluster_0
      )EOF");
  }

  void setup(uint32_t upstream_count) {
    udp_fake_upstream_ = true;
    if (upstream_count > 1) {
      setDeterministic();
      setUpstreamCount(upstream_count);
      config_helper_.addConfigModifier(
          [upstream_count](envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
            for (uint32_t i = 1; i < upstream_count; i++) {
              bootstrap.mutable_static_resources()
                  ->mutable_clusters(0)
                  ->mutable_load_assignment()
                  ->mutable_endpoints(0)
                  ->add_lb_endpoints()
                  ->mutable_endpoint()
                  ->MergeFrom(ConfigHelper::buildEndpoint(
                      Network::Test::getLoopbackAddressString(GetParam())));
            }
          });
    }
    BaseIntegrationTest::initialize();
  }

  /**
   *  Destructor for an individual test.
   */
  void TearDown() override {
    test_server_.reset();
    fake_upstreams_.clear();
  }

  void requestResponseWithListenerAddress(const Network::Address::Instance& listener_address) {
    // Send datagram to be proxied.
    Network::Test::UdpSyncPeer client(version_);
    client.write("hello", listener_address);

    // Wait for the upstream datagram.
    Network::UdpRecvData request_datagram;
    ASSERT_TRUE(fake_upstreams_[0]->waitForUdpDatagram(request_datagram));
    EXPECT_EQ("hello", request_datagram.buffer_->toString());

    // Respond from the upstream.
    fake_upstreams_[0]->sendUdpDatagram("world1", request_datagram.addresses_.peer_);
    Network::UdpRecvData response_datagram;
    client.recv(response_datagram);
    EXPECT_EQ("world1", response_datagram.buffer_->toString());
    EXPECT_EQ(listener_address.asString(), response_datagram.addresses_.peer_->asString());

    EXPECT_EQ(5, test_server_->counter("udp.foo.downstream_sess_rx_bytes")->value());
    EXPECT_EQ(1, test_server_->counter("udp.foo.downstream_sess_rx_datagrams")->value());
    EXPECT_EQ(5, test_server_->counter("cluster.cluster_0.upstream_cx_tx_bytes_total")->value());
    EXPECT_EQ(1, test_server_->counter("cluster.cluster_0.udp.sess_tx_datagrams")->value());

    EXPECT_EQ(6, test_server_->counter("cluster.cluster_0.upstream_cx_rx_bytes_total")->value());
    EXPECT_EQ(1, test_server_->counter("cluster.cluster_0.udp.sess_rx_datagrams")->value());
    // The stat is incremented after the send so there is a race condition and we must wait for
    // the counter to be incremented.
    test_server_->waitForCounterEq("udp.foo.downstream_sess_tx_bytes", 6);
    test_server_->waitForCounterEq("udp.foo.downstream_sess_tx_datagrams", 1);

    EXPECT_EQ(1, test_server_->counter("udp.foo.downstream_sess_total")->value());
    EXPECT_EQ(1, test_server_->gauge("udp.foo.downstream_sess_active")->value());
  }
};

INSTANTIATE_TEST_SUITE_P(IpVersions, UdpProxyIntegrationTest,
                         testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
                         TestUtility::ipTestParamsToString);

// Basic loopback test.
TEST_P(UdpProxyIntegrationTest, HelloWorldOnLoopback) {
  setup(1);
  const uint32_t port = lookupPort("listener_0");
  const auto listener_address = Network::Utility::resolveUrl(
      fmt::format("tcp://{}:{}", Network::Test::getLoopbackAddressUrlString(version_), port));
  requestResponseWithListenerAddress(*listener_address);
}

// Verifies calling sendmsg with a non-local address. Note that this test is only fully complete for
// IPv4. See the comment below for more details.
TEST_P(UdpProxyIntegrationTest, HelloWorldOnNonLocalAddress) {
  setup(1);
  const uint32_t port = lookupPort("listener_0");
  Network::Address::InstanceConstSharedPtr listener_address;
  if (version_ == Network::Address::IpVersion::v4) {
    // Kernel regards any 127.x.x.x as local address.
    listener_address = std::make_shared<Network::Address::Ipv4Instance>(
#ifndef __APPLE__
        "127.0.0.3",
#else
        "127.0.0.1",
#endif
        port);
  } else {
    // IPv6 doesn't allow any non-local source address for sendmsg. And the only
    // local address guaranteed in tests in loopback. Unfortunately, even if it's not
    // specified, kernel will pick this address as source address. So this test
    // only checks if IoSocketHandle::sendmsg() sets up CMSG_DATA correctly,
    // i.e. cmsg_len is big enough when that code path is executed.
    listener_address = std::make_shared<Network::Address::Ipv6Instance>("::1", port);
  }

  requestResponseWithListenerAddress(*listener_address);
}

// Make sure multiple clients are routed correctly to a single upstream host.
TEST_P(UdpProxyIntegrationTest, MultipleClients) {
  setup(1);
  const uint32_t port = lookupPort("listener_0");
  const auto listener_address = Network::Utility::resolveUrl(
      fmt::format("tcp://{}:{}", Network::Test::getLoopbackAddressUrlString(version_), port));

  Network::Test::UdpSyncPeer client1(version_);
  client1.write("client1_hello", *listener_address);

  Network::Test::UdpSyncPeer client2(version_);
  client2.write("client2_hello", *listener_address);
  client2.write("client2_hello_2", *listener_address);

  Network::UdpRecvData client1_request_datagram;
  ASSERT_TRUE(fake_upstreams_[0]->waitForUdpDatagram(client1_request_datagram));
  EXPECT_EQ("client1_hello", client1_request_datagram.buffer_->toString());

  Network::UdpRecvData client2_request_datagram;
  ASSERT_TRUE(fake_upstreams_[0]->waitForUdpDatagram(client2_request_datagram));
  EXPECT_EQ("client2_hello", client2_request_datagram.buffer_->toString());
  ASSERT_TRUE(fake_upstreams_[0]->waitForUdpDatagram(client2_request_datagram));
  EXPECT_EQ("client2_hello_2", client2_request_datagram.buffer_->toString());

  // We should not be getting datagrams from the same peer.
  EXPECT_NE(*client1_request_datagram.addresses_.peer_, *client2_request_datagram.addresses_.peer_);

  // Send two datagrams back to client 2.
  fake_upstreams_[0]->sendUdpDatagram("client2_world", client2_request_datagram.addresses_.peer_);
  fake_upstreams_[0]->sendUdpDatagram("client2_world_2", client2_request_datagram.addresses_.peer_);
  Network::UdpRecvData response_datagram;
  client2.recv(response_datagram);
  EXPECT_EQ("client2_world", response_datagram.buffer_->toString());
  client2.recv(response_datagram);
  EXPECT_EQ("client2_world_2", response_datagram.buffer_->toString());

  // Send 1 datagram back to client 1.
  fake_upstreams_[0]->sendUdpDatagram("client1_world", client1_request_datagram.addresses_.peer_);
  client1.recv(response_datagram);
  EXPECT_EQ("client1_world", response_datagram.buffer_->toString());
}

// Make sure sessions correctly forward to the same upstream host when there are multiple upstream
// hosts.
TEST_P(UdpProxyIntegrationTest, MultipleUpstreams) {
  setup(2);
  const uint32_t port = lookupPort("listener_0");
  const auto listener_address = Network::Utility::resolveUrl(
      fmt::format("tcp://{}:{}", Network::Test::getLoopbackAddressUrlString(version_), port));

  Network::Test::UdpSyncPeer client(version_);
  client.write("hello1", *listener_address);
  client.write("hello2", *listener_address);
  Network::UdpRecvData request_datagram;
  ASSERT_TRUE(fake_upstreams_[0]->waitForUdpDatagram(request_datagram));
  EXPECT_EQ("hello1", request_datagram.buffer_->toString());
  ASSERT_TRUE(fake_upstreams_[0]->waitForUdpDatagram(request_datagram));
  EXPECT_EQ("hello2", request_datagram.buffer_->toString());

  fake_upstreams_[0]->sendUdpDatagram("world1", request_datagram.addresses_.peer_);
  fake_upstreams_[0]->sendUdpDatagram("world2", request_datagram.addresses_.peer_);
  Network::UdpRecvData response_datagram;
  client.recv(response_datagram);
  EXPECT_EQ("world1", response_datagram.buffer_->toString());
  client.recv(response_datagram);
  EXPECT_EQ("world2", response_datagram.buffer_->toString());
}

} // namespace
} // namespace Envoy


text:
package certinel

import (
	"crypto/sha1"
	"crypto/sha256"
	"crypto/tls"
	"crypto/x509"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"errors"
	"log"
	"net"
	"strings"
	"sync"
	"time"

	"github.com/miekg/dns"
)

var (
	ErrNoPeerCertificate = errors.New("peer did not present certificate for domain")
	ErrExpired           = errors.New("certificate expired")
	ErrNotYetValid       = errors.New("certificate not yet valid")
	ErrInvalidHostname   = errors.New("invalid hostname")
	ErrNoCertificate     = errors.New("certificate serial not found")
)

var checkers struct {
	sync.Mutex
	state map[string]bool
}

func init() {
	checkers.state = make(map[string]bool)
}

type Domain struct {
	Domain string `json:"domain"`
	Port   string `json:"port"`
	cert   *x509.Certificate
}

type Status struct {
	Duration int64  `json:"check_duration"`
	Valid    bool   `json:"valid"`
	Err      string `json:"last_error"`
	Time     string `json:"last_check"`
	Validity int    `json:"valid_days"`
}

type Subject struct {
	CommonName         string   `json:"cn"`
	Country            []string `json:"c,omitempty"`
	Organization       []string `json:"o,omitempty"`
	OrganizationalUnit []string `json:"ou,omitempty"`
}

type Signature struct {
	Algorithm int    `json:"algorithm"`
	Value     string `json:"value"`
}

type Certificate struct {
	NotBefore      time.Time         `json:"not_before"`
	NotAfter       time.Time         `json:"not_after"`
	Issuer         Subject           `json:"issuer"`
	Subject        Subject           `json:"subject"`
	SerialNumber   string            `json:"serial"`
	AlternateNames []string          `json:"alternate_names,omitempty"`
	Signature      Signature         `json:"signature"`
	Fingerprints   map[string]string `json:"fingerprints"`
}

func toHexString(data []byte) string {
	result := make([]string, len(data))
	for i := 0; i < len(data); i += 1 {
		result[i] = hex.EncodeToString(data[i : i+1])
	}
	return strings.Join(result, ":")
}

func convertCert(cert *x509.Certificate) *Certificate {
	result := &Certificate{
		NotBefore:      cert.NotBefore.UTC(),
		NotAfter:       cert.NotAfter.UTC(),
		SerialNumber:   toHexString(cert.SerialNumber.Bytes()),
		AlternateNames: cert.DNSNames,
		Fingerprints:   make(map[string]string),
	}

	result.Signature = Signature{
		Value:     toHexString(cert.Signature),
		Algorithm: int(cert.SignatureAlgorithm),
	}

	result.Subject = Subject{
		CommonName:         cert.Subject.CommonName,
		Country:            cert.Subject.Country,
		Organization:       cert.Subject.Organization,
		OrganizationalUnit: cert.Subject.OrganizationalUnit,
	}

	result.Issuer = Subject{
		CommonName:         cert.Issuer.CommonName,
		Country:            cert.Issuer.Country,
		Organization:       cert.Issuer.Organization,
		OrganizationalUnit: cert.Issuer.OrganizationalUnit,
	}

	s256 := sha256.New()
	s256.Write(cert.Raw)
	result.Fingerprints["sha256"] = toHexString(s256.Sum(nil))

	s1 := sha1.New()
	s1.Write(cert.Raw)
	result.Fingerprints["sha1"] = toHexString(s1.Sum(nil))

	return result
}

// reverse a hostname (example.com => com.example.). This will provide a better
// form for sorting (www.example.com and api.example.com will be close together
// when reversed)
func ReverseHost(hostname string) (string, error) {
	if _, ok := dns.IsDomainName(hostname); ok {
		labels := dns.SplitDomainName(hostname)

		for i, j := 0, len(labels)-1; i < j; i, j = i+1, j-1 {
			labels[i], labels[j] = labels[j], labels[i]
		}

		return strings.Join(labels, "."), nil
	} else {
		return "", ErrInvalidHostname
	}

	return "", ErrInvalidHostname
}

func (d *Domain) GetCertificate() (*x509.Certificate, error) {
	// dial the remote server with timeout
	c, err := net.DialTimeout("tcp", d.Domain+":"+d.Port, time.Second*10)
	if err != nil {
		return nil, err
	}

	conn := tls.Client(c, &tls.Config{
		InsecureSkipVerify: true,     // we check expiration and hostname afterwars, we're only interested in the presented certificate
		ServerName:         d.Domain, // Set the ServerName to support checking vHost certs using SNI
	})
	if conn == nil {
		return nil, err
	}

	// make sure the handshake will timeout so the check will return
	// at some point
	if err := conn.SetDeadline(time.Now().Add(time.Second * 10)); err != nil {
		return nil, err
	}

	if err := conn.Handshake(); err != nil {
		return nil, err
	}

	state := conn.ConnectionState()
	for _, cert := range state.PeerCertificates {
		if ok := cert.VerifyHostname(d.Domain); ok == nil {
			return cert, nil
		}
	}

	return nil, ErrNoPeerCertificate
}

func (d *Domain) Check() error {
	cert, err := d.GetCertificate()
	if err != nil {
		return err
	}
	d.cert = cert

	now := time.Now().UTC()
	if !now.Before(cert.NotAfter) {
		return ErrExpired
	}

	if !now.After(cert.NotBefore) {
		return ErrNotYetValid
	}

	return nil
}

func (d *Domain) Store(status *Status) error {
	rhost, err := ReverseHost(d.Domain)
	if err != nil {
		return err
	}

	store := GetStore()
	bucket := []string{"domains", rhost + ":" + d.Port}
	if err := store.Create(bucket); err != nil {
		return err
	}

	if d.cert != nil {
		id := d.cert.NotBefore.Format(time.RFC3339)
		data := base64.StdEncoding.EncodeToString(d.cert.Raw)
		if err := store.Set(bucket, "cert~"+d.cert.SerialNumber.String(), data); err != nil {
			return err
		}

		if err := store.Set(bucket, "history~"+id, d.cert.SerialNumber.String()); err != nil {
			return err
		}

		if err := store.Set(bucket, "history~~", "-- LIST STOP --"); err != nil {
			return err
		}

		if err := store.Set(bucket, "current", d.cert.SerialNumber.String()); err != nil {
			return err
		}
	}

	if status != nil {
		data, err := json.Marshal(status)
		if err != nil {
			return err
		}
		if err := store.Set(bucket, "status", string(data)); err != nil {
			return err
		}
	}

	return nil
}

func (d *Domain) Status() (*Status, error) {
	rhost, err := ReverseHost(d.Domain)
	if err != nil {
		return nil, err
	}

	store := GetStore()
	bucket := []string{"domains", rhost + ":" + d.Port}
	value, err := store.Get(bucket, "status")
	if err != nil {
		return nil, err
	}

	data := &Status{}
	if err := json.Unmarshal([]byte(value), data); err != nil {
		return nil, err
	}

	return data, nil
}

func (d *Domain) Delete() error {
	rhost, err := ReverseHost(d.Domain)
	if err != nil {
		return err
	}

	store := GetStore()
	if err := store.Remove([]string{"domains"}, rhost+":"+d.Port); err != nil {
		return err
	}

	checkers.Lock()
	delete(checkers.state, d.Domain+":"+d.Port)
	checkers.Unlock()

	return nil
}

func (d *Domain) CertList() (*Certificate, []*Certificate, error) {
	rhost, err := ReverseHost(d.Domain)
	if err != nil {
		return nil, nil, err
	}

	store := GetStore()
	bucket := []string{"domains", rhost + ":" + d.Port}
	curr, err := store.Get(bucket, "current")
	if err != nil {
		return nil, nil, err
	}

	current, err := d.LoadCertificate(curr)
	if err != nil {
		return nil, nil, err
	}

	his := store.Scan(bucket, "history~", true, 51)
	history := make([]*Certificate, 0)
	for kv := range his {
		if len(kv.Value) > 0 {
			cert, err := d.LoadCertificate(kv.Value)
			if err == nil {
				history = append(history, cert)
			}
		}
	}

	return current, history, nil
}

func (d *Domain) LoadCertificate(serial string) (*Certificate, error) {
	rhost, err := ReverseHost(d.Domain)
	if err != nil {
		return nil, err
	}

	store := GetStore()
	bucket := []string{"domains", rhost + ":" + d.Port}
	raw, err := store.Get(bucket, "cert~"+serial)
	if err != nil {
		return nil, err
	}

	if len(raw) == 0 {
		return nil, ErrNoCertificate
	}

	data, err := base64.StdEncoding.DecodeString(raw)
	if err != nil {
		return nil, err
	}

	cert, err := x509.ParseCertificate(data)
	if err != nil {
		return nil, err
	}

	return convertCert(cert), nil
}

func CheckDomain(domain, port string) {
	ticker := time.NewTicker(time.Minute * 5)
	log.Printf("starting domain checker for \"%s:%s\"\n", domain, port)

	checkers.Lock()
	checkers.state[domain+":"+port] = true
	checkers.Unlock()

	for {
		checkers.Lock()
		v, ok := checkers.state[domain+":"+port]
		checkers.Unlock()

		if !v || !ok {
			log.Printf("stopping check on \"%s:%s\"\n", domain, port)
			break
		}

		d := &Domain{
			Domain: domain,
			Port:   port,
		}

		start := time.Now()
		status := &Status{Time: start.UTC().Format(time.RFC3339)}
		err := d.Check()
		if err != nil {
			log.Printf("checking domain \"%s:%s\": %s\n", domain, port, err.Error())
			status.Valid = false
			status.Err = err.Error()
			AddMetricPoint(d.Domain, d.Port, 0, err)
		} else {
			now := time.Now().UTC().Unix()
			validity := d.cert.NotAfter.Unix() - now
			status.Valid = true
			status.Validity = int(validity / 86400)
			log.Printf("checking domain \"%s:%s\": certificate is valid for %d days", domain, port, status.Validity)
			AddMetricPoint(d.Domain, d.Port, float64(validity), nil)
		}
		status.Duration = int64(time.Since(start) / time.Millisecond)

		// store latest check and certificate
		d.Store(status)

		// wait for 5 minutes
		<-ticker.C
	}
}

func GetDomains() []*Domain {
	result := make([]*Domain, 0)
	store := GetStore()
	for kv := range store.Scan([]string{"domains"}, "", false, 0) {
		splitter := strings.Split(kv.Key, ":")
		if len(splitter) != 2 {
			continue
		}

		domain, err := ReverseHost(splitter[0])
		if err != nil {
			continue
		}

		result = append(result, &Domain{Domain: domain, Port: splitter[1]})
	}

	return result
}

func StartDomainChecker() {
	for _, d := range GetDomains() {
		go CheckDomain(d.Domain, d.Port)
	}
}


text:
<?php

namespace Herkod\Core\Page;

class Page
{

}


text:
<!DOCTYPE HTML>

        <meta name="viewport" content="width=device-width">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

            <meta http-equiv="Refresh" content="1; URL=/noscript">

        <link rel="stylesheet" type="text/css" href="/shared/oae/css/oae.core.css" />
        <link rel="stylesheet" type="text/css" href="/api/ui/skin" />

        <link rel="stylesheet" type="text/css" href="/ui/css/oae.lti.css" />


text:
bool conpty_init();
#endif

typedef struct {
  char *base;
  size_t len;
} pty_buf_t;

struct pty_process_;
typedef struct pty_process_ pty_process;
typedef void (*pty_read_cb)(pty_process *, pty_buf_t *, bool);
typedef void (*pty_exit_cb)(pty_process *);

struct pty_process_ {
  int pid, exit_code, exit_signal;
  uint16_t columns, rows;
#ifdef _WIN32
  STARTUPINFOEXW si;
  HPCON pty;
  HANDLE handle;
  HANDLE wait;
#else
  pid_t pty;
  uv_thread_t tid;
#endif
  char **argv;
  char **envp;
  char *cwd;

  uv_loop_t *loop;
  uv_async_t async;
  uv_pipe_t *in;
  uv_pipe_t *out;
  bool paused;

  pty_read_cb read_cb;
  pty_exit_cb exit_cb;
  void *ctx;
};

pty_buf_t *pty_buf_init(char *base, size_t len);
void pty_buf_free(pty_buf_t *buf);
pty_process *process_init(void *ctx, uv_loop_t *loop, char *argv[], char *envp[]);
bool process_running(pty_process *process);
void process_free(pty_process *process);
int pty_spawn(pty_process *process, pty_read_cb read_cb, pty_exit_cb exit_cb);
void pty_pause(pty_process *process);
void pty_resume(pty_process *process);
int pty_write(pty_process *process, pty_buf_t *buf);
bool pty_resize(pty_process *process);
bool pty_kill(pty_process *process, int sig);

#endif  // TTYD_PTY_H


text:
import RTable from './Table';
import Column from './Column';
import Cell from './Cell';
import HeaderCell from './HeaderCell';
import TablePagination from './TablePagination';
import './style/style.css';

RTable.Column = Column;
RTable.Cell = Cell;
RTable.HeaderCell = HeaderCell;
RTable.TablePagination = TablePagination;
export default RTable;


text:
package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	strfmt "github.com/go-openapi/strfmt"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/swag"
)

// OpenpitrixDeleteRuntimeCredentialsRequest openpitrix delete runtime credentials request
// swagger:model openpitrixDeleteRuntimeCredentialsRequest
type OpenpitrixDeleteRuntimeCredentialsRequest struct {

	// required, ids of runtime credential to delete
	RuntimeCredentialID []string `json:"runtime_credential_id"`
}

// Validate validates this openpitrix delete runtime credentials request
func (m *OpenpitrixDeleteRuntimeCredentialsRequest) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateRuntimeCredentialID(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *OpenpitrixDeleteRuntimeCredentialsRequest) validateRuntimeCredentialID(formats strfmt.Registry) error {

	if swag.IsZero(m.RuntimeCredentialID) { // not required
		return nil
	}

	return nil
}

// MarshalBinary interface implementation
func (m *OpenpitrixDeleteRuntimeCredentialsRequest) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *OpenpitrixDeleteRuntimeCredentialsRequest) UnmarshalBinary(b []byte) error {
	var res OpenpitrixDeleteRuntimeCredentialsRequest
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}


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

namespace LyraElectronics
{
    public class CanArray : IEnumerable
    {
        private List<CanBoard> _boards { get; set; }

        public CanController Controller { get; private set; }

        public CanArray()
        {
            _boards = new List<CanBoard>();
        }

        public T GetBoardAt<T>(int address) where T : CanBoard
        {
            return (T)_boards.Where(b => typeof(T) == b.GetType()).FirstOrDefault(i => i.SequenceNumber == address);
        }

        /// <summary>
        /// Gets the <see cref="System.Boolean"/> at the specified index.
        /// </summary>
        /// <value>
        /// The <see cref="System.Boolean"/>.
        /// </value>
        /// <param name="index">The index.</param>
        /// <returns></returns>
        public CanBoard this[int index]
        {
            get
            {
                if (index < _boards.Count - 1 || index > _boards.Count - 1)
                {
                    throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "A board at index {0} does not exist.", index.ToString()));
                }
                return _boards[index];
            }
        }

        /// <summary>
        /// Gets the enumerator.
        /// </summary>
        /// <returns></returns>
        public IEnumerator<CanBoard> GetEnumerator()
        {
            return _boards.GetEnumerator();
        }

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
        /// </returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
}


text:
package co.infinum.ava;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * Adapter that can be injected with views using AbstractViewHolder.
 *
 * Created by ivan on 12/15/13.
 */
public class AbstractViewAdapter<T> extends ArrayAdapter<T> {

    protected static final String INJECTOR_CLASS_NAME_SUFIX = "$$AdapterInjector";

    protected static final String INJECTOR_METHOD_NAME = "inject";

    /**
     * Factory for creating abstract view holders.
     */
    protected AbstractViewHolder.Factory<T> abstractViewFactory;

    /**
     * Used to store current abstract view holder.
     */
    private AbstractViewHolder<T> abstractViewHolder;

    /**
     * Creates new AbstractViewAdapter.
     *
     * @param context
     * @param abstractViewFactory
     * @param items
     */
    public AbstractViewAdapter(Context context, AbstractViewHolder.Factory<T> abstractViewFactory, ArrayList<T> items) {
        super(context, 0, items);
        this.abstractViewFactory = abstractViewFactory;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null) {
            abstractViewHolder = abstractViewFactory.createView(getContext());

            convertView = abstractViewHolder.updateView(getItem(position));
            convertView.setTag(abstractViewHolder);
        } else {
            abstractViewHolder = (AbstractViewHolder<T>)convertView.getTag();
            abstractViewHolder.updateView(getItem(position));
            return convertView;
        }

        return convertView;
    }

    public static void injectAdapters(Activity activity) {
        String injectorClassName = activity.getClass().getName() + INJECTOR_CLASS_NAME_SUFIX;

        try {
            Object injectorObject = Class.forName(injectorClassName).newInstance();

            Method method = getActivityInjectMethod(injectorObject, activity);
            method.invoke(injectorObject, activity);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void injectAdapters(Object object, View rootView) {
        String injectorClassName = object.getClass().getName() + INJECTOR_CLASS_NAME_SUFIX;

        try {
            Object injectorObject = Class.forName(injectorClassName).newInstance();

            Method method = getObjectInjectMethod(injectorObject, object);
            method.invoke(injectorObject, object, rootView);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Returns method for activity injection.
     *
     * @param injectorObject
     * @param activity
     * @return
     * @throws NoSuchMethodException
     */
    private static Method getActivityInjectMethod(Object injectorObject, Activity activity) throws NoSuchMethodException {
        Class[] parameterTypes = new Class[] {
            activity.getClass()
        };

        return injectorObject.getClass().getMethod(INJECTOR_METHOD_NAME, parameterTypes);
    }

    /**
     * Returns method for object injection.
     *
     * @param injectorObject
     * @param object
     * @return
     * @throws NoSuchMethodException
     */
    private static Method getObjectInjectMethod(Object injectorObject, Object object) throws NoSuchMethodException {
        Class[] parameterTypes = new Class[] {
                object.getClass(),
                View.class
        };

        return injectorObject.getClass().getMethod(INJECTOR_METHOD_NAME, parameterTypes);
    }

}


text:
<?php

namespace Cocorico\CoreBundle\Mailer;

use Cocorico\CoreBundle\Entity\Booking;
use Cocorico\CoreBundle\Entity\Listing;

interface MailerInterface
{
    /**
     * email is sent when a listing is activated
     *
     * @param Listing $listing
     *
     * @return void
     */
    public function sendListingActivatedMessageToOfferer(Listing $listing);

    /**
     * Send an email to offerer to confirm the new booking request
     *
     * @param Booking $booking
     *
     * @return void
     */
    public function sendBookingRequestMessageToOfferer(Booking $booking);

    /**
     * Send an email to offerer to inform the booking acceptation
     *
     * @param Booking $booking
     *
     * @return void
     */
    public function sendBookingAcceptedMessageToOfferer(Booking $booking);

    /**
     * email is sent when the bank refuses the payment
     *
     * @param Booking $booking
     *
     * @return void
     */
    //public function sendPaymentErrorMessageToOfferer(Booking $booking);

    /**
     * email is sent when the offerer rejects a reservation request
     *
     * @param Booking $booking
     *
     * @return void
     */
    public function sendBookingRefusedMessageToOfferer(Booking $booking);

    /**
     * email is sent 2 hours before a reservation request expires.
     *
     * @param Booking $booking
     * @return void
     */
    public function sendBookingExpirationAlertMessageToOfferer(Booking $booking);

    /**
     * Send an email to offerer to inform the new booking expiration
     *
     * @param Booking $booking
     *
     * @return void
     */
    public function sendBookingRequestExpiredMessageToOfferer(Booking $booking);

    /**
     * email is sent 24 hours after the end of the reservation.
     * so, that the offerer can rate the asker.
     *
     * @param Booking $booking
     * @return void
     */
    public function sendReminderToRateAskerMessageToOfferer(Booking $booking);

    /**
     * email is sent if the asker cancels his reservation
     *
     * @param Booking $booking
     *
     * @return void
     */
    public function sendBookingCanceledByAskerMessageToOfferer(Booking $booking);

    /**
     * email is sent 24 hours before the booking begins
     *
     * @param Booking $booking
     *
     * @return void
     */
    public function sendBookingImminentMessageToOfferer(Booking $booking);

    /**
     * email is sent when money is wired to the offerer
     *
     * @param Booking $booking
     *
     * @return void
     */
    public function sendWireTransferMessageToOfferer(Booking $booking);

    /**
     * This is a reminder email that is sent every 27th day of the month.
     * It is sent only to users that have an active listing.
     *
     * @param Listing $listing
     *
     * @return void
     */
    public function sendUpdateYourCalendarMessageToOfferer(Listing $listing);

    /**
     * Send an email to asker to confirm the new booking request
     *
     * @param Booking $booking
     *
     * @return void
     */
    public function sendBookingRequestMessageToAsker(Booking $booking);

    /**
     * Send an email to asker to inform the booking acceptation
     *
     * @param Booking $booking
     *
     * @return void
     */
    public function sendBookingAcceptedMessageToAsker(Booking $booking);

    /**
     * email is sent when the bank refuses the payment
     *
     * @param Booking $booking
     *
     * @return void
     */
    //public function sendPaymentErrorMessageToAsker(Booking $booking);

    /**
     * Send an email to asker to inform the booking refusal
     *
     * @param Booking $booking
     *
     * @return void
     */
    public function sendBookingRefusedMessageToAsker(Booking $booking);

    /**
     * Send an email to asker to inform the new booking expiration
     *
     * @param Booking $booking
     *
     * @return void
     */
    public function sendBookingRequestExpiredMessageToAsker(Booking $booking);

    /**
     * email is sent when the offerer rejects a reservation request
     *
     * @param Booking $booking
     *
     * @return void
     */
    public function sendBookingImminentMessageToAsker(Booking $booking);

    /**
     * email is sent 24 hours after the end of the reservation.
     * so, that the asker can rate the offerer.
     *
     * @param Booking $booking
     *
     * @return void
     */
    public function sendReminderToRateOffererMessageToAsker(Booking $booking);

    /**
     * email is sent if the asker cancels his reservation.
     *
     * @param Booking $booking
     *
     * @return void
     */
    public function sendBookingCanceledByAskerMessageToAsker(Booking $booking);

    /**
     * email is sent to admin
     *
     * @param string $subject
     * @param string $message
     *
     * @return void
     */
    public function sendMessageToAdmin($subject, $message);
}


text:
'use strict';

/* eslint-disable no-restricted-properties */

const common = require('../common.js');
const assert = require('assert');

const bench = common.createBenchmark(main, {
  n: [5e2],
  len: [5e2],
  method: [
    'deepEqual_primitiveOnly',
    'deepStrictEqual_primitiveOnly',
    'deepEqual_objectOnly',
    'deepStrictEqual_objectOnly',
    'deepEqual_mixed',
    'deepStrictEqual_mixed',
    'deepEqual_looseMatches',
    'notDeepEqual_primitiveOnly',
    'notDeepStrictEqual_primitiveOnly',
    'notDeepEqual_objectOnly',
    'notDeepStrictEqual_objectOnly',
    'notDeepEqual_mixed',
    'notDeepStrictEqual_mixed',
    'notDeepEqual_looseMatches',
  ]
});

function benchmark(method, n, values, values2) {
  const actual = new Map(values);
  // Prevent reference equal elements
  const deepCopy = JSON.parse(JSON.stringify(values2 ? values2 : values));
  const expected = new Map(deepCopy);
  bench.start();
  for (var i = 0; i < n; ++i) {
    method(actual, expected);
  }
  bench.end(n);
}

function main({ n, len, method }) {
  const array = Array(len).fill(1);
  var values, values2;

  switch (method) {
    case '':
      // Empty string falls through to next line as default, mostly for tests.
    case 'deepEqual_primitiveOnly':
      values = array.map((_, i) => [`str_${i}`, 123]);
      benchmark(assert.deepEqual, n, values);
      break;
    case 'deepStrictEqual_primitiveOnly':
      values = array.map((_, i) => [`str_${i}`, 123]);
      benchmark(assert.deepStrictEqual, n, values);
      break;
    case 'deepEqual_objectOnly':
      values = array.map((_, i) => [[`str_${i}`, 1], 123]);
      benchmark(assert.deepEqual, n, values);
      break;
    case 'deepStrictEqual_objectOnly':
      values = array.map((_, i) => [[`str_${i}`, 1], 123]);
      benchmark(assert.deepStrictEqual, n, values);
      break;
    case 'deepEqual_mixed':
      values = array.map((_, i) => [i % 2 ? [`str_${i}`, 1] : `str_${i}`, 123]);
      benchmark(assert.deepEqual, n, values);
      break;
    case 'deepStrictEqual_mixed':
      values = array.map((_, i) => [i % 2 ? [`str_${i}`, 1] : `str_${i}`, 123]);
      benchmark(assert.deepStrictEqual, n, values);
      break;
    case 'deepEqual_looseMatches':
      values = array.map((_, i) => [i, i]);
      values2 = values.slice().map((v) => [String(v[0]), String(v[1])]);
      benchmark(assert.deepEqual, n, values, values2);
      break;
    case 'notDeepEqual_primitiveOnly':
      values = array.map((_, i) => [`str_${i}`, 123]);
      values2 = values.slice(0);
      values2[Math.floor(len / 2)] = ['w00t', 123];
      benchmark(assert.notDeepEqual, n, values, values2);
      break;
    case 'notDeepStrictEqual_primitiveOnly':
      values = array.map((_, i) => [`str_${i}`, 123]);
      values2 = values.slice(0);
      values2[Math.floor(len / 2)] = ['w00t', 123];
      benchmark(assert.notDeepStrictEqual, n, values, values2);
      break;
    case 'notDeepEqual_objectOnly':
      values = array.map((_, i) => [[`str_${i}`, 1], 123]);
      values2 = values.slice(0);
      values2[Math.floor(len / 2)] = [['w00t'], 123];
      benchmark(assert.notDeepEqual, n, values, values2);
      break;
    case 'notDeepStrictEqual_objectOnly':
      values = array.map((_, i) => [[`str_${i}`, 1], 123]);
      values2 = values.slice(0);
      values2[Math.floor(len / 2)] = [['w00t'], 123];
      benchmark(assert.notDeepStrictEqual, n, values, values2);
      break;
    case 'notDeepEqual_mixed':
      values = array.map((_, i) => [i % 2 ? [`str_${i}`, 1] : `str_${i}`, 123]);
      values2 = values.slice(0);
      values2[0] = ['w00t', 123];
      benchmark(assert.notDeepEqual, n, values, values2);
      break;
    case 'notDeepStrictEqual_mixed':
      values = array.map((_, i) => [i % 2 ? [`str_${i}`, 1] : `str_${i}`, 123]);
      values2 = values.slice(0);
      values2[0] = ['w00t', 123];
      benchmark(assert.notDeepStrictEqual, n, values, values2);
      break;
    case 'notDeepEqual_looseMatches':
      values = array.map((_, i) => [i, i]);
      values2 = values.slice().map((v) => [String(v[0]), String(v[1])]);
      values2[len - 1] = [String(len + 1), String(len + 1)];
      benchmark(assert.notDeepEqual, n, values, values2);
      break;
    default:
      throw new Error(`Unsupported method ${method}`);
  }
}


text:
package com.s24.search.solr.component.termstrategy;

import com.s24.search.solr.query.bmax.Terms;

import java.util.Collection;
import java.util.Locale;
import java.util.Map;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
import org.apache.lucene.analysis.Analyzer;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.util.SolrPluginUtils;

import static com.google.common.base.Preconditions.checkNotNull;

public abstract class AbstractTermRankingStrategy implements TermRankingStrategy {

    private String q;
    private String extraTerms;
    private Analyzer analyzer;
    private String fields;
    private float boostFactor;
    private String queryType;

    @Override
    public String apply(ModifiableSolrParams params) {
        String joinedTerms = getTerms();
        if (!joinedTerms.isEmpty()){
            String termRankingQueryString = makeQueryString(params, joinedTerms);

            addToQuery(termRankingQueryString, params);
            return joinedTerms;
        }
        return "";
    }

    protected abstract void addToQuery(String termRankingQueryString, ModifiableSolrParams params);

    private String getTerms() {
        final Collection<CharSequence> terms = Terms.collect(q, analyzer);
        // add extra terms
        if (extraTerms != null) {
            terms.addAll(Sets.newHashSet(Splitter.on(',').omitEmptyStrings().split(extraTerms)));
        }

        return Joiner.on(" ").join(terms);
    }

    private String makeQueryString(SolrParams params, String joinedTerms) {
            return String.format(Locale.US, "{!%s qf='%s' mm=1 bq=''} %s", queryType,
                    computeFactorizedQueryFields(params),
                    joinedTerms);
    }

    private String computeFactorizedQueryFields(SolrParams params) {
        checkNotNull(params, "Pre-condition violated: params must not be null.");
        StringBuilder qf = new StringBuilder();
        // parse fields and boosts
        Map<String, Float> fieldBoosts = SolrPluginUtils.parseFieldBoosts(params.getParams(fields));
        // iterate, add factor and add to result qf
        for (Map.Entry<String, Float> f : fieldBoosts.entrySet()) {
            qf.append(f.getKey());
            qf.append('^');

            if (f.getValue() != null) {
                qf.append(f.getValue() * boostFactor);
            } else {
                qf.append(boostFactor);
            }
            qf.append(' ');
        }
        return qf.toString();
    }

    public void setQ(String q) {
        this.q = q;
    }

    public void setExtraTerms(String extraTerms) {
        this.extraTerms = extraTerms;
    }

    public void setAnalyzer(Analyzer analyzer) {
        this.analyzer = analyzer;
    }

    public void setFields(String fields) {
        this.fields = fields;
    }

    public void setBoostFactor(float boostFactor) {
        this.boostFactor = boostFactor;
    }

    public void setQueryType(String queryType) {
        this.queryType = queryType;
    }
}


text:
// Copyright (c) Source Tree Solutions, LLC. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Author:                  Joe Audette
// Created:                 2016-02-06
// Last Modified:           2016-02-15
//

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace cloudscribe.MetaWeblog
{
    public class MetaWeblogRequestValidator : IMetaWeblogRequestValidator
    {
        public Task<bool> IsValid(MetaWeblogRequest request, CancellationToken cancellationToken)
        {
            if(string.IsNullOrEmpty(request.MethodName)) { return Task.FromResult(false); }

            switch (request.MethodName)
            {
                case "system.listMethods":
                    return Task.FromResult(true);

                case "wpcom.getFeatures":
                    return Task.FromResult(true);

                case "metaWeblog.newPost":
                    if(string.IsNullOrEmpty(request.BlogId)) { return Task.FromResult(false); }
                    if(string.IsNullOrEmpty(request.Post.title)) { return Task.FromResult(false); }

                    return Task.FromResult(true);

                case "metaWeblog.getPost":
                    //TODO: more checks

                    return Task.FromResult(true);

                case "metaWeblog.newMediaObject":
                case "wp.uploadFile":

                    var requestedFileExtension = Path.GetExtension(request.MediaObject.name);
                    //TODO: validate extension against white list of allowed extensions

                    return Task.FromResult(true);

                case "metaWeblog.getCategories":
                case "wp.getCategories":

                    return Task.FromResult(true);

                case "wp.newCategory":

                    return Task.FromResult(true);

                case "metaWeblog.getRecentPosts":

                    return Task.FromResult(true);

                case "blogger.getUsersBlogs":
                case "metaWeblog.getUsersBlogs":

                    return Task.FromResult(true);

                case "wp.getUsersBlogs":

                    return Task.FromResult(true);

                case "metaWeblog.editPost":
                case "blogger.deletePost":
                case "wp.editPage":
                case "wp.deletePage":

                    return Task.FromResult(true);

                case "wp.newPage":

                    return Task.FromResult(true);

                case "wp.getPage":

                    return Task.FromResult(true);

                case "wp.getPageList":

                    return Task.FromResult(true);

                case "wp.getPages":

                    return Task.FromResult(true);

                case "wp.getAuthors":

                    return Task.FromResult(true);

                case "wp.getTags":

                    return Task.FromResult(true);

            }

            return Task.FromResult(false);
        }
    }
}


text:
Hand, foot and mouth disease is easily spread to other people. It's spread in coughs, sneezes and poo.

You're infectious from a few days before you have any symptoms, but you're most likely to give it to others in the first five days after symptoms start.

To reduce the risk of spreading hand, foot and mouth disease:

- wash your hands often with warm water and soap (and teach children to do it)
- use tissues to trap germs when you cough or sneeze
- bin used tissues as quickly as possible
- don't share towels or household items (such as cups or cutlery)
- wash soiled bedding and clothing on a hot wash

### Stay off work, school or nursery

Stay off work or keep your child away from school or nursery while they're feeling unwell.

Check with your school or nursery guidance on when children can return after hand, foot and mouth disease.

## Hand, foot and mouth disease in pregnancy

Although there's normally no risk to the pregnancy or baby, it's best to avoid close contact with anyone who has hand,
foot and mouth disease.

This is because:
- having a high temperature during the first 3 months of pregnancy can lead to miscarriage, although this is very rare
- getting hand, foot and mouth disease shortly before birth can mean the baby is born with a mild version of it

Speak to your GP or midwife if you have been in contact with someone with hand, foot and mouth disease.


text:
package com.google.cloud.spanner;

import static com.google.common.truth.Truth.assertThat;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Unit tests for {@link com.google.cloud.spanner.DatabaseId}. */
@RunWith(JUnit4.class)
public class DatabaseIdTest {
  @Rule public ExpectedException expectedException = ExpectedException.none();

  @Test
  public void basics() {
    String name = "projects/test-project/instances/test-instance/databases/database-1";
    DatabaseId db = DatabaseId.of(name);
    assertThat(db.getName()).isEqualTo(name);
    assertThat(db.getInstanceId().getInstance()).isEqualTo("test-instance");
    assertThat(db.getDatabase()).isEqualTo("database-1");
    assertThat(DatabaseId.of("test-project", "test-instance", "database-1")).isEqualTo(db);
    assertThat(DatabaseId.of(name)).isEqualTo(db);
    assertThat(DatabaseId.of(name).hashCode()).isEqualTo(db.hashCode());
    assertThat(db.toString()).isEqualTo(name);
  }

  @Test
  public void badName() {
    expectedException.expect(IllegalArgumentException.class);
    expectedException.expectMessage("projects"); // Expect conforming pattern in output.
    DatabaseId.of("bad name");
  }
}


text:
package main

import (
	"encoding/xml"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestRequestParsing(t *testing.T) {
	req, err := parseRequest(strings.NewReader(
		`<?xml version="1.0" encoding="utf-8"?>
        <Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/mobilesync/requestschema/2006">
            <Request>
                <EMailAddress>me@example.com</EMailAddress>
                <AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/mobilesync/responseschema/2006</AcceptableResponseSchema>
            </Request>
        </Autodiscover>`))

	t.Log(req.AcceptableResponseSchema)
	t.Log(req.EMailAddress)
	if err != nil {
		t.Fatal(err.Error())
	}

	if req.AcceptableResponseSchema != "http://schemas.microsoft.com/exchange/autodiscover/mobilesync/responseschema/2006" {
		t.Fail()
	}

	if req.EMailAddress != "me@example.com" {
		t.Fail()
	}
}

type response2006 struct {
	XMLName      xml.Name `xml:"Autodiscover"`
	DisplayName  string   `xml:"Response>User>DisplayName"`
	EMailAddress string   `xml:"Response>User>EMailAddress"`
	URL          string   `xml:"Response>Action>Settings>Server>Url"`
	Name         string   `xml:"Response>Action>Settings>Server>Name"`
}

var bla = []struct {
	server string
	mail   string
}{
	{"mail.example.com", "me@example.com"},
	{"mail", "me@example.com"},
	{"example.com", "abc@123"},
}

func Test2006RequestProcessing_new(t *testing.T) {
	const (
		schema = "http://schemas.microsoft.com/exchange/autodiscover/mobilesync/responseschema/2006"
	)

	for _, tt := range bla {
		uri := fmt.Sprintf("https://%sMicrosoft-Server-ActiveSync", tt.server)

		s := NewService(tt.server, uri)
		rec := httptest.NewRecorder()
		s.processRequest(rec, request{
			AcceptableResponseSchema: schema,
			EMailAddress:             tt.mail,
		})

		if rec.Code != http.StatusOK {
			t.Fatalf("http status want %d, got %d", http.StatusOK, rec.Code)
		}

		var res response2006
		decoder := xml.NewDecoder(rec.Body)
		if err := decoder.Decode(&res); err != nil {
			t.Fatal(err.Error())
		}

		// Schema is not checked, because unmarshalling nested attributes is a pain
		// See https://code.google.com/p/go/issues/detail?id=3633

		if res.DisplayName != tt.mail {
			t.Fatalf("want display name '%s', got '%s'", res.DisplayName, tt.mail)
		}

		if res.EMailAddress != tt.mail {
			t.Fatalf("want email address was '%s', got '%s'", res.EMailAddress, tt.mail)
		}

		if res.URL != uri {
			t.Fatalf("want url was '%s', got '%s'", res.URL, uri)
		}

		if res.Name != uri {
			t.Fatalf("want name was '%s', got '%s'", res.Name, uri)
		}
	}
}

type response2006a struct {
	XMLName     xml.Name                `xml:"Autodiscover"`
	DisplayName string                  `xml:"Response>User>DisplayName"`
	Protocols   []response2006aProtocol `xml:"Response>Protocol"`
}

type response2006aProtocol struct {
	XMLName   xml.Name `xml:"Protocol"`
	Server    string
	LoginName string
}

func Test2006aRequstProcessing(t *testing.T) {
	const (
		schema = "http://schemas.microsoft.com/exchange/autodiscover/mobilesync/responseschema/2006a"
	)

	for _, tt := range bla {
		uri := fmt.Sprintf("https://%sMicrosoft-Server-ActiveSync", tt.server)

		s := NewService(tt.server, uri)
		rec := httptest.NewRecorder()
		s.processRequest(rec, request{
			AcceptableResponseSchema: schema,
			EMailAddress:             tt.mail,
		})

		if rec.Code != http.StatusOK {
			t.Fatalf("http status want %d, got %d", http.StatusOK, rec.Code)
		}

		var res response2006a
		decoder := xml.NewDecoder(rec.Body)
		if err := decoder.Decode(&res); err != nil {
			t.Fatal(err.Error())
		}

		if res.DisplayName != tt.mail {
			t.Fatalf("Response display name was '%s' expected '%s'", res.DisplayName, tt.mail)
		}

		if res.Protocols[0].Server != tt.server {
			t.Fatalf("Response server was '%s' expected '%s'", res.Protocols[0].Server, tt.server)
		}

		if res.Protocols[0].LoginName != tt.mail {
			t.Fatalf("Response server was '%s' expected '%s'", res.Protocols[0].LoginName, tt.mail)
		}

		if res.Protocols[1].Server != tt.server {
			t.Fatalf("Response server was '%s' expected '%s'", res.Protocols[1].Server, tt.server)
		}

		if res.Protocols[1].LoginName != tt.mail {
			t.Fatalf("Response server was '%s' expected '%s'", res.Protocols[1].LoginName, tt.mail)
		}
	}
}

func TestRenderResponse(t *testing.T) {

}

func TestRenderError(t *testing.T) {
	r := httptest.NewRecorder()
	renderError(r)

	if r.Code != http.StatusBadRequest {
		t.Fatalf("http status want %d, got %d", http.StatusBadRequest, r.Code)
	}
}


text:
class MoveToConfigurableGateways < ActiveRecord::Migration
  def up
    drop_table :gateways
    drop_table :gateway_options
    drop_table :gateway_option_values
    drop_table :gateway_configurations

    create_table :gateways, :force => true do |t|
      t.string   :type, :name
      t.text     :description
      t.boolean  :active, :default => true
      t.string   :environment, :default => 'development'
      t.string   :server, :default => 'test'
      t.boolean  :test_mode, :default => true

      t.timestamps
    end
  end

  def down
    drop_table :gateways

    create_table :gateway_configurations, :force => true do |t|
      t.references :gateway

      t.timestamps
    end

    create_table :gateway_option_values, :force => true do |t|
      t.text     :value
      t.references :gateway_configuration
      t.references :gateway_option

      t.timestamps
    end

    create_table :gateway_options, :force => true do |t|
      t.string   :name
      t.text     :description
      t.boolean  :textarea, :default => false
      t.references :gateway

      t.timestamps
    end

    create_table :gateways, :force => true do |t|
      t.string   :clazz, :name
      t.text     :description
      t.boolean  :active

      t.timestamps
    end
  end
end


text:
module Html5
  module Beautifier
    VERSION = "0.0.2"
  end
end


text:
using Game;
using Game.Enums;
using UnityEngine;

// ReSharper disable once CheckNamespace
public class HitBox : MonoBehaviour
{
    public Group group;
    public Vector3 hitPosition;
    public float multiple = 1f;
}


text:
<?php

/**
 * Autoloads files with CMB2 classes when needed
 * @since  1.0.0
 * @param  string $class_name Name of the class being requested
 */
function cmb2_autoload_classes( $class_name ) {
	if ( class_exists( $class_name, false ) || false === strpos( $class_name, 'CMB2_' ) ) {
		return;
	}

	$file = cmb2_dir( "includes/{$class_name}.php" );
	if ( file_exists( $file ) ) {
		@include_once( $file );
	}
}
spl_autoload_register( 'cmb2_autoload_classes' );

/**
 * Get instance of the CMB2_Utils class
 * @since  2.0.0
 * @return CMB2_Utils object CMB utilities class
 */
function cmb2_utils() {
	static $cmb2_utils;
	$cmb2_utils = $cmb2_utils ? $cmb2_utils : new CMB2_Utils();
	return $cmb2_utils;
}

/**
 * Get instance of the CMB2_Ajax class
 * @since  2.0.0
 * @return CMB2_Ajax object CMB utilities class
 */
function cmb2_ajax( $args = array() ) {
	static $cmb2_ajax;
	$cmb2_ajax = $cmb2_ajax ? $cmb2_ajax : new CMB2_Ajax();
	return $cmb2_ajax;
}

/**
 * Get instance of the CMB2_Option class for the passed metabox ID
 * @since  2.0.0
 * @return CMB2_Option object Options class for setting/getting options for metabox
 */
function cmb2_options( $key ) {
	return CMB2_Options::get( $key );
}

/**
 * Get a cmb oEmbed. Handles oEmbed getting for non-post objects
 * @since  2.0.0
 * @param  array   $args Arguments. Accepts:
 *
 *         'url'         - URL to retrieve the oEmbed from,
 *         'object_id'   - $post_id,
 *         'object_type' - 'post',
 *         'oembed_args' - $embed_args, // array containing 'width', etc
 *         'field_id'    - false,
 *         'cache_key'   - false,
 *
 * @return string        oEmbed string
 */
function cmb2_get_oembed( $args = array() ) {
	return cmb2_ajax()->get_oembed( $args );
}

/**
 * A helper function to get an option from a CMB options array
 * @since  1.0.1
 * @param  string  $option_key Option key
 * @param  string  $field_id   Option array field key
 * @return array               Options array or specific field
 */
function cmb2_get_option( $option_key, $field_id = '' ) {
	return cmb2_options( $option_key )->get( $field_id );
}

/**
 * Get a CMB field object.
 * @since  1.1.0
 * @param  array  $meta_box    Metabox ID or Metabox config array
 * @param  array  $field_args  Field ID or all field arguments
 * @param  int    $object_id   Object ID
 * @param  string $object_type Type of object being saved. (e.g., post, user, comment, or options-page)
 * @return object              CMB2_Field object
 */
function cmb2_get_field( $meta_box, $field_id, $object_id = 0, $object_type = 'post' ) {

	$object_id = $object_id ? $object_id : get_the_ID();
	$cmb = ( $meta_box instanceof CMB2 ) ? $meta_box : cmb2_get_metabox( $meta_box, $object_id );

	if ( ! $cmb ) {
		return;
	}

	$object_type = $object_type ? $object_type : $cmb->mb_object_type();
	$cmb->object_type( $object_type );

	if ( is_array( $field_id ) && isset( $field_id['id'] ) ) {
		return new CMB2_Field( array(
			'field_args'  => $field_id,
			'object_id'   => $object_id,
			'object_type' => $object_type,
		) );
	}

	$fields = (array) $cmb->prop( 'fields' );
	foreach ( $fields as $field ) {
		if ( $field['id'] == $field_id || $field['name'] == $field_id ) {
			// Send back field object
			return new CMB2_Field( array(
				'field_args'  => $field,
				'object_id'   => $object_id,
				'object_type' => $object_type,
			) );

		}
	}
}

/**
 * Get a field's value.
 * @since  1.1.0
 * @param  array  $meta_box    Metabox ID or Metabox config array
 * @param  array  $field_args  Field ID or all field arguments
 * @param  int    $object_id   Object ID
 * @param  string $object_type Type of object being saved. (e.g., post, user, comment, or options-page)
 * @return mixed               Maybe escaped value
 */
function cmb2_get_field_value( $meta_box, $field_id, $object_id = 0, $object_type = 'post' ) {
	$field = cmb2_get_field( $meta_box, $field_id, $object_id, $object_type );
	return $field->escaped_value();
}

/**
 * Retrieve a CMB instance by the metabox ID
 * @since  2.0.0
 * @param  array $meta_box  Metabox ID or Metabox config array
 * @return CMB2 object
 */
function cmb2_get_metabox( $meta_box, $object_id = 0 ) {

	if ( $meta_box instanceof CMB2 ) {
		return $meta_box;
	}

	if ( is_string( $meta_box ) ) {
		$cmb = CMB2_Boxes::get( $meta_box );
	} else {
		// See if we already have an instance of this metabox
		$cmb = CMB2_Boxes::get( $meta_box['id'] );
		// If not, we'll initate a new metabox
		$cmb = $cmb ? $cmb : new CMB2( $meta_box, $object_id );
	}

	if ( $cmb && $object_id ) {
		$cmb->object_id( $object_id );
	}
	return $cmb;
}

/**
 * Retrieve a metabox form
 * @since  2.0.0
 * @param  array   $meta_box  Metabox config array or Metabox ID
 * @param  int     $object_id Object ID
 * @param  array   $args      Optional arguments array
 * @return string             CMB html form markup
 */
function cmb2_get_metabox_form( $meta_box, $object_id = 0, $args = array() ) {

	$object_id = $object_id ? $object_id : get_the_ID();
	$cmb       = cmb2_get_metabox( $meta_box, $object_id );

	ob_start();
	// Get cmb form
	cmb2_print_metabox_form( $cmb, $object_id, $args );
	$form = ob_get_contents();
	ob_end_clean();

	return apply_filters( 'cmb2_get_metabox_form', $form, $object_id, $cmb );
}

/**
 * Display a metabox form & save it on submission
 * @since  1.0.0
 * @param  array   $meta_box  Metabox config array or Metabox ID
 * @param  int     $object_id Object ID
 * @param  array   $args      Optional arguments array
 */
function cmb2_print_metabox_form( $meta_box, $object_id = 0, $args = array() ) {

	$object_id = $object_id ? $object_id : get_the_ID();
	$cmb = cmb2_get_metabox( $meta_box, $object_id );

	// if passing a metabox ID, and that ID was not found
	if ( ! $cmb ) {
		return;
	}

	// Set object type to what is declared in the metabox (rather than trying to guess from context)
	$cmb->object_type( $cmb->mb_object_type() );

	// Save the metabox if it's been submitted
	// check permissions
	// @todo more hardening?
	if (
		// check nonce
		isset( $_POST['submit-cmb'], $_POST['object_id'], $_POST[ $cmb->nonce() ] )
		&& wp_verify_nonce( $_POST[ $cmb->nonce() ], $cmb->nonce() )
		&& $_POST['object_id'] == $object_id
	) {
		$cmb->save_fields( $object_id, $cmb->object_type(), $_POST );
	}

	// Enqueue JS/CSS
	if ( $cmb->prop( 'cmb_styles' ) ) {
		CMB2_hookup::enqueue_cmb_css();
	}
	CMB2_hookup::enqueue_cmb_js();

	$args = wp_parse_args( $args, array(
		'form_format' => '<form class="cmb-form" method="post" id="%1$s" enctype="multipart/form-data" encoding="multipart/form-data"><input type="hidden" name="object_id" value="%2$s">%3$s<input type="submit" name="submit-cmb" value="%4$s" class="button-primary"></form>',
		'save_button' => __( 'Save', 'cmb2' ),
	) );

	$form_format = apply_filters( 'cmb2_get_metabox_form_format', $args['form_format'], $object_id, $cmb );

	$format_parts = explode( '%3$s', $form_format );

	// Show cmb form
	printf( $format_parts[0], $cmb->cmb_id, $object_id );
	$cmb->show_form();

	if ( isset( $format_parts[1] ) && $format_parts[1] ) {
		printf( str_ireplace( '%4$s', '%1$s', $format_parts[1] ), $args['save_button'] );
	}

}

/**
 * Display a metabox form (or optionally return it) & save it on submission
 * @since  1.0.0
 * @param  array   $meta_box  Metabox config array or Metabox ID
 * @param  int     $object_id Object ID
 * @param  array   $args      Optional arguments array
 */
function cmb2_metabox_form( $meta_box, $object_id = 0, $args = array() ) {
	if ( ! isset( $args['echo'] ) || $args['echo'] ) {
		cmb2_print_metabox_form( $meta_box, $object_id, $args );
	} else {
		cmb2_get_metabox_form( $meta_box, $object_id, $args );
	}
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>添加banner</title>

Banner

增加banner

<form id="add-banner-form" method="post" action="#">
    <input type="text" name="type" id="type" placeholder="请输入banner类型"/>
    <input type="text" name="title" id="title" placeholder="请输入banner标题"/>
    <input type="text" name="thumb_url" id="thumb_url" placeholder="请输入banner活动 thumb url"/>
    <input type="text" name="url" id="url" placeholder="请输入banner活动 url"/>
    <input type="submit" value="添加"/>
</form>

删除banner

<form id="add-banner-form" method="post" action="#">
    <input type="text" name="banner_id" id="banner_id" placeholder="请输入banner id"/>
    <input type="submit" value="删除"/>
</form>

更新banner

<form id="update-banner-form" method="post" action="#">
    <input type="text" name="banner_id" id="banner_id" placeholder="请输入banner id"/>
    <input type="text" name="type" id="type" placeholder="请输入banner类型"/>
    <input type="text" name="title" id="title" placeholder="请输入banner标题"/>
    <input type="text" name="thumb_url" id="thumb_url" placeholder="请输入banner活动 thumb url"/>
    <input type="text" name="url" id="url" placeholder="请输入banner活动 url"/>
    <input type="submit" value="更新"/>
</form>

查询单个banner

    <form id="add-banner-form" method="post" action="#">
        <input type="text" name="banner_id" id="banner_id" placeholder="请输入banner id"/>
        <input type="submit" value="查询"/>
    </form>

        查询结果在这显示:

查询多个banner

    <form id="add-banner-form" method="post" action="#">
        <input type="text" name="type" id="type" placeholder="要查询的banner类型"/>
        <input type="submit" value="查询"/>
    </form>

        查询结果在这显示:

添加文章分类

<form id="add-article-category-form" method="post" action="#">
    <input type="text" name="type" id="type" placeholder="请输入类型名称"/>
    <input type="text" name="title" id="title" placeholder="请输入标题"/>
    <input type="text" name="category_thumb_url" id="category_thumb_url" placeholder="请输入类型thumb url"/>
    <input type="submit" value="添加"/>
</form>


text:
//
//  UINavigationController+SPGestureRecognizer.h
//  SPCategory
//
//  Created by shiping li on 2020/5/8.
//  Copyright © 2020 lishiping. All rights reserved.
//

/*
 控制右滑手势返回上一页的方法
 当ViewController内部实现
 -(BOOL)gestureRecognizerShouldBegin;
 实例方法,如果返回是YES,则可以右滑返回,如果返回是NO,则不可以右滑返回
 */

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UINavigationController (SPGestureRecognizer)<UIGestureRecognizerDelegate>

@end

NS_ASSUME_NONNULL_END


text:
 $('div.parallaxBackground').each(function(){
  var item = $(this);

  item.find('article').css({
        position:'absolute',
        left: (item .width() - $('article').width())/2,
        top: (item .height() - $('article').height())/2
    });

  $(window).scroll(function() {

    var yPosition = -($(window).scrollTop() / item.data('scroll-speed'));

    var backgroundPosition = '50% '+ yPosition + 'px';

    item.css('background-position', backgroundPosition );

  });

   $(window).resize(function() {

   item.find('article').css({
        position:'absolute',
        left: (item .width() - $('article').width())/2,
        top: (item .height() - $('article').height())/2
    });

});
});


text:
import { IncomingMessage, ServerResponse, Server } from 'http';

export type RequestHandler = (req: IncomingMessage, res: ServerResponse) => any;

export function run(req: IncomingMessage, res: ServerResponse, fn: RequestHandler): Promise<void>;

declare function serve(fn: RequestHandler): Server;
export default serve;

export function send(res: ServerResponse, code: number, data?: any): Promise<void>;

export function sendError(req: IncomingMessage, res: ServerResponse, info: { statusCode?: number, status?: number, message?: string, stack?: string; }): Promise<void>;

export function createError(code: number, msg: string, orig?: Error): Error & { statusCode: number, originalError?: Error; };

export function buffer(req: IncomingMessage, info?: { limit?: string | number, encoding?: string; }): Promise<Buffer | string>;

export function text(req: IncomingMessage, info?: { limit?: string | number, encoding?: string; }): Promise<string>;

export function json(req: IncomingMessage, info?: { limit?: string | number, encoding?: string; }): Promise<{ [s: string]: any; }>;


text:
"""Utilities to test render setup drag and drop."""

import akaPipe.views.proxy.renderSetup as renderSetupProxy
import akaPipe.views.renderSetup as renderSetupUI
import akaPipe.model.utils as utils
import akaPipe.model.renderSetup as renderSetupModel

import PySide2.QtCore as QtCore

def mimeData(nodeNames):
    mimeData = QtCore.QMimeData()
    encodedData = QtCore.QByteArray()
    stream = QtCore.QDataStream(encodedData, QtCore.QIODevice.WriteOnly)
    for name in nodeNames:
        stream.writeString(name)
    mimeData.setData(renderSetupProxy.RENDER_SETUP_MIME_TYPE, encodedData)

    return mimeData

def dropOnto(nodeName, mimeData, row):
    # Note: If nodeName is None, then we are dropping onto the RenderSetup model.
    if nodeName != renderSetupModel.instance().name():
        n = utils.nameToUserNode(nodeName)
        nProxy = n.getOpaqueData(renderSetupProxy.PROXY_OPAQUE_DATA)()
    rsProxy = renderSetupUI.renderSetupWindow.centralWidget.renderSetupView.model()

    rsProxy.dropMimeDataFailure = False # Indicates if the drop was accepted
    rsProxy.dropMimeData(
        mimeData, QtCore.Qt.DropAction.MoveAction, row, 0, QtCore.QModelIndex() if nodeName==renderSetupModel.instance().name() else nProxy.index())

    return not rsProxy.dropMimeDataFailure
# ===========================================================================
# Copyright 2016 Autodesk, Inc. All rights reserved.
#
# Use of this software is subject to the terms of the Autodesk license
# agreement provided at the time of installation or download, or which
# otherwise accompanies this software in either electronic or hard copy form.
# ===========================================================================


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

import java.io.IOException;
import java.util.Date;
import java.util.Random;

import org.jsmpp.InvalidResponseException;
import org.jsmpp.PDUException;
import org.jsmpp.bean.BindType;
import org.jsmpp.bean.DataCodings;
import org.jsmpp.bean.ESMClass;
import org.jsmpp.bean.NumberingPlanIndicator;
import org.jsmpp.bean.OptionalParameter;
import org.jsmpp.bean.OptionalParameters;
import org.jsmpp.bean.RegisteredDelivery;
import org.jsmpp.bean.SMSCDeliveryReceipt;
import org.jsmpp.bean.TypeOfNumber;
import org.jsmpp.extra.NegativeResponseException;
import org.jsmpp.extra.ResponseTimeoutException;
import org.jsmpp.session.BindParameter;
import org.jsmpp.session.SMPPSession;
import org.jsmpp.util.AbsoluteTimeFormatter;
import org.jsmpp.util.TimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author uudashr
 *
 */
public class SubmitLongMessageExample {
    private static final Logger LOGGER = LoggerFactory.getLogger(SubmitLongMessageExample.class);
    private static final TimeFormatter TIME_FORMATTER = new AbsoluteTimeFormatter();;

    public static void main(String[] args) {
        SMPPSession session = new SMPPSession();
        try {
            session.connectAndBind("localhost", 8056, new BindParameter(BindType.BIND_TX, "test", "test", "cp", TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null));

            Random random = new Random();

            final int totalSegments = 3;
            OptionalParameter sarMsgRefNum = OptionalParameters.newSarMsgRefNum((short)random.nextInt());
            OptionalParameter sarTotalSegments = OptionalParameters.newSarTotalSegments(totalSegments);

            for (int i = 0; i < totalSegments; i++) {
                final int seqNum = i + 1;
                String message = "Message part " + seqNum + " of " + totalSegments + " ";
                OptionalParameter sarSegmentSeqnum = OptionalParameters.newSarSegmentSeqnum(seqNum);
                String messageId = submitMessage(session, message, sarMsgRefNum, sarSegmentSeqnum, sarTotalSegments);
                LOGGER.info("Message submitted, message_id is {}", messageId);
            }

            session.unbindAndClose();

        } catch (IOException e) {
            LOGGER.error("Failed connect and bind to host", e);
        }
    }

    public static String submitMessage(SMPPSession session, String message, OptionalParameter sarMsgRefNum, OptionalParameter sarSegmentSeqnum, OptionalParameter sarTotalSegments) {
        String messageId = null;
        try {
            messageId = session.submitShortMessage("CMT", TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.UNKNOWN, "1616", TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.UNKNOWN, "628176504657", new ESMClass(), (byte)0, (byte)1,  TIME_FORMATTER
                .format(new Date()), null, new RegisteredDelivery(SMSCDeliveryReceipt.DEFAULT), (byte)0, DataCodings.ZERO, (byte)0, message.getBytes(), sarMsgRefNum, sarSegmentSeqnum, sarTotalSegments);;
        } catch (PDUException e) {
            // Invalid PDU parameter
            LOGGER.error("Invalid PDU parameter", e);
        } catch (ResponseTimeoutException e) {
            // Response timeout
            LOGGER.error("Response timeout", e);
        } catch (InvalidResponseException e) {
            // Invalid response
            LOGGER.error("Receive invalid response", e);
        } catch (NegativeResponseException e) {
            // Receiving negative response (non-zero command_status)
            LOGGER.error("Receive negative response", e);
        } catch (IOException e) {
            LOGGER.error("I/O error occured", e);
        }
        return messageId;
    }
}


text:
since: 2.4.0
category: Bans
signatures:
    - - dataType: const char*
        name: hostmask
        description: ~
        default: ~
      - dataType: const char*
        name: source
        description: ~
        default: ~
      - dataType: int
        name: duration
        description: ~
        default: ~
      - dataType: const char*
        name: reason
        description: ~
        default: ~
returns:
    dataType: bool
    description: ~
---

Bans the host of specified user for the `duration` and `reason` provided.


text:
<component name="ArtifactManager">
  <artifact type="jar" name="ProgrammingLife:jar">
    <output-path>$PROJECT_DIR$/out/artifacts/ProgrammingLife_jar</output-path>
    <root id="archive" name="ProgrammingLife.jar">
      <element id="directory" name="META-INF">
        <element id="file-copy" path="$PROJECT_DIR$/src/main/java/whatever/META-INF/MANIFEST.MF" />
      </element>
      <element id="module-output" name="ProgrammingLife" />
      <element id="extracted-dir" path="$MAVEN_REPOSITORY$/com/diffplug/durian/durian/3.4.0/durian-3.4.0.jar" path-in-jar="/" />
      <element id="extracted-dir" path="$MAVEN_REPOSITORY$/org/apache/commons/commons-lang3/3.5/commons-lang3-3.5.jar" path-in-jar="/" />
      <element id="extracted-dir" path="$MAVEN_REPOSITORY$/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar" path-in-jar="/" />
      <element id="extracted-dir" path="$MAVEN_REPOSITORY$/junit/junit/4.12/junit-4.12.jar" path-in-jar="/" />
      <element id="library" level="project" name="Maven: com.diffplug.durian:durian:3.4.0" />
      <element id="library" level="project" name="Maven: org.apache.commons:commons-lang3:3.5" />
    </root>
  </artifact>
</component>


text:
class Makeconf

  Makeconf_Version = 0.1

  require 'optparse'
  require 'pp'
  require 'logger'

  require 'makeconf/archiver'
  require 'makeconf/buildable'
  require 'makeconf/binary'
  require 'makeconf/compiler'
  require 'makeconf/externalproject'
  require 'makeconf/gui'
  require 'makeconf/header'
  require 'makeconf/installer'
  require 'makeconf/library'
  require 'makeconf/linker'
  require 'makeconf/makefile'
  require 'makeconf/packager'
  require 'makeconf/platform'
  require 'makeconf/project'
  require 'makeconf/systemtype'
  require 'makeconf/target'
  require 'makeconf/test'

  @@installer = Installer.new
  @@makefile = Makefile.new
  @@original_argv = ARGV.clone   # OptionParser seems to clobber this..

  @@logger = Logger.new(STDOUT)
  #TODO:@@logger = Logger.new('config.log')
  @@logger.datetime_format = ''
  if ENV['MAKECONF_DEBUG'] == 'yes'
    @@logger.level = Logger::DEBUG
  else
    @@logger.level = Logger::WARN
  end

  def Makeconf.original_argv
    @@original_argv.clone
  end

  def Makeconf.logger
    @@logger
  end

  def Makeconf.parse_options(args = ARGV)
    reject_unknown_options = true

    x = OptionParser.new do |opts|
       opts.banner = 'Usage: configure [options]'

       @@installer.parse_options(opts)
       @@project.parse_options(opts)

       # Cross-compilation options
       opts.separator ''
       opts.separator 'System types:'

       opts.on('--build BUILD', 'set the system type for building') do |arg|
         @@build = arg
       end
       opts.on('--host HOST', 'cross-compile programs to run on a different system type') do |arg|
         @@host = arg
       end
       opts.on('--target TARGET', 'build a compiler for cross-compiling') do |arg|
         @@target = arg
       end

       opts.separator ''
       opts.separator 'Optional Features:'

       opts.on_tail('--disable-static', 'Disable generation of static libraries') do
         StaticLibrary.disable_all
       end

       opts.separator ''
       opts.separator 'Common options:'

       opts.on_tail('--disable-option-checking') {}     # NOOP

       opts.on_tail('-h', '--help', 'Show this message') do
         puts opts
         exit
       end

       opts.on_tail('-V', '--version', 'Display version information and exit') do
         puts "Makeconf $Id: makeconf.rb 366 2013-01-08 01:53:33Z mheily $"
         exit
       end
    end

    # Special case: This must be processed prior to all other options
    if args.include? '--disable-option-checking'
      reject_unknown_options = false
    end

    # Parse all options, and gracefully resume when an invalid option
    # is provided.
    #
    loop do
      begin
        x.parse!(args)
        rescue OptionParser::InvalidOption => e
           if reject_unknown_options
             warn '*** ERROR *** ' + e.to_s
             exit 1
           else
             warn 'WARNING: ' + e.to_s
             next
           end
      end
      break
    end
  end

  # Adjust the log level to increase debugging output
  def log_level=(level)
    @@logger.level = level
  end

  # Examine the operating environment and set configuration options
  def configure(project = nil)
    @project = project unless project.nil?

    @@logger.info 'Configuring the project'
    # FIXME: once the GUI is finished, it should just be
    # if Platform.is_graphical?
    if ENV['MAKECONF_GUI'] == 'yes' and Platform.is_graphical?
      ui = Makeconf::GUI.new(@project)
      ui.main_loop
    else
      Makeconf.configure_project(@project)
    end
  end

  def initialize(options = {})
    raise ArgumentError unless options.kind_of?(Hash)
    options.each do |k,v|
      case k
      when :minimum_version, :log_level
        send(k.to_s + '=',v)
      else
        raise ArgumentError, "Unknown argument #{k}"
      end
    end
  end

  # Check if the current version is equal to or greater than the minimum required version
  def minimum_version=(version)
    if version > 0.1
      throw "This version of Makeconf is too old. Please upgrade to version #{version} or newer"
    end
  end

  # TODO: support multiple projects
  def project(id = 'default')
    @project
  end

  def project=(obj)
    #raise ArgumentError unless options.kind_of?(Project)
    @project = obj
  end

  private

  # Examine the operating environment and set configuration options
  def Makeconf.configure_project(project)
    @@project = project
    parse_options

    makefile = Makefile.new
    toplevel_init(makefile)

    @@installer.configure(project)
    project.makefile = @@makefile
    project.installer = @@installer
    project.configure
    project.finalize
    project.write_config_h
    project.write_config_yaml
    project.write_configure
    makefile.merge! project.to_make

    puts 'creating Makefile'
    makefile.write('Makefile')
  end

  # Add rules and targets used in the top-level Makefile
  def Makeconf.toplevel_init(makefile)
    makefile.add_target('dist', [], [])
    makefile.add_dependency('distclean', 'clean')
    makefile.add_rule('distclean', Platform.rm('Makefile'))
  end

end