text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<!--#log4j中有5级logger ,#FATAL 0 ,#ERROR 3 ,#WARN 4 ,#INFO 6 ,#DEBUG 7 -->
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>

	<!--将级别为DEBUG的信息输出到控制台 -->
	<appender name="DEBUG" class="org.apache.log4j.ConsoleAppender">
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d{yyy-MM-dd HH:mm:ss} [%-5p] %c {%F:%L} - %m%n" />
		</layout>
		<filter class="org.apache.log4j.varia.LevelRangeFilter">
			<param name="LevelMin" value="DEBUG" />
			<param name="LevelMax" value="DEBUG" />
		</filter>
	</appender>

	<!--将级别为INFO的信息输出到控制台 -->
	<appender name="INFO" class="org.apache.log4j.ConsoleAppender">
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d{yyy-MM-dd HH:mm:ss} [%-5p] %c {%F:%L} - %m%n" />
		</layout>
		<filter class="org.apache.log4j.varia.LevelRangeFilter">
			<param name="LevelMin" value="INFO" />
			<param name="LevelMax" value="INFO" />
		</filter>
	</appender>

	<!--将级别为WARN的信息输出到文件 -->
	<appender name="WARN" class="org.apache.log4j.ConsoleAppender">
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d{yyy-MM-dd HH:mm:ss} [%-5p] %c {%F:%L} - %m%n" />
		</layout>
		<filter class="org.apache.log4j.varia.LevelRangeFilter">
			<param name="LevelMin" value="WARN" />
			<param name="LevelMax" value="WARN" />
		</filter>
	</appender>

	<!--将级别为ERROR的信息输出到文件 -->
	<appender name="ERROR" class="org.apache.log4j.ConsoleAppender">
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d{yyy-MM-dd HH:mm:ss} [%-5p] %c {%F:%L} - %m%n" />
		</layout>
		<filter class="org.apache.log4j.varia.LevelRangeFilter">
			<param name="LevelMin" value="ERROR" />
			<param name="LevelMax" value="ERROR" />
		</filter>
	</appender>

	<!--将级别为FATAL的信息输出到文件 -->
	<appender name="FATAL" class="org.apache.log4j.ConsoleAppender">
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d{yyy-MM-dd HH:mm:ss} [%-5p] %c {%F:%L} - %m%n" />
		</layout>
		<filter class="org.apache.log4j.varia.LevelRangeFilter">
			<param name="LevelMin" value="FATAL" />
			<param name="LevelMax" value="FATAL" />
		</filter>
	</appender>

	<logger name="org.springframework">
		<level value="DEBUG" />
	</logger>
	<logger name="org.springframework.web">
		<level value="DEBUG" />
	</logger>

	<logger name="com.ibatis">
		<level value="DEBUG" />
	</logger>
	<logger name="java.sql.Connection">
		<level value="DEBUG" />
	</logger>
	<logger name="java.sql.Statement">
		<level value="DEBUG" />
	</logger>
	<logger name="java.sql.ResultSet">
		<level value="DEBUG" />
	</logger>

	<root>
		<priority value="DEBUG" />
		<level value="DEBUG" />
		<appender-ref ref="DEBUG" />
	</root>

</log4j:configuration>


text:
<?xml version="1.0" encoding="utf-8"?>
<pathInterpolator android:pathData="M 0,0 c 0.6,0 0.2,1 1,1"
  xmlns:android="http://schemas.android.com/apk/res/android" />

redpajama_set_name: RedPajamaGithub


text:
package io.bootique.logback.sentry;

import io.sentry.SentryClient;
import io.sentry.connection.Connection;
import io.sentry.context.ContextManager;

/**
 * Wrapper for {@link SentryClient}.
 *
 * @author Ibragimov Ruslan
 */
public class BootiqueSentryClient extends SentryClient {
    public BootiqueSentryClient(Connection connection, ContextManager contextManager) {
        super(connection, contextManager);
    }
}


text:
#include "berryExtensionTracker.h"

#include <berryIExtension.h>
#include <berryIExtensionPoint.h>
#include <berryIExtensionPointFilter.h>
#include <berryIExtensionRegistry.h>
#include <berryIExtensionChangeHandler.h>
#include <berryIRegistryEventListener.h>
#include <berryListenerList.h>
#include <berryLog.h>
#include "internal/berrySimpleExtensionPointFilter.h"
#include <berryPlatform.h>

#include <QSet>
#include <QHash>
#include <QMutex>

namespace berry {

struct ExtensionTracker::Impl
{
  struct HandlerWrapper;

  ExtensionTracker* const q;
  QHash<IExtension::Pointer, QSet<Object::Pointer> > extensionToStrongObjects;
  QHash<IExtension::Pointer, QSet<Object::WeakPtr> > extensionToWeakObjects;
  //ListenerList<HandlerWrapper> handlers;
  QHash<IExtensionChangeHandler*, HandlerWrapper*> handlerToWrapper;
  QMutex mutex;
  bool closed;
  IExtensionRegistry* registry; // the registry that this tacker works with

  Impl(ExtensionTracker* q, IExtensionRegistry* theRegistry)
    : q(q)
    , closed(false)
    , registry(theRegistry)
  {}

};

struct ExtensionTracker::Impl::HandlerWrapper : public IRegistryEventListener
{
  ExtensionTracker* const q;
  IExtensionChangeHandler* const handler;

  HandlerWrapper(ExtensionTracker* q, IExtensionChangeHandler* handler)
    : q(q)
    , handler(handler)
  {}

  bool operator==(const HandlerWrapper& target) const
  {
    return handler == target.handler;
  }

  void Added(const QList<IExtension::Pointer>& extensions) override
  {
    for (int i = 0; i < extensions.size(); ++i)
    {
      q->ApplyAdd(handler, extensions[i]);
    }
  }

  void Removed(const QList<IExtension::Pointer>& extensions) override
  {
    QList<QList<Object::Pointer> > removedObjects;
    {
      QMutexLocker lock(&q->d->mutex);
      for (int i = 0; i < extensions.size(); ++i)
      {
        QSet<Object::Pointer> associatedObjects = q->d->extensionToStrongObjects.take(extensions[i]);
        foreach(const Object::WeakPtr& ptr, q->d->extensionToWeakObjects.take(extensions[i]))
        {
          if (!ptr.Expired())
          {
            associatedObjects.insert(ptr.Lock());
          }
        }
        removedObjects.push_back(associatedObjects.toList());
      }
    }
    for (int i = 0; i < extensions.size(); ++i)
    {
      q->ApplyRemove(handler, extensions[i], removedObjects[i]);
    }
  }

  void Added(const QList<IExtensionPoint::Pointer>& /*extensionPoints*/) override
  {
    // do nothing
  }

  void Removed(const QList<IExtensionPoint::Pointer>& /*extensionPoints*/) override
  {
    // do nothing
  }
};

ExtensionTracker::ExtensionTracker()
{
  this->Init(Platform::GetExtensionRegistry());
}

ExtensionTracker::~ExtensionTracker()
{
}

ExtensionTracker::ExtensionTracker(IExtensionRegistry* theRegistry)
  : d()
{
  this->Init(theRegistry);
}

void ExtensionTracker::Init(IExtensionRegistry* registry)
{
  d.reset(new Impl(this, registry));
  if (registry == nullptr)
  {
    //RuntimeLog.log(new Status(IStatus.ERROR, RegistryMessages.OWNER_NAME, 0, RegistryMessages.registry_no_default, null));
    BERRY_ERROR << "Extension tracker was unable to obtain BlueBerry extension registry.";
    d->closed = true;
  }
}

void ExtensionTracker::RegisterHandler(IExtensionChangeHandler* handler, const IExtensionPointFilter& filter)
{
  QMutexLocker lock(&d->mutex);
  if (d->closed) return;
  auto iter = d->handlerToWrapper.insert(handler, new Impl::HandlerWrapper(this, handler));
  d->registry->AddListener(iter.value(), filter);
}

void ExtensionTracker::RegisterHandler(IExtensionChangeHandler* handler, const QString& extensionPointId)
{
  this->RegisterHandler(handler, extensionPointId.isEmpty() ? IExtensionPointFilter(nullptr)
                                                            : IExtensionPointFilter(new SimpleExtensionPointFilter(extensionPointId)));
}

void ExtensionTracker::UnregisterHandler(IExtensionChangeHandler* handler)
{
  QMutexLocker lock(&d->mutex);
  if (d->closed) return;
  IRegistryEventListener* listener = d->handlerToWrapper.take(handler);
  d->registry->RemoveListener(listener);
  delete listener;
}

void ExtensionTracker::RegisterObject(const SmartPointer<IExtension>& element, const SmartPointer<Object>& object, IExtensionTracker::ReferenceType referenceType)
{
  if (element.IsNull() || object.IsNull()) return;

  QMutexLocker lock(&d->mutex);
  if (d->closed) return;

  if (referenceType == REF_STRONG)
  {
    d->extensionToStrongObjects[element].insert(object);
  }
  else if (referenceType == REF_WEAK)
  {
    d->extensionToWeakObjects[element].insert(Object::WeakPtr(object));
  }
}

QList<SmartPointer<Object> > ExtensionTracker::GetObjects(const IExtension::Pointer& element) const
{
  QSet<Object::Pointer> objectSet;

  QMutexLocker lock(&d->mutex);
  if (d->closed) return objectSet.toList();

  auto iter = d->extensionToStrongObjects.find(element);
  if (iter != d->extensionToStrongObjects.end())
  {
    objectSet.unite(iter.value());
  }
  auto iter2 = d->extensionToWeakObjects.find(element);
  if (iter2 != d->extensionToWeakObjects.end())
  {
    foreach(const Object::WeakPtr& ptr, iter2.value())
    {
      if (!ptr.Expired()) objectSet.insert(ptr.Lock());
    }
  }
  return objectSet.toList();
}

void ExtensionTracker::Close()
{
  QMutexLocker lock(&d->mutex);
  if (d->closed) return;
  foreach(Impl::HandlerWrapper* wrapper, d->handlerToWrapper.values())
  {
    d->registry->RemoveListener(wrapper);
    delete wrapper;
  }
  d->extensionToStrongObjects.clear();
  d->extensionToWeakObjects.clear();
  d->handlerToWrapper.clear();

  d->closed = true;
}

void ExtensionTracker::UnregisterObject(const SmartPointer<IExtension>& extension, const SmartPointer<Object>& object)
{
  QMutexLocker lock(&d->mutex);
  if (d->closed) return;

  auto iter = d->extensionToStrongObjects.find(extension);
  if (iter != d->extensionToStrongObjects.end())
  {
    iter.value().remove(object);
  }
  auto iter2 = d->extensionToWeakObjects.find(extension);
  if (iter2 != d->extensionToWeakObjects.end())
  {
    iter2.value().remove(Object::WeakPtr(object));
  }
}

QList<SmartPointer<Object> > ExtensionTracker::UnregisterObject(const SmartPointer<IExtension>& extension)
{
  QSet<Object::Pointer> objectSet;

  QMutexLocker lock(&d->mutex);
  if (d->closed) return objectSet.toList();

  auto iter = d->extensionToStrongObjects.find(extension);
  if (iter != d->extensionToStrongObjects.end())
  {
    objectSet.unite(iter.value());
    d->extensionToStrongObjects.erase(iter);
  }
  auto iter2 = d->extensionToWeakObjects.find(extension);
  if (iter2 != d->extensionToWeakObjects.end())
  {
    foreach(const Object::WeakPtr& ptr, iter2.value())
    {
      if (!ptr.Expired()) objectSet.insert(ptr.Lock());
    }
    d->extensionToWeakObjects.erase(iter2);
  }

  return objectSet.toList();
}

IExtensionPointFilter ExtensionTracker::CreateExtensionPointFilter(const SmartPointer<IExtensionPoint>& xpt)
{
  struct F : IExtensionPointFilter::Concept {
    const IExtensionPoint::Pointer m_Xpt;

    F(const IExtensionPoint::Pointer& xp)
      : m_Xpt(xp)
    {}

    bool Matches(const IExtensionPoint* target) const override
    {
      return m_Xpt == target;
    }
  };

  return IExtensionPointFilter(new F(xpt));
}

IExtensionPointFilter ExtensionTracker::CreateExtensionPointFilter(const QList<SmartPointer<IExtensionPoint> >& xpts)
{
  struct F : IExtensionPointFilter::Concept {
    const QList<IExtensionPoint::Pointer> m_Xpts;

    F(const QList<IExtensionPoint::Pointer>& xps)
      : m_Xpts(xps)
    {}

    bool Matches(const IExtensionPoint* target) const override
    {
      for (int i = 0; i < m_Xpts.size(); i++)
      {
        if (m_Xpts[i] == target)
        {
          return true;
        }
      }
      return false;
    }
  };

  return IExtensionPointFilter(new F(xpts));
}

IExtensionPointFilter ExtensionTracker::CreateNamespaceFilter(const QString& id)
{
  struct F : IExtensionPointFilter::Concept {
    const QString m_Id;

    F(const QString& id)
      : m_Id(id)
    {}

    bool Matches(const IExtensionPoint* target) const override
    {
      return m_Id == target->GetNamespaceIdentifier();
    }
  };

  return IExtensionPointFilter(new F(id));
}

void ExtensionTracker::ApplyAdd(IExtensionChangeHandler* handler, const SmartPointer<IExtension>& extension)
{
  handler->AddExtension(this, extension);
}

void ExtensionTracker::ApplyRemove(IExtensionChangeHandler* handler, const SmartPointer<IExtension>& removedExtension, const QList<Object::Pointer>& removedObjects)
{
  handler->RemoveExtension(removedExtension, removedObjects);
}

}


text:
package io.netty.handler.ssl;

import io.netty.buffer.ByteBufAllocator;
import io.netty.util.internal.PlatformDependent;

import javax.net.ssl.SSLEngine;

/**
 * The {@link JdkApplicationProtocolNegotiator} to use if you need ALPN and are using {@link SslProvider#JDK}.
 *
 * @deprecated use {@link ApplicationProtocolConfig}.
 */
@Deprecated
public final class JdkAlpnApplicationProtocolNegotiator extends JdkBaseApplicationProtocolNegotiator {
    private static final boolean AVAILABLE = Conscrypt.isAvailable() ||
                                             jdkAlpnSupported() ||
                                             JettyAlpnSslEngine.isAvailable();

    private static final SslEngineWrapperFactory ALPN_WRAPPER = AVAILABLE ? new AlpnWrapper() : new FailureWrapper();

    /**
     * Create a new instance.
     * @param protocols The order of iteration determines the preference of support for protocols.
     */
    public JdkAlpnApplicationProtocolNegotiator(Iterable<String> protocols) {
        this(false, protocols);
    }

    /**
     * Create a new instance.
     * @param protocols The order of iteration determines the preference of support for protocols.
     */
    public JdkAlpnApplicationProtocolNegotiator(String... protocols) {
        this(false, protocols);
    }

    /**
     * Create a new instance.
     * @param failIfNoCommonProtocols Fail with a fatal alert if not common protocols are detected.
     * @param protocols The order of iteration determines the preference of support for protocols.
     */
    public JdkAlpnApplicationProtocolNegotiator(boolean failIfNoCommonProtocols, Iterable<String> protocols) {
        this(failIfNoCommonProtocols, failIfNoCommonProtocols, protocols);
    }

    /**
     * Create a new instance.
     * @param failIfNoCommonProtocols Fail with a fatal alert if not common protocols are detected.
     * @param protocols The order of iteration determines the preference of support for protocols.
     */
    public JdkAlpnApplicationProtocolNegotiator(boolean failIfNoCommonProtocols, String... protocols) {
        this(failIfNoCommonProtocols, failIfNoCommonProtocols, protocols);
    }

    /**
     * Create a new instance.
     * @param clientFailIfNoCommonProtocols Client side fail with a fatal alert if not common protocols are detected.
     * @param serverFailIfNoCommonProtocols Server side fail with a fatal alert if not common protocols are detected.
     * @param protocols The order of iteration determines the preference of support for protocols.
     */
    public JdkAlpnApplicationProtocolNegotiator(boolean clientFailIfNoCommonProtocols,
            boolean serverFailIfNoCommonProtocols, Iterable<String> protocols) {
        this(serverFailIfNoCommonProtocols ? FAIL_SELECTOR_FACTORY : NO_FAIL_SELECTOR_FACTORY,
                clientFailIfNoCommonProtocols ? FAIL_SELECTION_LISTENER_FACTORY : NO_FAIL_SELECTION_LISTENER_FACTORY,
                protocols);
    }

    /**
     * Create a new instance.
     * @param clientFailIfNoCommonProtocols Client side fail with a fatal alert if not common protocols are detected.
     * @param serverFailIfNoCommonProtocols Server side fail with a fatal alert if not common protocols are detected.
     * @param protocols The order of iteration determines the preference of support for protocols.
     */
    public JdkAlpnApplicationProtocolNegotiator(boolean clientFailIfNoCommonProtocols,
            boolean serverFailIfNoCommonProtocols, String... protocols) {
        this(serverFailIfNoCommonProtocols ? FAIL_SELECTOR_FACTORY : NO_FAIL_SELECTOR_FACTORY,
                clientFailIfNoCommonProtocols ? FAIL_SELECTION_LISTENER_FACTORY : NO_FAIL_SELECTION_LISTENER_FACTORY,
                protocols);
    }

    /**
     * Create a new instance.
     * @param selectorFactory The factory which provides classes responsible for selecting the protocol.
     * @param listenerFactory The factory which provides to be notified of which protocol was selected.
     * @param protocols The order of iteration determines the preference of support for protocols.
     */
    public JdkAlpnApplicationProtocolNegotiator(ProtocolSelectorFactory selectorFactory,
            ProtocolSelectionListenerFactory listenerFactory, Iterable<String> protocols) {
        super(ALPN_WRAPPER, selectorFactory, listenerFactory, protocols);
    }

    /**
     * Create a new instance.
     * @param selectorFactory The factory which provides classes responsible for selecting the protocol.
     * @param listenerFactory The factory which provides to be notified of which protocol was selected.
     * @param protocols The order of iteration determines the preference of support for protocols.
     */
    public JdkAlpnApplicationProtocolNegotiator(ProtocolSelectorFactory selectorFactory,
            ProtocolSelectionListenerFactory listenerFactory, String... protocols) {
        super(ALPN_WRAPPER, selectorFactory, listenerFactory, protocols);
    }

    private static final class FailureWrapper extends AllocatorAwareSslEngineWrapperFactory {
        @Override
        public SSLEngine wrapSslEngine(SSLEngine engine, ByteBufAllocator alloc,
                                       JdkApplicationProtocolNegotiator applicationNegotiator, boolean isServer) {
            throw new RuntimeException("ALPN unsupported. Is your classpath configured correctly?"
                    + " For Conscrypt, add the appropriate Conscrypt JAR to classpath and set the security provider."
                    + " For Jetty-ALPN, see "
                    + "http://www.eclipse.org/jetty/documentation/current/alpn-chapter.html#alpn-starting");
        }
    }

    private static final class AlpnWrapper extends AllocatorAwareSslEngineWrapperFactory {
        @Override
        public SSLEngine wrapSslEngine(SSLEngine engine, ByteBufAllocator alloc,
                                       JdkApplicationProtocolNegotiator applicationNegotiator, boolean isServer) {
            if (Conscrypt.isEngineSupported(engine)) {
                return isServer ? ConscryptAlpnSslEngine.newServerEngine(engine, alloc, applicationNegotiator)
                        : ConscryptAlpnSslEngine.newClientEngine(engine, alloc, applicationNegotiator);
            }
            if (jdkAlpnSupported()) {
                return new Java9SslEngine(engine, applicationNegotiator, isServer);
            }
            if (JettyAlpnSslEngine.isAvailable()) {
                return isServer ? JettyAlpnSslEngine.newServerEngine(engine, applicationNegotiator)
                        : JettyAlpnSslEngine.newClientEngine(engine, applicationNegotiator);
            }
            throw new RuntimeException("Unable to wrap SSLEngine of type " + engine.getClass().getName());
        }
    }

    static boolean jdkAlpnSupported() {
        return PlatformDependent.javaVersion() >= 9 && Java9SslUtils.supportsAlpn();
    }
}


text:
package thinkbot

import (
	"github.com/thinkofdeath/thinkbot/command"
	"regexp"
)

// BotConfig allows for initial setup of a bot during
// init
type BotConfig struct {
	bot *Bot

	Password string
	Prefixes []string
}

// SetPermissionContainer sets the container used for checking
// permissions for irc users.
func (b *BotConfig) SetPermissionContainer(pc PermissionContainer) {
	b.bot.setPermissionContainer(pc)
}

// Commands returns the command registry for this bot.
// It is not safe to retain the result of this method after
// init
func (b *BotConfig) Commands() *command.Registry {
	return &b.bot.commands
}

// AddChatHandler adds a handler which is called
// whenever the passed regexp matches a message
func (b *BotConfig) AddChatHandler(r *regexp.Regexp, f chatHandlerFunc) {
	b.bot.chatHandlers = append(b.bot.chatHandlers, chatHandler{r, f})
}


text:
/) {
                    // TODO: get shape when required

                    T min_val = static_cast<T*>(ctx->buffer_data[arg0_buffer_index])[0];
                    T max_val = static_cast<T*>(ctx->buffer_data[arg1_buffer_index])[0];
                    bool use_fixed_seed = static_cast<bool>(
                        static_cast<char*>(ctx->buffer_data[arg3_buffer_index])[0]);

                    if (!use_fixed_seed)
                    {
                        reference::random_uniform<T>(
                            static_cast<T*>(ctx->buffer_data[out_buffer_index]),
                            min_val,
                            max_val,
                            element_count,
                            static_cast<UniformRNGState*>(ctx->states[index]));
                    }
                    else
                    {
                        reference::random_uniform_with_fixed_seed<T>(
                            static_cast<T*>(ctx->buffer_data[out_buffer_index]),
                            min_val,
                            max_val,
                            element_count,
                            fixed_seed);
                    }
                };
                return functor;
            }

            template <>
            void Builder::BUILDER_DECL(ngraph::op::v0::RandomUniform)
            {
                auto& functors = external_function->get_functors();
                CPUKernelFunctor functor;
                if (args[2].get_element_type() != element::i64)
                {
                    throw ngraph_error("Unsupported index 2 element type");
                }
                auto element_type = args[0].get_element_type();
#if defined(__GNUC__) && !(__GNUC__ == 4 && __GNUC_MINOR__ == 8)
#pragma GCC diagnostic push
#pragma GCC diagnostic error "-Wswitch"
#pragma GCC diagnostic error "-Wswitch-enum"
#endif
                switch (element_type)
                {
                case element::Type_t::undefined:
                    NGRAPH_CHECK(false,
                                 "Encountered 'undefined' element type in fold_constant_convert");
                    break;
                case element::Type_t::dynamic:
                    NGRAPH_CHECK(false,
                                 "Encountered 'dynamic' element type in fold_constant_convert");
                    break;
                case element::Type_t::u1:
                    NGRAPH_CHECK(false, "Encountered 'u1' element type in fold_constant_convert");
                    break;
                case element::Type_t::boolean:
                    functor = prepare_functor<char>(node, args, out, external_function);
                    break;
                case element::Type_t::bf16:
                    functor = prepare_functor<bfloat16>(node, args, out, external_function);
                    break;
                case element::Type_t::f16:
                    functor = prepare_functor<float16>(node, args, out, external_function);
                    break;
                case element::Type_t::f32:
                    functor = prepare_functor<float>(node, args, out, external_function);
                    break;
                case element::Type_t::f64:
                    functor = prepare_functor<double>(node, args, out, external_function);
                    break;
                case element::Type_t::i8:
                    functor = prepare_functor<int8_t>(node, args, out, external_function);
                    break;
                case element::Type_t::i16:
                    functor = prepare_functor<int16_t>(node, args, out, external_function);
                    break;
                case element::Type_t::i32:
                    functor = prepare_functor<int32_t>(node, args, out, external_function);
                    break;
                case element::Type_t::i64:
                    functor = prepare_functor<int64_t>(node, args, out, external_function);
                    break;
                case element::Type_t::u8:
                    functor = prepare_functor<uint8_t>(node, args, out, external_function);
                    break;
                case element::Type_t::u16:
                    functor = prepare_functor<uint16_t>(node, args, out, external_function);
                    break;
                case element::Type_t::u32:
                    functor = prepare_functor<uint32_t>(node, args, out, external_function);
                    break;
                case element::Type_t::u64:
                    functor = prepare_functor<uint64_t>(node, args, out, external_function);
                    break;
                    NGRAPH_UNREACHABLE("Unexpected switch case");
                }

#if defined(__GNUC__) && !(__GNUC__ == 4 && __GNUC_MINOR__ == 8)
#pragma GCC diagnostic pop
#endif

                functors.emplace_back(functor);
            }

            void register_builders_random_uniform_cpp()
            {
                REGISTER_OP_BUILDER(ngraph::op::v0::RandomUniform);
            }
        }
    }
}


text:
#ifndef mozilla_dom_DocumentRendererNativeIDChild
#define mozilla_dom_DocumentRendererNativeIDChild

#include "mozilla/ipc/PDocumentRendererNativeIDChild.h"

class nsIDOMWindow;
struct gfxMatrix;

namespace mozilla {
namespace ipc {

class DocumentRendererNativeIDChild : public PDocumentRendererNativeIDChild
{
public:
    DocumentRendererNativeIDChild();
    virtual ~DocumentRendererNativeIDChild();

    bool RenderDocument(nsIDOMWindow* window, const PRInt32& x,
                        const PRInt32& y, const PRInt32& w,
                        const PRInt32& h, const nsString& aBGColor,
                        const PRUint32& flags, const bool& flush,
                        const gfxMatrix& aMatrix,
                        const PRInt32& nativeID);

private:

    DISALLOW_EVIL_CONSTRUCTORS(DocumentRendererNativeIDChild);
};

}
}

#endif


text:
require 'zmachine'
require 'zmachine/channel'

module ZMachine
  class ZMQChannel < Channel

    extend Forwardable

    def_delegator :@socket, :identity
    def_delegator :@socket, :identity=

    def initialize
      super
      @raw = true
    end

    def selectable_fd
      @socket.fd
    end

    def bind(address, type)
      ZMachine.logger.debug("zmachine:zmq_channel:#{__method__}", channel: self) if ZMachine.debug
      @bound = true
      @connected = true
      @socket = ZContext.create_socket(type)
      @socket.bind(address)
    end

    def bound?
      @bound
    end

    def accept
      ZMachine.logger.debug("zmachine:zmq_channel:#{__method__}", channel: self) if ZMachine.debug
      self
    end

    def connect(address, type)
      ZMachine.logger.debug("zmachine:zmq_channel:#{__method__}", channel: self) if ZMachine.debug
      @connection_pending = true
      @socket = ZContext.create_socket(type)
      @socket.connect(address)
    end

    def connection_pending?
      @connection_pending
    end

    def finish_connecting
      ZMachine.logger.debug("zmachine:zmq_channel:#{__method__}", channel: self) if ZMachine.debug
      return unless connection_pending?
      @connected = true
    end

    def connected?
      @connected
    end

    def read_inbound_data
      ZMachine.logger.debug("zmachine:zmq_channel:#{__method__}", channel: self) if ZMachine.debug
      return nil unless can_recv?
      data = ZMsg.recv_msg(@socket)
      data = String.from_java_bytes(data.first.data) unless @raw
      data
    end

    def close!
      ZMachine.logger.debug("zmachine:zmq_channel:#{__method__}", channel: self) if ZMachine.debug
      @closed = true
      @connected = false
      @bound = false
      ZContext.destroy_socket(@socket)
    end

    def closed?
      @closed
    end

    def peer
      raise RuntimeError.new("ZMQChannel has no peer")
    end

    # see comment in ConnectionManager#process
    def can_recv?
      @socket.events & ZMQ::Poller::POLLIN == ZMQ::Poller::POLLIN
    end

  end
end


text:
import logging
from datetime import datetime

from sqlalchemy import or_

from aleph.core import db, url_for
from aleph.model.user import User
from aleph.model.forms import ListForm

log = logging.getLogger(__name__)

list_user_table = db.Table('list_user', db.metadata,
    db.Column('list_id', db.Integer, db.ForeignKey('list.id')), # noqa
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')) # noqa
)

class List(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    label = db.Column(db.Unicode)
    public = db.Column(db.Boolean, default=False)

    creator_id = db.Column(db.Integer(), db.ForeignKey('user.id'),
                           nullable=True)
    creator = db.relationship(User)

    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow,
                           onupdate=datetime.utcnow)

    users = db.relationship(User, secondary=list_user_table,
                            backref='lists')

    def to_dict(self):
        return {
            'id': self.id,
            'api_url': url_for('lists.view', id=self.id),
            'entities_api_url': url_for('entities.index', list=self.id),
            'label': self.label,
            'public': self.public,
            'creator_id': self.creator_id,
            'created_at': self.created_at,
            'updated_at': self.updated_at
        }

    @classmethod
    def create(cls, data, user):
        lst = cls()
        lst.update(data, user)
        lst.creator = user
        db.session.add(lst)
        return lst

    def update(self, data, user):
        data = ListForm().deserialize(data)
        self.label = data.get('label')
        if data.get('public') is not None:
            self.public = data.get('public')
        users = set(data.get('users', []))
        if user is not None:
            users.add(user)
        self.users = list(users)

    def delete(self):
        # for entity in self.entities:
        #     entity.delete()
        db.session.delete(self)

    @classmethod
    def by_label(cls, label):
        q = db.session.query(cls).filter_by(label=label)
        return q.first()

    @classmethod
    def by_id(cls, id):
        q = db.session.query(cls).filter_by(id=id)
        return q.first()

    @classmethod
    def user_list_ids(cls, user=None, include_public=True):
        logged_in = user is not None and user.is_authenticated()
        q = db.session.query(cls.id)
        conds = []
        if include_public:
            conds.append(cls.public == True) # noqa
        if logged_in:
            conds.append(cls.users.any(User.id == user.id))
        if not len(conds):
            return []
        if not (logged_in and user.is_admin):
            q = q.filter(or_(*conds))
        return [c.id for c in q.all()]

    @classmethod
    def all_by_user(cls, user):
        q = db.session.query(cls)
        q = q.filter(cls.id.in_(cls.user_list_ids(user)))
        q = q.order_by(cls.id.desc())
        return q

    @property
    def terms(self):
        from aleph.model.entity import Entity
        from aleph.model.selector import Selector
        q = db.session.query(Selector.normalized)
        q = q.join(Entity, Entity.id == Selector.entity_id)
        q = q.filter(Entity.list_id == self.id)
        q = q.distinct()
        return set([r[0] for r in q])

    def __repr__(self):
        return '<List(%r, %r)>' % (self.id, self.label)

    def __unicode__(self):
        return self.label


text:
package home.smart.fly.animations.ui.activity;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

import home.smart.fly.animations.R;

public class BitmapMeshActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bitmap_mesh);
    }
}


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

namespace StatusBoard.Core
{
    public class WebResponse
    {
        readonly string content;
        readonly string contentType;
        readonly int? httpStatusCode;

        public WebResponse(string content, string contentType, int? httpStatusCode = null)
        {
            this.httpStatusCode = httpStatusCode;
            this.contentType = contentType;
            this.content = content;
        }

        public string Content
        {
            get
            {
                return content;
            }
        }

        public string ContentType
        {
            get
            {
                return contentType;
            }
        }

        public int? HttpStatusCode
        {
            get
            {
                return httpStatusCode;
            }
        }

        public static WebResponse JsonResponse(string content, int? httpStatusCode = null)
        {
            return new WebResponse(content, "application/json", httpStatusCode);
        }

        public static WebResponse HtmlResponse(string content)
        {
            return new WebResponse(content, "text/html; charset=utf-8");
        }

        public static WebResponse JavaScriptResponse(string content)
        {
            return new WebResponse(content, "application/javascript; charset=utf-8");
        }

        public static WebResponse CssResponse(string content)
        {
            return new WebResponse(content, "text/css; charset=utf-8");
        }

        public static WebResponse JsonResponse(object content, int? httpStatusCode = null)
        {
            var jsonResponse = Newtonsoft.Json.JsonConvert.SerializeObject(content);
            return JsonResponse(jsonResponse, httpStatusCode);
        }
    }
}


text: default_app_config = 'mailer.apps.MailerConfig'


text:
package com.yahoo.omid.tso.messages;

import java.io.DataOutputStream;
import java.io.IOException;

import org.jboss.netty.buffer.ChannelBuffer;

import com.yahoo.omid.tso.TSOMessage;

/**
 * The message object for sending a commit request to TSO
 *
 * @author maysam
 *
 */
public class TimestampResponse implements TSOMessage {

    /**
     * the timestamp
     */
    public long timestamp;

    /**
     * Constructor from timestamp
     *
     * @param t
     */
    public TimestampResponse(long t) {
        timestamp = t;
    }

    public TimestampResponse() {
    }

    @Override
    public String toString() {
        return "TimestampResponse: T_s:" + timestamp;
    }

    @Override
    public void writeObject(ChannelBuffer buffer) {
        buffer.writeLong(timestamp);
    }

    @Override
    public void readObject(ChannelBuffer aInputStream) {
        timestamp = aInputStream.readLong();
    }

    @Override
    public void writeObject(DataOutputStream aOutputStream) throws IOException {
        aOutputStream.writeLong(timestamp);
    }
}


text:
using System;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Controls;

namespace MagicSquare
{
    class NumberValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            string pattern = @"\A[1-9]+\Z";

            if (Regex.IsMatch((string)value, pattern))
            {
                return new ValidationResult(true, null);
            }
            else
            {
                return new ValidationResult(false, "Value must be a number in interval [1-9]!");
            }
        }
    }
}


text:
package org.verdictdb.commons;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.ArrayUtils;

import com.google.common.collect.Sets;

public class StringSplitter {

  /**
   * Splits a given query using the delimiter. The delimiters in quote chars are ignored.
   *
   * <p>Note: I have tried many regex-based and the Apache commons library for this, but they do not
   * work. Regex throws StackOverflowError, and the StringTokenizer by the commons library is
   * incorrect for our purpose.
   *
   * @param sql
   */
  public static List<String> splitOnSemicolon(String sql, String quoteChars) {
    List<String> splitted = new ArrayList<>();
    Map<Character, Integer> quoteCharCounts = new HashMap<>();
    Set<Character> quoteCharSet = Sets.newHashSet(ArrayUtils.toObject(quoteChars.toCharArray()));
    for (char c : quoteCharSet) {
      quoteCharCounts.put(c, 0);
    }
    char delimiter = ';';

    StringBuilder beginConstructed = new StringBuilder();
    for (char c : sql.toCharArray()) {
      // when encountered a delimiter
      if (c == delimiter) {
        // if there is no odd-count quote chars, we create a new sql
        boolean oddCountQuoteExist = false;
        for (int count : quoteCharCounts.values()) {
          if (count % 2 == 1) {
            oddCountQuoteExist = true;
            break;
          }
        }
        if (oddCountQuoteExist == false) {
          // create a new sql
          splitted.add(beginConstructed.toString());
          beginConstructed = new StringBuilder();
          ;
        }
      } else {
        beginConstructed.append(c);
        if (quoteCharSet.contains(c)) {
          quoteCharCounts.put(c, quoteCharCounts.get(c) + 1);
        }
      }
    }
    // if there anything remaining, add it as a separate sql
    if (beginConstructed.length() > 0) {
      String s = beginConstructed.toString();
      if (s.trim().length() > 0) {
        splitted.add(s);
      }
    }

    return splitted;
  }

}


text:
namespace ui {

// A partial implementation of GLOzone for EGL.
class GLOzoneEGL : public GLOzone {
 public:
  GLOzoneEGL() {}
  ~GLOzoneEGL() override {}

  // GLOzone:
  bool InitializeGLOneOffPlatform() override;
  bool InitializeStaticGLBindings(gl::GLImplementation implementation) override;
  void InitializeDebugGLBindings() override;
  void ClearGLBindings() override;
  bool GetGLWindowSystemBindingInfo(
      gl::GLWindowSystemBindingInfo* info) override;
  scoped_refptr<gl::GLContext> CreateGLContext(
      gl::GLShareGroup* share_group,
      gl::GLSurface* compatible_surface,
      gl::GpuPreference gpu_preference) override;
  scoped_refptr<gl::GLSurface> CreateViewGLSurface(
      gfx::AcceleratedWidget window) override = 0;
  scoped_refptr<gl::GLSurface> CreateSurfacelessViewGLSurface(
      gfx::AcceleratedWidget window) override;
  scoped_refptr<gl::GLSurface> CreateOffscreenGLSurface(
      const gfx::Size& size) override = 0;

 protected:
  // Returns native platform display handle. This is used to obtain the EGL
  // display connection for the native display.
  virtual intptr_t GetNativeDisplay() = 0;

  // Sets up GL bindings for the native surface.
  virtual bool LoadGLES2Bindings() = 0;

 private:
  DISALLOW_COPY_AND_ASSIGN(GLOzoneEGL);
};

}  // namespace ui

#endif  // UI_OZONE_COMMON_GL_OZONE_EGL_H_


text:
"""Administration form for general Review Board settings."""

from collections import OrderedDict
from urllib.parse import urlparse

from django import forms
from django.conf import settings
from django.contrib.sites.models import Site
from django.utils.module_loading import import_string
from django.utils.translation import gettext, gettext_lazy as _
from djblets.cache.backend_compat import normalize_cache_backend
from djblets.cache.forwarding_backend import DEFAULT_FORWARD_CACHE_ALIAS
from djblets.forms.fields import TimeZoneField
from djblets.siteconfig.forms import SiteSettingsForm

from reviewboard.admin.siteconfig import load_site_config

class BaseCacheSettingsForm(forms.Form):
    """Base class for a cache backend settings form.

    Version Added:
        4.0
    """

    def load(self, cache_backend_settings):
        """Load the cache backend settings into the form.

        Args:
            cache_backend_settings (dict):
                Settings for the cache backend.
        """
        pass

    def build_cache_backend_settings(self):
        """Build new cache backend settings from the form data.

        Returns:
            dict:
            The new cache backend settings.
        """
        raise NotImplementedError

class FileCacheSettingsForm(BaseCacheSettingsForm):
    """Settings for the file-based cache backend.

    This backend is recommended only for simple test setups and development.
    """

    cache_path = forms.CharField(
        label=_('Cache Path'),
        help_text=_(
            'The file location for the cache. This must be writable by '
            'the web server.'
        ),
        required=True,
        widget=forms.TextInput(attrs={'size': '50'}),
        error_messages={
            'required': 'A valid cache path must be provided.'
        })

    def load(self, cache_backend_settings):
        """Load the cache backend settings into the form.

        Args:
            cache_backend_settings (dict):
                Settings for the cache backend.
        """
        cache_locations = cache_backend_settings['LOCATION']

        if not isinstance(cache_locations, list):
            cache_locations = [cache_locations]

        self.fields['cache_path'].initial = ';'.join(cache_locations)

    def build_cache_backend_settings(self):
        """Build new cache backend settings from the form data.

        Returns:
            dict:
            The new cache backend settings.
        """
        return {
            'LOCATION': self.cleaned_data['cache_path'],
        }

    def clean_cache_path(self):
        """Clean the cache_path field.

        This will strip whitespace around the value and return it.

        Returns:
            unicode:
            The cache path, with whitespace stripped.
        """
        return self.cleaned_data['cache_path'].strip()

    class Meta:
        title = _('Local File Cache Settings')

class LocalMemoryCacheSettingsForm(BaseCacheSettingsForm):
    """Settings for the local memory cache backend.

    This is only available for development setups and cannot be used in
    production.
    """

    def build_cache_backend_settings(self):
        """Build new cache backend settings from the form data.

        Returns:
            dict:
            The new cache backend settings.
        """
        # We want to specify a "reviewboard" location to keep items
        # separate from those in other caches.
        return {
            'LOCATION': 'reviewboard'
        }

    class Meta:
        title = _('Local Memory Cache Settings')

class MemcachedSettingsForm(BaseCacheSettingsForm):
    """Settings for the memcached backend.

    This is the recommended caching backend.
    """

    cache_host = forms.CharField(
        label=_('Cache Hosts'),
        help_text=_('The host or hosts used for the cache, in hostname:port '
                    'form. Multiple hosts can be specified by separating '
                    'them with a semicolon (;).'),
        required=True,
        widget=forms.TextInput(attrs={'size': '50'}),
        error_messages={
            'required': 'A valid cache host must be provided.'
        })

    def load(self, cache_backend_settings):
        """Load the cache backend settings into the form.

        Args:
            cache_backend_settings (dict):
                Settings for the cache backend.
        """
        cache_locations = cache_backend_settings['LOCATION']

        if not isinstance(cache_locations, list):
            cache_locations = [cache_locations]

        self.fields['cache_host'].initial = ';'.join(cache_locations)

    def build_cache_backend_settings(self):
        """Build new cache backend settings from the form data.

        Returns:
            dict:
            The new cache backend settings.
        """
        return {
            'LOCATION': self.cleaned_data['cache_host'].split(';'),
        }

    def clean_cache_host(self):
        """Clean the cache_host field.

        This will strip whitespace around the value and return it.

        Returns:
            unicode:
            The cache host, with whitespace stripped.
        """
        return self.cleaned_data['cache_host'].strip()

    class Meta:
        title = _('Memcached Settings')

class GeneralSettingsForm(SiteSettingsForm):
    """General settings for Review Board."""

    _cache_backends = OrderedDict([
        ('locmem', {
            'name': _('Local memory cache (developer-only)'),
            'available': not settings.PRODUCTION,
            'backend_cls_path':
                'django.core.cache.backends.locmem.LocMemCache',
            'form_cls': LocalMemoryCacheSettingsForm,
        }),
        ('memcached', {
            'name': _('Memcached (recommended)'),
            'backend_cls_path':
                'django.core.cache.backends.memcached.PyMemcacheCache',
            'legacy_backend_cls_paths': [
                'django.core.cache.backends.memcached.CacheClass',
                'django.core.cache.backends.memcached.MemcachedCache',
            ],
            'form_cls': MemcachedSettingsForm,

        }),
        ('file', {
            'name': _('Local file cache'),
            'backend_cls_path':
                'django.core.cache.backends.filebased.FileBasedCache',
            'form_cls': FileCacheSettingsForm,
        }),
    ])

    CACHE_VALIDATION_KEY = '__rb-cache-validation__'
    CACHE_VALIDATION_VALUE = 12345

    company = forms.CharField(
        label=_('Company/Organization'),
        help_text=_('The optional name of your company or organization. '
                    'This will be displayed on your support page.'),
        required=False,
        widget=forms.TextInput(attrs={'size': '30'}))

    server = forms.CharField(
        label=_('Server'),
        help_text=_('The URL of this Review Board server. This should not '
                    'contain the subdirectory Review Board is installed in.'),
        widget=forms.TextInput(attrs={'size': '30'}))

    site_read_only = forms.BooleanField(
        label=_('Enable read-only mode'),
        help_text=_('Prevent non-superusers from making any changes to '
                    'Review Board.'),
        required=False)

    read_only_message = forms.CharField(
        label=_('Read-only message'),
        help_text=_('A custom message displayed when the site is in '
                    'read-only mode.'),
        required=False,
        widget=forms.TextInput(attrs={'size': '30'}))

    site_media_url = forms.CharField(
        label=_('Media URL'),
        help_text=(_('The URL to the media files. Set to '
                     '%smedia/ to use the default media path on '
                     'this server.')
                   % settings.SITE_ROOT),
        required=True,
        widget=forms.TextInput(attrs={'size': '30'}))

    site_static_url = forms.CharField(
        label=_('Static URL'),
        help_text=(_('The URL to the static files, such as JavaScript files, '
                     'CSS files, and images that are bundled with Review '
                     'Board or third-party extensions. Set to '
                     '%sstatic/ to use the default static path '
                     'on this server.')
                   % settings.SITE_ROOT),
        required=True,
        widget=forms.TextInput(attrs={'size': '30'}))

    site_admin_name = forms.CharField(
        label=_('Administrator Name'),
        required=True,
        widget=forms.TextInput(attrs={'size': '30'}))
    site_admin_email = forms.EmailField(
        label=_('Administrator E-Mail'),
        required=True,
        widget=forms.TextInput(attrs={'size': '30'}))

    locale_timezone = TimeZoneField(
        label=_('Time Zone'),
        required=True,
        help_text=_('The time zone used for all dates on this server.'))

    cache_type = forms.ChoiceField(
        label=_('Cache Backend'),
        help_text=_('The type of server-side caching to use.'),
        required=True,
        widget=forms.Select(attrs={
            'data-subform-group': 'cache-backend',
        }))

    def __init__(self, siteconfig, data=None, files=None, *args, **kwargs):
        """Initialize the settings form.

        Args:
            siteconfig (djblets.siteconfig.models.SiteConfiguration):
                The site configuration being changed.

            data (dict, optional):
                The submitted form data.

            files (dict, optional):
                The uploaded file data.

            *args (tuple):
                Additional positional arguments for the form.

            **kwargs (dict):
                Additional keyword arguments for the form.
        """
        self.cache_backend_forms = {
            backend_id: backend_info['form_cls'](data=data, files=files)
            for backend_id, backend_info in self._cache_backends.items()
            if backend_info.get('available', True)
        }

        super(GeneralSettingsForm, self).__init__(siteconfig,
                                                  data=data,
                                                  files=files,
                                                  *args, **kwargs)

    def load(self):
        """Load settings from the form.

        This will populate initial fields based on the site configuration.
        It takes care to transition legacy (<= Review Board 1.7) cache
        backends, if still used in production, to a modern configuration.
        """
        domain_method = self.siteconfig.get('site_domain_method')
        site = Site.objects.get_current()

        # Load the rest of the settings from the form.
        super(GeneralSettingsForm, self).load()

        # Load the cache settings.
        cache_backend_info = self.siteconfig.get('cache_backend')
        cache_backend = (
            normalize_cache_backend(cache_backend_info,
                                    DEFAULT_FORWARD_CACHE_ALIAS) or
            normalize_cache_backend(cache_backend_info))

        cache_backend_path = cache_backend['BACKEND']
        cache_type = 'custom'

        for _cache_type, backend_info in self._cache_backends.items():
            if (cache_backend_path == backend_info['backend_cls_path'] or
                cache_backend_path in backend_info.get(
                    'legacy_backend_cls_paths', [])):
                cache_type = _cache_type
                break

        cache_type_choices = [
            (backend_id, backend_info['name'])
            for backend_id, backend_info in self._cache_backends.items()
            if backend_info.get('available', True)
        ]

        if cache_type == 'custom':
            cache_type_choices.append(('custom', gettext('Custom')))

        cache_type_field = self.fields['cache_type']
        cache_type_field.choices = tuple(cache_type_choices)
        cache_type_field.initial = cache_type

        if cache_type in self.cache_backend_forms:
            self.cache_backend_forms[cache_type].load(cache_backend)

        # This must come after we've loaded the general settings.
        self.fields['server'].initial = '%s://%s' % (domain_method,
                                                     site.domain)

    def save(self):
        """Save the form.

        This will write the new configuration to the database. It will then
        force a site configuration reload.
        """
        server = self.cleaned_data['server']

        if '://' not in server:
            # urlparse doesn't properly handle URLs without a scheme. It
            # believes the domain is actually the path. So we apply a prefix.
            server = 'http://' + server

        url_parts = urlparse(server)
        domain_method = url_parts[0]
        domain_name = url_parts[1]

        if domain_name.endswith('/'):
            domain_name = domain_name[:-1]

        site = Site.objects.get_current()

        if site.domain != domain_name:
            site.domain = domain_name
            site.save(update_fields=['domain'])

        self.siteconfig.set('site_domain_method', domain_method)

        cache_type = self.cleaned_data['cache_type']

        if cache_type != 'custom':
            cache_backend_info = self._cache_backends[cache_type]
            cache_form = self.cache_backend_forms[cache_type]
            cache_backend_settings = cache_form.build_cache_backend_settings()

            self.siteconfig.set('cache_backend', {
                DEFAULT_FORWARD_CACHE_ALIAS: dict({
                    'BACKEND': cache_backend_info['backend_cls_path'],
                }, **cache_backend_settings),
            })

        super(GeneralSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()

    def is_valid(self):
        """Return whether the form is valid.

        This will check that this form, and the form for any selected cache
        backend, is valid.

        Returns:
            bool:
            ``True`` if all form fields are valid. ``False`` if any are
            invalid.
        """
        if not super(GeneralSettingsForm, self).is_valid():
            return False

        cache_form = self.cache_backend_forms.get(
            self.cleaned_data['cache_type'])

        return cache_form is None or cache_form.is_valid()

    def clean(self):
        """Clean and validate the form fields.

        This is called after all individual fields are validated. It does
        the remaining work of checking to make sure the resulting configuration
        is valid.

        Returns:
            dict:
            The cleaned form data.
        """
        cleaned_data = super(GeneralSettingsForm, self).clean()

        if 'cache_type' not in self.errors:
            cache_type = cleaned_data['cache_type']
            cache_backend_info = self._cache_backends.get(cache_type)
            cache_form = self.cache_backend_forms.get(cache_type)

            if (cache_backend_info is not None and
                cache_form is not None and
                cache_form.is_valid()):
                cache_backend = None

                try:
                    cache_backend_settings = \
                        cache_form.build_cache_backend_settings()

                    cache_cls = import_string(
                        cache_backend_info['backend_cls_path'])
                    cache_backend = cache_cls(
                        cache_backend_settings.get('LOCATION'),
                        {})

                    cache_backend.set(self.CACHE_VALIDATION_KEY,
                                      self.CACHE_VALIDATION_VALUE)
                    value = cache_backend.get(self.CACHE_VALIDATION_KEY)
                    cache_backend.delete(self.CACHE_VALIDATION_KEY)

                    if value != self.CACHE_VALIDATION_VALUE:
                        self.errors['cache_type'] = self.error_class([
                            _('Unable to store and retrieve values from this '
                              'caching backend. There may be a problem '
                              'connecting.')
                        ])
                except Exception as e:
                    self.errors['cache_type'] = self.error_class([
                        _('Error with this caching configuration: %s')
                        % e
                    ])

                # If the cache backend is open, try closing it. This may fail,
                # so we want to ignore any failures.
                if cache_backend is not None:
                    try:
                        cache_backend.close()
                    except Exception:
                        pass

        return cleaned_data

    class Meta:
        title = _('General Settings')
        save_blacklist = ('server', 'cache_type')

        subforms = (
            {
                'subforms_attr': 'cache_backend_forms',
                'controller_field': 'cache_type',
            },
        )

        fieldsets = (
            {
                'title': _('Site Settings'),
                'classes': ('wide',),
                'fields': ('company', 'server', 'site_media_url',
                           'site_static_url', 'site_admin_name',
                           'site_admin_email', 'locale_timezone',
                           'site_read_only', 'read_only_message'),
            },
            {
                'title': _('Cache Settings'),
                'classes': ('wide',),
                'fields': ('cache_type',),
            },
        )


text:
layout: post
title: "Writing to the AWS Lambda SAM Local container /tmp filesystem"
date: 2018-01-07 14:10:00
comments: true
published: true
tags: lambda sam local
redirect_to: https://bacchi.org/posts/sam-local-readwrite-filesystem/
---

While using [AWS Lambda SAM
Local](https://docs.aws.amazon.com/lambda/latest/dg/test-sam-local.html) to test
Lambda functions locally, I encountered an error writing to the current
directory where the function was running in the container (/var/task/). I'm not
claiming a best practice of writing to the filesystem while running a Lambda
function, but that's part of my learning process for the moment, and I will
investigate other workflows shortly. But what I was able to get working
successfuly was writing to the /tmp filesystem instead of the current working
directory.

Here is the example code where it writes to the current directory with an the
result that we encounter the error that the directory is read only:

<!--more-->

{% highlight shell %}
[mbacchi@nuc2 sample-sam-local-write]$ cat samlocalwrite.py
import os
import sys

def handler(event, context):
    print("Starting samlocalwrite lambda handler function")
    print("Directory provided from event was: {}".format(event['directory']))

    remote_repo = event['directory']

    #local_repo = os.path.join(os.path.sep, "tmp", os.path.basename(event['directory']))
    local_repo = os.path.basename(event['directory'])

    if not os.path.exists(local_repo):
        os.makedirs(local_repo)

    with open(local_repo + "blah.txt", 'w') as f:
        f.write('blah\n')

    return "Hello"
{% endhighlight %}

And the output of the `sam local invoke` command:

{% highlight shell %}
[mbacchi@nuc2 sample-sam-local-write]$ sam local invoke "SamLocalWriteFunction" -e event.json
2018/01/07 15:50:24 Successfully parsed template.yaml
2018/01/07 15:50:24 Connected to Docker 1.35
2018/01/07 15:50:24 Fetching lambci/lambda:python3.6 image for python3.6 runtime...
python3.6: Pulling from lambci/lambda
f338a32fa56c: Pull complete
4926b20b634f: Pull complete
298eae5902d7: Pull complete
e58d162628c7: Pull complete
e02bc73f2e71: Pull complete
Digest: sha256:0682e157b34e18cf182b2aaffb501971c7a0c08c785f337629122b7de34e3945
Status: Downloaded newer image for lambci/lambda:python3.6
2018/01/07 15:51:25 Invoking samlocalwrite.handler (python3.6)
2018/01/07 15:51:25 Decompressing /home/mbacchi/data/repos/mbacchi/sample-sam-local-write/samlocalwrite.zip
2018/01/07 15:51:46 WARNING: No AWS credentials found. Missing credentials may lead to slow startup times as detailed in https://github.com/awslabs/aws-sam-local/issues/134
2018/01/07 15:51:46 Mounting /tmp/aws-sam-local-1515358285999917851 as /var/task:ro inside runtime container
START RequestId: 9371dabf-9678-4fc4-83d8-5d8c8cf8c9fa Version: $LATEST
Starting samlocalwrite lambda handler function
Directory provided from event was: whatever
[Errno 30] Read-only file system: 'whatever': OSError
Traceback (most recent call last):
  File "/var/task/samlocalwrite.py", line 18, in handler
    os.makedirs(local_repo)
  File "/var/lang/lib/python3.6/os.py", line 220, in makedirs
    mkdir(name, mode)
OSError: [Errno 30] Read-only file system: 'whatever'

END RequestId: 9371dabf-9678-4fc4-83d8-5d8c8cf8c9fa
REPORT RequestId: 9371dabf-9678-4fc4-83d8-5d8c8cf8c9fa Duration: 161 ms Billed Duration: 0 ms Memory Size: 0 MB Max Memory Used: 18 MB

{"errorMessage": "[Errno 30] Read-only file system: 'whatever'", "errorType": "OSError", "stackTrace": [["/var/task/samlocalwrite.py", 18, "handler", "os.makedirs(local_repo)"], ["/var/lang/lib/python3.6/os.py", 220, "makedirs", "mkdir(name, mode)"]]}

{% endhighlight %}

If we make a slight modification to write to the `/tmp` filesystem:

{% highlight shell %}
[mbacchi@nuc2 sample-sam-local-write]$ diff samlocalwrite.py samlocalwrite-new.py
14,15c14,15
<     #local_repo = os.path.join(os.path.sep, "tmp", os.path.basename(event['directory']))
<     local_repo = os.path.basename(event['directory'])
---
>     local_repo = os.path.join(os.path.sep, "tmp", os.path.basename(event['directory']))
>     #local_repo = os.path.basename(event['directory'])
{% endhighlight %}

We get a successful run:

{% highlight shell %}
[mbacchi@nuc2 sample-sam-local-write]$ sam local invoke "SamLocalWriteFunction" -e event.json
2018/01/07 15:55:54 Successfully parsed template.yaml
2018/01/07 15:55:54 Connected to Docker 1.35
2018/01/07 15:55:54 Fetching lambci/lambda:python3.6 image for python3.6 runtime...
python3.6: Pulling from lambci/lambda
Digest: sha256:0682e157b34e18cf182b2aaffb501971c7a0c08c785f337629122b7de34e3945
Status: Image is up to date for lambci/lambda:python3.6
2018/01/07 15:55:54 Invoking samlocalwrite.handler (python3.6)
2018/01/07 15:55:54 Decompressing /home/mbacchi/data/repos/mbacchi/sample-sam-local-write/samlocalwrite.zip
2018/01/07 15:56:15 WARNING: No AWS credentials found. Missing credentials may lead to slow startup times as detailed in https://github.com/awslabs/aws-sam-local/issues/134
2018/01/07 15:56:15 Mounting /tmp/aws-sam-local-1515358554848977835 as /var/task:ro inside runtime container
START RequestId: 0af0a302-49db-4ca2-a0fa-db31acb0182a Version: $LATEST
Starting samlocalwrite lambda handler function
Directory provided from event was: whatever
END RequestId: 0af0a302-49db-4ca2-a0fa-db31acb0182a
REPORT RequestId: 0af0a302-49db-4ca2-a0fa-db31acb0182a Duration: 160 ms Billed Duration: 0 ms Memory Size: 0 MB Max Memory Used: 18 MB

"Hello"
{% endhighlight %}

Again, this may not be the perfect solution but it is a way to write to the
image filesystem if necessary in your Lambda function.


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

namespace P09.LongerLine
{
    public class Program
    {
        public static void Main(string[] args)
        {
            double x1Line01 = double.Parse(Console.ReadLine());
            double y1Line01 = double.Parse(Console.ReadLine());
            double x2Line01 = double.Parse(Console.ReadLine());
            double y2Line01 = double.Parse(Console.ReadLine());
            double x1Line02 = double.Parse(Console.ReadLine());
            double y1Line02 = double.Parse(Console.ReadLine());
            double x2Line02 = double.Parse(Console.ReadLine());
            double y2Line02 = double.Parse(Console.ReadLine());

            CloseToCenter(x1Line01, y1Line01, x2Line01, y2Line01, x1Line02, y1Line02, x2Line02, y2Line02);
        }

        private static void CloseToCenter(double x1First, double y1First, double x2First, double y2First, double x1Second, double y1Second, double x2Second, double y2Second)
        {
            if ((Math.Abs(x1First + x2First) < Math.Abs(x1Second + x2Second)) || (Math.Abs(y1First + y2First) < Math.Abs(y1Second + y2Second)))
            {
                if ((Math.Abs(x1Second) < Math.Abs(x2Second)) && (Math.Abs(y1Second) < Math.Abs(y2Second)))
                {
                    Console.WriteLine($"({x1Second}, {y1Second })({x2Second}, {y2Second})");
                }
                else
                {
                    Console.WriteLine($"({x2Second}, {y2Second})({x1Second}, {y1Second})");
                }

            }
            else if ((Math.Abs(x1First - x2First) == Math.Abs(x1Second - x2Second)) || (Math.Abs(y1First - y2First) == Math.Abs(y1Second - y2Second)))
            {
                if ((Math.Abs(x1First) < Math.Abs(x2First)) && (Math.Abs(y1First) < Math.Abs(y2First)))
                {
                    Console.WriteLine($"({x1First}, {y1First })({x2First}, {y2First})");
                }
                else
                {
                    Console.WriteLine($"({x2First}, {y2First})({x1First}, {y1First})");
                }
            }
            else
            {
                if ((Math.Abs(x1First) < Math.Abs(x2First)) && (Math.Abs(y1First) < Math.Abs(y2First)))
                {
                    Console.WriteLine($"({x1First}, {y1First })({x2First}, {y2First})");
                }
                else
                {
                    Console.WriteLine($"({x2First}, {y2First})({x1First}, {y1First})");
                }
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;

namespace SendFile
{
    public partial class SendFile : Form
    {
        public SendFile()
        {
            InitializeComponent();
        }

        private void SendFile_Load(object sender, EventArgs e)
        {
            if (System.IO.File.Exists(@"Config.xml"))
            {
                string ver = version("Config.xml");
                string[] sulyver = ver.Split('.');
                int tangver = int.Parse(sulyver[1]) + 1;
                txtVer.Text = sulyver[0] +"."+tangver.ToString();
            }
        }
        private void uploadFile(string FTPAddress, string filePath, string username, string password)
        {
            //Create FTP request
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTPAddress + "/" + Path.GetFileName(filePath));

            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(username, password);
            request.UsePassive = false;
            request.UseBinary = true;
            request.KeepAlive = false;
            request.Proxy = null;

            //Load the file
            FileStream stream = File.OpenRead(filePath);
            byte[] buffer = new byte[stream.Length];

            stream.Read(buffer, 0, buffer.Length);
            stream.Close();

            //Upload file
            Stream reqStream = request.GetRequestStream();
            reqStream.Write(buffer, 0, buffer.Length);
            reqStream.Close();
        }

        private void Send_Click(object sender, EventArgs e)
        {
            XmlDocument myXmlDocument = new XmlDocument();
            myXmlDocument.Load("Config.xml");
            XmlNode node;
            node = myXmlDocument.DocumentElement;
           // MessageBox.Show(node.Name);
            foreach (XmlNode nodechild in node.ChildNodes)
            {
                //MessageBox.Show(nodechild.Name);
                if (nodechild.Name == "version")
                {
                    nodechild.InnerText = txtVer.Text;
                }

            }
            myXmlDocument.Save("Config.xml");

          uploadFile(host.Text, linkfile.Text, username.Text, password.Text);
          uploadFile(host.Text, txtUpdate.Text, username.Text, password.Text);
          uploadFile(host.Text, "Config.xml", username.Text, password.Text);
          MessageBox.Show("Gửi yêu cầu xử lý thành công.");
          XmlDocument myXmlDocument1 = new XmlDocument();
          myXmlDocument1.Load(@"E:\DEV\HFC\HFC\HFC\bin\Debug\Config.xml");
          XmlNode node1;
          node1 = myXmlDocument1.DocumentElement;
          // MessageBox.Show(node.Name);
          foreach (XmlNode nodechild in node1.ChildNodes)
          {
              //MessageBox.Show(nodechild.Name);
              if (nodechild.Name == "version")
              {
                  nodechild.InnerText = txtVer.Text;
              }

          }
          myXmlDocument1.Save(@"E:\DEV\HFC\HFC\HFC\bin\Debug\Config.xml");

        }

        private void button1_Click(object sender, EventArgs e)
        {
           // MessageBox.Show(version());
        }
        private static string version(string url)
        {
            string _config = "";
            XmlTextReader xmlReader = new XmlTextReader(url);
            while (xmlReader.Read())
            {
                if (xmlReader.Name == "version")
                {
                    _config = xmlReader.ReadElementString();
                }
            }
            xmlReader.Close();
            return _config;
        }
    }
}


text:
@extends('layouts.app')
{{-- Content --}}
@section('content')

            Нова послуга

    @if (isset($services))
    {!! Form::model($services, array('url' => URL::to('services') . '/' . $services->id, 'method' => 'PUT', 'class' => 'bf', 'files'=> true)) !!}
    @else
    {!! Form::open(array('url' => URL::to('services'), 'method' => 'UPDATE', 'class' => 'bf', 'files'=> true)) !!}
    @endif

has('name') ? 'has-error' : '' }}">
                {!! Form::label('name', 'Назва сервісу', array('class' => 'control-label')) !!}

                    {!! Form::text('name', null, array('class' => 'form-control')) !!}
                    {{ $errors->first('name', ':message') }}

has('detail') ? 'has-error' : '' }}">
                {!! Form::label('detail', 'Деталі', array('class' => 'control-label')) !!}

                    {!! Form::text('detail', null, array('class' => 'form-control')) !!}
                    {{ $errors->first('detail', ':message') }}

has('activityTime') ? 'has-error' : '' }}">
                {!! Form::label('activityTime', 'Активний час', array('class' => 'control-label')) !!}

                    {!! Form::text('activityTime', null, array('class' => 'form-control')) !!}
                    {{ $errors->first('activityTime', ':message') }}

has('value') ? 'has-error' : '' }}">
                {!! Form::label('value', 'Ціна', array('class' => 'control-label')) !!}

                    {!! Form::text('value', null, array('class' => 'form-control')) !!}
                    {{ $errors->first('value', ':message') }}

has('enabled') ? 'has-error' : '' }}">
                {!! Form::label('enabled', 'Активний?', array('class' => 'control-label')) !!}

                    {!! Form::label('enabled', 'Активний', array('class' => 'control-label')) !!}
                    {!! Form::radio('enabled', '1', @isset($services)? $services->enabled : '1') !!}
                    {!! Form::label('enabled', 'Деактивний', array('class' => 'control-label')) !!}
                    {!! Form::radio('enabled', '0', @isset($services)? $services->enabled : '0') !!}
                    {{ $errors->first('enabled', ':message') }}

                <button type="reset" class="btn btn-sm btn-default">
                     Очистити
                </button>
                <button type="submit" class="btn btn-sm btn-success">

                    @if	(isset($services))
                        Зберегти
                    @else
                        Створити
                    @endif
                </button>

        {!! Form::close() !!}
        @stop


text:
var App = require('./App');
var Dispatcher = require('./Dispatcher');
var EventEmitter = require('events').EventEmitter;
var Baobab = require('baobab');
var { createApp } = require('deku');

class Bootstrapper {
  // Create app instance attached to some real DOM node
  create (config = {}, rootEl) {
    var app = new App();
    this.configure(config, app.locator, rootEl);
    return app;
  }

  // Register core services
  configure (config, locator, rootEl) {
    var eventBus = new EventEmitter();
    var tree = new Baobab({}, config.baobab);

    eventBus.setMaxListeners(0);
    locator.registerInstance('eventBus', eventBus);
    locator.registerInstance('config', config);
    locator.registerInstance('tree', tree);
    locator.register('dispatcher', Dispatcher, config, true);

    var dispatcher = locator.resolve('dispatcher');
    var documentRenderer = createApp(rootEl, dispatcher.run.bind(dispatcher));
    locator.registerInstance('documentRenderer', documentRenderer);
  }
}

module.exports = new Bootstrapper();


text:
package com.google.code.nanorm.internal.mapping.parameter;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.google.code.nanorm.TypeHandler;
import com.google.code.nanorm.TypeHandlerFactory;
import com.google.code.nanorm.internal.config.ParameterMappingConfig;

/**
 * Parameter mapper. Maps IN/OUT parmaters to {@link PreparedStatement}/
 * {@link CallableStatement}.
 *
 * @author Ivan Dubrov
 */
public final class ParameterMapper {

    private final int index;

    private final Object[] args;

    private final ParameterMappingConfig config;

    /**
     * Constructor.
     *
     * @param config parameter mapping configuration
     * @param index parameter index
     * @param args argument to bind to
     */
    public ParameterMapper(ParameterMappingConfig config, int index, Object[] args) {
        this.config = config;
        this.index = index;
        this.args = args;
    }

    /**
     * Map IN parameter to {@link PreparedStatement}.
     *
     * @param factory type handler factory
     * @param ps prepared statement to set parameters to
     * @throws SQLException exception while setting parameter
     */
    public void mapParameterIn(TypeHandlerFactory factory, PreparedStatement ps)
            throws SQLException {
        // IN parameter
        if (config.getGetter() != null) {
            TypeHandler<?> typeHandler = factory.getTypeHandler(config.getType());

            Object value = config.getGetter().getValue(args);
            typeHandler.setParameter(ps, index, value);
        }
    }

    /**
     * TODO: Check out is used only for @Call
     *
     * Map OUT parameter from {@link CallableStatement}.
     *
     * @param factory type handler factory
     * @param cs callable statement to get parameter from
     * @throws SQLException exception while getting value
     */
    public void mapParameterOut(TypeHandlerFactory factory, CallableStatement cs)
            throws SQLException {
        // OUT parameter
        if (config.getSetter() != null) {
            TypeHandler<?> typeHandler = factory.getTypeHandler(config.getType());

            // XXX: NULL handling for primitive types?
            Object value = typeHandler.getValue(cs, index);
            config.getSetter().setValue(args, value);
        }
    }

    /**
     * Register OUT parameter.
     * @param factory type handler factory
     * @param cs callable statement
     * @throws SQLException exception while registering parameter
     */
    public void registerOutParameter(TypeHandlerFactory factory, CallableStatement cs)
            throws SQLException {
        if (config.getSetter() != null) {
            TypeHandler<?> typeHandler = factory.getTypeHandler(config.getType());

            cs.registerOutParameter(index, typeHandler.getSqlType());
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return String.valueOf(config.getGetter().getValue(args));
    }
}


text:
package com.jetbrains.python.inspections;

import com.intellij.testFramework.LightProjectDescriptor;
import com.jetbrains.python.fixtures.PyTestCase;
import com.jetbrains.python.psi.LanguageLevel;

/**
 * @author vlan
 */
public class Py3TypeCheckerInspectionTest extends PyTestCase {
  public static final String TEST_DIRECTORY = "inspections/PyTypeCheckerInspection/";

  @Override
  protected LightProjectDescriptor getProjectDescriptor() {
    return ourPy3Descriptor;
  }

  private void doTest() {
    runWithLanguageLevel(LanguageLevel.PYTHON36, () -> {
      myFixture.copyDirectoryToProject("typing", "");
      myFixture.configureByFile(TEST_DIRECTORY + getTestName(false) + ".py");
      myFixture.enableInspections(PyTypeCheckerInspection.class);
      myFixture.checkHighlighting(true, false, true);
    });
  }

  private void doMultiFileTest() {
    runWithLanguageLevel(LanguageLevel.PYTHON36, () -> {
      myFixture.copyDirectoryToProject(TEST_DIRECTORY + getTestName(false), "");
      myFixture.copyDirectoryToProject("typing", "");
      myFixture.configureFromTempProjectFile("a.py");
      myFixture.enableInspections(PyTypeCheckerInspection.class);
      myFixture.checkHighlighting(true, false, true);
    });
  }

  // PY-9289
  public void testWithOpenBinaryPy3() {
    doTest();
  }

  // PY-10660
  public void testStructUnpackPy3() {
    doMultiFileTest();
  }

  public void testBuiltinsPy3() {
    doTest();
  }

  // PY-16125
  public void testTypingIterableForLoop() {
    doTest();
  }

  // PY-16146
  public void testTypingListSubscriptionExpression() {
    doTest();
  }

  // PY-16855
  public void testTypingTypeVarWithUnresolvedBound() {
    doTest();
  }

  // PY-16303
  public void testTypingTupleInDocstring() {
    doTest();
  }

  // PY-16898
  public void testAsyncForIterable() {
    doTest();
  }

  // PY-18275
  public void testStrFormatPy3() {
    doTest();
  }

  // PY-18762
  public void testHomogeneousTuples() {
    myFixture.copyDirectoryToProject("typing/typing.py", TEST_DIRECTORY);
    doTest();
  }

  // PY-9924
  public void testTupleGetItemWithSlice() {
    doTest();
  }

  // PY-9924
  public void testListGetItemWithSlice() {
    doTest();
  }

  // PY-20460
  public void testStringGetItemWithSlice() {
    doTest();
  }

  // PY-20460
  public void testBytesGetItemWithSlice() {
    doTest();
  }

  // PY-19796
  public void testOrd() {
    doTest();
  }

  // PY-12944
  public void testDelegatedGenerator() {
    doTest();
  }

  // PY-16055
  public void testFunctionReturnTypePy3() {
    doTest();
  }

  // PY-20770
  public void testAsyncForOverAsyncGenerator() {
    doTest();
  }

  // PY-20770
  public void testForOverAsyncGenerator() {
    doTest();
  }

  // PY-20770
  public void testAsyncComprehensionsOverAsyncGenerator() {
    doTest();
  }

  // PY-20770
  public void testAsyncComprehensionsOverGenerator() {
    doTest();
  }

  // PY-20770
  public void testComprehensionsOverAsyncGenerator() {
    doTest();
  }

  // PY-21048
  public void testAsyncFunctionReturnType() {
    doTest();
  }
}


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ITCC.HTTP.SslConfigUtil.GUI
{
    /// <summary>
    /// Interaction logic for CertificateViewControl.xaml
    /// </summary>
    public partial class CertificateViewControl : UserControl
    {
        #region IssuedTo
        public string IssuedTo
        {
            get { return (string)GetValue(IssuedToProperty); }
            set { SetValue(IssuedToProperty, value); }
        }
        public static readonly DependencyProperty IssuedToProperty = DependencyProperty.Register(
            "IssuedTo",
            typeof(string),
            typeof(CertificateViewControl),
            new PropertyMetadata(null, OnIssuedToChanged));

        public static string GetIssuedTo(UIElement element) => (string)element.GetValue(IssuedToProperty);
        public static void SetIssuedTo(UIElement element, string value) => element.SetValue(IssuedToProperty, value);
        private static void OnIssuedToChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as CertificateViewControl;
            if (control == null)
                return;

            control.IssuedToTextBlock.Text = (string) e.NewValue;
        }
        #endregion

        #region IssuedBy
        public string IssuedBy
        {
            get { return (string)GetValue(IssuedByProperty); }
            set { SetValue(IssuedByProperty, value); }
        }
        public static readonly DependencyProperty IssuedByProperty = DependencyProperty.Register(
            "IssuedBy",
            typeof(string),
            typeof(CertificateViewControl),
            new PropertyMetadata(null, OnIssuedByChanged));

        public static string GetIssuedBy(UIElement element) => (string)element.GetValue(IssuedByProperty);
        public static void SetIssuedBy(UIElement element, string value) => element.SetValue(IssuedByProperty, value);
        private static void OnIssuedByChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as CertificateViewControl;
            if (control == null)
                return;

            control.IssuedByTextBox.Text = (string)e.NewValue;

            control.Background = control.IssuedTo == control.IssuedBy ? Brushes.LightGoldenrodYellow : Brushes.PaleGreen;
        }
        #endregion

        #region ValidUntil
        public DateTime ValidUntil
        {
            get { return (DateTime)GetValue(ValidUntilProperty); }
            set { SetValue(ValidUntilProperty, value); }
        }
        public static readonly DependencyProperty ValidUntilProperty = DependencyProperty.Register(
            "ValidUntil",
            typeof(DateTime),
            typeof(CertificateViewControl),
            new PropertyMetadata(new DateTime(), OnValidUntilChanged));

        public static DateTime GetValidUntil(UIElement element) => (DateTime)element.GetValue(ValidUntilProperty);
        public static void SetValidUntil(UIElement element, DateTime value) => element.SetValue(ValidUntilProperty, value);
        private static void OnValidUntilChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as CertificateViewControl;
            if (control == null)
                return;

            control.ValidUntolTextBlock.Text = ((DateTime) e.NewValue).ToShortDateString();
        }

        #endregion

        public CertificateViewControl()
        {
            InitializeComponent();
        }
    }
}