text:
#ifndef AVMediaCaptureSource_h
#define AVMediaCaptureSource_h

#if ENABLE(MEDIA_STREAM) && USE(AVFOUNDATION)

#include "GenericTaskQueue.h"
#include "RealtimeMediaSource.h"
#include "Timer.h"
#include <wtf/Function.h>
#include <wtf/RetainPtr.h>
#include <wtf/WeakPtr.h>

OBJC_CLASS AVCaptureAudioDataOutput;
OBJC_CLASS AVCaptureConnection;
OBJC_CLASS AVCaptureDevice;
OBJC_CLASS AVCaptureOutput;
OBJC_CLASS AVCaptureSession;
OBJC_CLASS AVCaptureVideoDataOutput;
OBJC_CLASS WebCoreAVMediaCaptureSourceObserver;

typedef struct opaqueCMSampleBuffer *CMSampleBufferRef;

namespace WebCore {

class AVMediaCaptureSource : public RealtimeMediaSource {
public:
    virtual ~AVMediaCaptureSource();

    virtual void captureOutputDidOutputSampleBufferFromConnection(AVCaptureOutput*, CMSampleBufferRef, AVCaptureConnection*) = 0;

    virtual void captureSessionIsRunningDidChange(bool);

    AVCaptureSession *session() const { return m_session.get(); }

    const RealtimeMediaSourceSettings& settings() override;

    void startProducingData() override;
    void stopProducingData() override;
    bool isProducingData() const override { return m_isRunning; }

    WeakPtr<AVMediaCaptureSource> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(); }

protected:
    AVMediaCaptureSource(AVCaptureDevice*, const AtomicString&, RealtimeMediaSource::Type, PassRefPtr<MediaConstraints>);

    AudioSourceProvider* audioSourceProvider() override;

    virtual void setupCaptureSession() = 0;
    virtual void shutdownCaptureSession() = 0;
    virtual void updateSettings(RealtimeMediaSourceSettings&) = 0;
    virtual void initializeCapabilities(RealtimeMediaSourceCapabilities&) = 0;
    virtual void initializeSupportedConstraints(RealtimeMediaSourceSupportedConstraints&) = 0;

    AVCaptureDevice *device() const { return m_device.get(); }

    MediaConstraints* constraints() { return m_constraints.get(); }

    RealtimeMediaSourceSupportedConstraints& supportedConstraints();
    RefPtr<RealtimeMediaSourceCapabilities> capabilities() override;

    void setVideoSampleBufferDelegate(AVCaptureVideoDataOutput*);
    void setAudioSampleBufferDelegate(AVCaptureAudioDataOutput*);

    void scheduleDeferredTask(Function<void ()>&&);

private:
    void setupSession();
    void reset() override;

    RealtimeMediaSourceSettings m_currentSettings;
    RealtimeMediaSourceSupportedConstraints m_supportedConstraints;
    WeakPtrFactory<AVMediaCaptureSource> m_weakPtrFactory;
    RetainPtr<WebCoreAVMediaCaptureSourceObserver> m_objcObserver;
    RefPtr<MediaConstraints> m_constraints;
    RefPtr<RealtimeMediaSourceCapabilities> m_capabilities;
    RetainPtr<AVCaptureSession> m_session;
    RetainPtr<AVCaptureDevice> m_device;
    bool m_isRunning { false};
};

} // namespace WebCore

#endif // ENABLE(MEDIA_STREAM)

#endif // AVMediaCaptureSource_h


text:
package com.nexuslink.wenavi.ui.weight;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by 18064 on 2018/1/30.
 */

public class SkewWallpaperView extends View {

    private static final float RATE = 0.6f;

    private Paint paint;

    public SkewWallpaperView(Context context) {
        super(context, null);
    }

    public SkewWallpaperView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SkewWallpaperView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint = new Paint();
        paint.setColor(Color.parseColor("#82B1FF"));
        Path path = new Path();
        path.moveTo(0, getHeight());
        path.lineTo(getWidth(), (float) (getHeight() * RATE));
        path.lineTo(getWidth(),0);
        path.lineTo(0,0);
        path.close();
        canvas.drawPath(path, paint);
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { defaultStyleOptions } from 'botframework-webchat-component';

import createAdaptiveCardRendererStyle from './StyleSet/AdaptiveCardRenderer';
import createAnimationCardAttachmentStyle from './StyleSet/AnimationCardAttachment';
import createAudioCardAttachmentStyle from './StyleSet/AudioCardAttachment';

// TODO: [P4] We should add a notice for people who want to use "styleSet" instead of "styleOptions".
//       "styleSet" is actually CSS stylesheet and it is based on the DOM tree.
//       DOM tree may change from time to time, thus, maintaining "styleSet" becomes a constant effort.

export default function createAdaptiveCardsStyleSet(options) {
  options = { ...defaultStyleOptions, ...options };

  return {
    adaptiveCardRenderer: createAdaptiveCardRendererStyle(options),
    animationCardAttachment: createAnimationCardAttachmentStyle(options),
    audioCardAttachment: createAudioCardAttachmentStyle(options)
  };
}


text:
package org.displaytag.export;

import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;

import javax.servlet.jsp.JspException;

import org.apache.commons.lang3.StringUtils;
import org.displaytag.model.Column;
import org.displaytag.model.ColumnIterator;
import org.displaytag.model.HeaderCell;
import org.displaytag.model.Row;
import org.displaytag.model.RowIterator;
import org.displaytag.model.TableModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *

 * Base abstract class for simple export views.
 *

 *

 * A class that extends BaseExportView simply need to provide delimiters for rows and columns.
 *

 *
 * @author Fabrizio Giustina
 *
 * @version $Revision$ ($Author$)
 */
public abstract class BaseExportView implements TextExportView {

    /**
     * logger.
     */
    private static Logger log = LoggerFactory.getLogger(BaseExportView.class);

    /**
     * TableModel to render.
     */
    private TableModel model;

    /** export full list?. */
    private boolean exportFull;

    /** include header in export?. */
    private boolean header;

    /** decorate export?. */
    private boolean decorated;

    /**
     * Sets the parameters.
     *
     * @param tableModel
     *            the table model
     * @param exportFullList
     *            the export full list
     * @param includeHeader
     *            the include header
     * @param decorateValues
     *            the decorate values
     *
     * @see org.displaytag.export.ExportView#setParameters(org.displaytag.model.TableModel, boolean, boolean, boolean)
     */
    @Override
    public void setParameters(final TableModel tableModel, final boolean exportFullList, final boolean includeHeader,
            final boolean decorateValues) {
        this.model = tableModel;
        this.exportFull = exportFullList;
        this.header = includeHeader;
        this.decorated = decorateValues;
    }

    /**
     * String to add before a row.
     *
     * @return String
     */
    protected String getRowStart() {
        return null;
    }

    /**
     * String to add after a row.
     *
     * @return String
     */
    protected String getRowEnd() {
        return null;
    }

    /**
     * String to add before a cell.
     *
     * @return String
     */
    protected String getCellStart() {
        return null;
    }

    /**
     * String to add after a cell.
     *
     * @return String
     */
    protected abstract String getCellEnd();

    /**
     * String to add to the top of document.
     *
     * @return String
     */
    protected String getDocumentStart() {
        return null;
    }

    /**
     * String to add to the end of document.
     *
     * @return String
     */
    protected String getDocumentEnd() {
        return null;
    }

    /**
     * always append cell end string?.
     *
     * @return boolean
     */
    protected abstract boolean getAlwaysAppendCellEnd();

    /**
     * always append row end string?.
     *
     * @return boolean
     */
    protected abstract boolean getAlwaysAppendRowEnd();

    /**
     * can be implemented to escape values for different output.
     *
     * @param value
     *            original column value
     *
     * @return escaped column value
     */
    protected abstract String escapeColumnValue(Object value);

    /**
     * Write table header.
     *
     * @return String rendered header
     */
    protected String doHeaders() {

        final String ROW_START = this.getRowStart();
        final String ROW_END = this.getRowEnd();
        final String CELL_START = this.getCellStart();
        final String CELL_END = this.getCellEnd();
        final boolean ALWAYS_APPEND_CELL_END = this.getAlwaysAppendCellEnd();

        final StringBuilder buffer = new StringBuilder(1000);

        final Iterator<HeaderCell> iterator = this.model.getHeaderCellList().iterator();

        // start row
        if (ROW_START != null) {
            buffer.append(ROW_START);
        }

        while (iterator.hasNext()) {
            final HeaderCell headerCell = iterator.next();

            String columnHeader = headerCell.getTitle();

            if (columnHeader == null) {
                columnHeader = StringUtils.capitalize(headerCell.getBeanPropertyName());
            }

            columnHeader = this.escapeColumnValue(columnHeader);

            if (CELL_START != null) {
                buffer.append(CELL_START);
            }

            if (columnHeader != null) {
                buffer.append(columnHeader);
            }

            if (CELL_END != null && (ALWAYS_APPEND_CELL_END || iterator.hasNext())) {
                buffer.append(CELL_END);
            }
        }

        // end row
        if (ROW_END != null) {
            buffer.append(ROW_END);
        }

        return buffer.toString();

    }

    /**
     * Do export.
     *
     * @param out
     *            the out
     * @param characterEncoding
     *            the character encoding
     *
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     * @throws JspException
     *             the jsp exception
     *
     * @see org.displaytag.export.TextExportView#doExport(java.io.Writer,java.lang.String)
     */
    @Override
    public void doExport(final Writer out, final String characterEncoding) throws IOException, JspException {
        if (BaseExportView.log.isDebugEnabled()) {
            BaseExportView.log.debug(this.getClass().getName());
        }

        final String DOCUMENT_START = this.getDocumentStart();
        final String DOCUMENT_END = this.getDocumentEnd();
        final String ROW_START = this.getRowStart();
        final String ROW_END = this.getRowEnd();
        final String CELL_START = this.getCellStart();
        final String CELL_END = this.getCellEnd();
        final boolean ALWAYS_APPEND_CELL_END = this.getAlwaysAppendCellEnd();
        final boolean ALWAYS_APPEND_ROW_END = this.getAlwaysAppendRowEnd();

        // document start
        this.write(out, DOCUMENT_START);

        if (this.header) {
            this.write(out, this.doHeaders());
        }

        // get the correct iterator (full or partial list according to the exportFull field)
        final RowIterator rowIterator = this.model.getRowIterator(this.exportFull);

        // iterator on rows
        while (rowIterator.hasNext()) {
            final Row row = rowIterator.next();

            if (this.model.getTableDecorator() != null) {

                final String stringStartRow = this.model.getTableDecorator().startRow();
                this.write(out, stringStartRow);
            }

            // iterator on columns
            final ColumnIterator columnIterator = row.getColumnIterator(this.model.getHeaderCellList());

            this.write(out, ROW_START);

            while (columnIterator.hasNext()) {
                final Column column = columnIterator.nextColumn();

                // Get the value to be displayed for the column
                final String value = this.escapeColumnValue(column.getValue(this.decorated));

                this.write(out, CELL_START);

                this.write(out, value);

                if (ALWAYS_APPEND_CELL_END || columnIterator.hasNext()) {
                    this.write(out, CELL_END);
                }

            }
            if (ALWAYS_APPEND_ROW_END || rowIterator.hasNext()) {
                this.write(out, ROW_END);
            }
        }

        // document end
        this.write(out, DOCUMENT_END);

    }

    /**
     * Write a String, checking for nulls value.
     *
     * @param out
     *            output writer
     * @param string
     *            String to be written
     *
     * @throws IOException
     *             thrown by out.write
     */
    private void write(final Writer out, final String string) throws IOException {
        if (string != null) {
            out.write(string);
        }
    }

    /**
     * Output page.
     *
     * @return true, if successful
     *
     * @see org.displaytag.export.TextExportView#outputPage()
     */
    @Override
    public boolean outputPage() {
        return false;
    }
}


text:
using namespace Intrinsic::AssetManagement::Resources;

IntrinsicEdManagerWindowAsset::IntrinsicEdManagerWindowAsset(QWidget* parent)
    : IntrinsicEdManagerWindowBase(parent)
{
  setWindowTitle("Assets");
  setAcceptDrops(true);
  _propertyCompilerEntry =
      Application::_resourcePropertyCompilerMapping[_N(Asset)];
  _resourceManagerEntry = Application::_resourceManagerMapping[_N(Asset)];
  _resourceIcon = QIcon(":/Icons/asset");
  _managerFilePath = "managers/Asset.manager.json";
  _resourceName = "Asset";

  _assetChangeWatch = new QFileSystemWatcher(this);
  QObject::connect(_assetChangeWatch, SIGNAL(fileChanged(const QString&)), this,
                   SLOT(onAssetChanged(const QString&)));
  QObject::connect(this, SIGNAL(resourceTreePopulated()), this,
                   SLOT(onResourceTreePopulated()));
  QObject::connect(&_assetRecompileTimer, SIGNAL(timeout()),
                   SLOT(onCompileQueuedAssets()));

  _assetRecompileTimer.setSingleShot(true);

  onPopulateResourceTree();
}

void IntrinsicEdManagerWindowAsset::onPopulateResourceTree()
{
  _ui.resourceView->clear();
  _resourceToItemMapping.clear();
  _itemToResourceMapping.clear();

  rapidjson::Document doc;

  const uint32_t resourceCount = AssetManager::getActiveResourceCount();

  QTreeWidgetItem* textures = new QTreeWidgetItem();
  {
    textures->setText(0, "Textures");
    textures->setIcon(0, QIcon(":/Icons/picture"));
    _ui.resourceView->addTopLevelItem(textures);
  }

  QTreeWidgetItem* meshes = new QTreeWidgetItem();
  {
    meshes->setText(0, "Meshes");
    meshes->setIcon(0, QIcon(":/Icons/user"));
    _ui.resourceView->addTopLevelItem(meshes);
  }

  QTreeWidgetItem* generalAssets = new QTreeWidgetItem();
  {
    generalAssets->setText(0, "General");
    generalAssets->setIcon(0, QIcon(":/Icons/asset"));
    _ui.resourceView->addTopLevelItem(generalAssets);
  }

  for (uint32_t i = 0u; i < resourceCount; ++i)
  {
    Dod::Ref assetEntry = AssetManager::getActiveResourceAtIndex(i);
    _INTR_ASSERT(assetEntry.isValid());

    rapidjson::Value properties = rapidjson::Value(rapidjson::kObjectType);
    _propertyCompilerEntry.compileFunction(assetEntry, properties, doc);

    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0, properties["name"]["value"].GetString());
    item->setIcon(0, _resourceIcon);
    item->setFlags(item->flags() | Qt::ItemIsEditable);

    _itemToResourceMapping[item] = assetEntry;
    _resourceToItemMapping[assetEntry] = item;

    if (AssetManager::_descAssetType(assetEntry) ==
        Intrinsic::AssetManagement::Resources::AssetType::kMesh)
    {
      meshes->addChild(item);
    }
    else if (
        AssetManager::_descAssetType(assetEntry) ==
            Intrinsic::AssetManagement::Resources::AssetType::kColorTexture ||
        AssetManager::_descAssetType(assetEntry) ==
            Intrinsic::AssetManagement::Resources::AssetType::kAlphaTexture ||
        AssetManager::_descAssetType(assetEntry) ==
            Intrinsic::AssetManagement::Resources::AssetType::kNormalTexture ||
        AssetManager::_descAssetType(assetEntry) ==
            Intrinsic::AssetManagement::Resources::AssetType::kHdrTexture)
    {
      textures->addChild(item);
    }
    else
    {
      generalAssets->addChild(item);
    }
  }

  textures->setExpanded(true);
  meshes->setExpanded(true);
  generalAssets->setExpanded(true);

  emit resourceTreePopulated();
}

void IntrinsicEdManagerWindowAsset::initContextMenu(QMenu* p_ContextMenu)
{
  IntrinsicEdManagerWindowBase::initContextMenu(p_ContextMenu);

  QTreeWidgetItem* currIt = _ui.resourceView->currentItem();
  Dod::Ref resRef = _itemToResourceMapping[currIt];

  if (resRef.isValid())
  {
    p_ContextMenu->addSeparator();

    QAction* compileAsset =
        new QAction(QIcon(":/Icons/asset"), "Compile " + _resourceName, this);
    p_ContextMenu->addAction(compileAsset);
    QObject::connect(compileAsset, SIGNAL(triggered()), this,
                     SLOT(onCompileAsset()));
  }
}

void IntrinsicEdManagerWindowAsset::onCompileAsset()
{
  QTreeWidgetItem* currIt = _ui.resourceView->currentItem();
  Dod::Ref resource = _itemToResourceMapping[currIt];

  if (resource.isValid())
  {
    if (std::find(_assetsToRecompile.begin(), _assetsToRecompile.end(),
                  resource) == _assetsToRecompile.end())
    {
      _assetsToRecompile.push_back(resource);
      _assetRecompileTimer.start(100);
    }
  }
}

void IntrinsicEdManagerWindowAsset::onAssetChanged(const QString& p_FileName)
{
  // Recompile assets

  for (uint32_t i = 0u; i < AssetManager::getActiveResourceCount(); ++i)
  {
    AssetRef assetRef = AssetManager::getActiveResourceAtIndex(i);

    _INTR_STRING fileName, extension;
    StringUtil::extractFileNameAndExtension(p_FileName.toStdString().c_str(),
                                            fileName, extension);

    if (AssetManager::_descAssetFileName(assetRef) == (fileName + extension))
    {
      if (std::find(_assetsToRecompile.begin(), _assetsToRecompile.end(),
                    assetRef) == _assetsToRecompile.end())
      {
        _assetsToRecompile.push_back(assetRef);
      }
    }
  }

  _assetRecompileTimer.start(1000);
}

void IntrinsicEdManagerWindowAsset::onResourceTreePopulated()
{
  QStringList files = _assetChangeWatch->files();

  if (!files.empty())
    _assetChangeWatch->removePaths(files);

  for (uint32_t i = 0u; i < AssetManager::getActiveResourceCount(); ++i)
  {
    AssetRef ref = AssetManager::getActiveResourceAtIndex(i);

    if (AssetManager::_descAssetType(ref) == AssetType::kMesh)
    {
      _assetChangeWatch->addPath(
          QString(Settings::Manager::_assetMeshPath.c_str()) + "/" +
          AssetManager::_descAssetFileName(ref).c_str());
    }
    else if (AssetManager::_descAssetType(ref) == AssetType::kColorTexture ||
             AssetManager::_descAssetType(ref) == AssetType::kAlphaTexture ||
             AssetManager::_descAssetType(ref) == AssetType::kHdrTexture ||
             AssetManager::_descAssetType(ref) == AssetType::kNormalTexture)
    {
      _assetChangeWatch->addPath(
          QString(Settings::Manager::_assetTexturePath.c_str()) + "/" +
          AssetManager::_descAssetFileName(ref).c_str());
    }
  }
}

void IntrinsicEdManagerWindowAsset::onCompileQueuedAssets()
{
  Intrinsic::AssetManagement::Resources::AssetManager::compileAssets(
      _assetsToRecompile);
  _assetsToRecompile.clear();

  onResourceTreePopulated();
}

void IntrinsicEdManagerWindowAsset::dragEnterEvent(QDragEnterEvent* event)
{
  event->accept();
}

void IntrinsicEdManagerWindowAsset::dropEvent(QDropEvent* event)
{
  const QMimeData* mimeData = event->mimeData();

  if (mimeData->hasUrls())
  {
    QStringList pathList;
    QList<QUrl> urlList = mimeData->urls();

    AssetRef lastCreatedAsset = Dod::Ref();

    for (int i = 0; i < urlList.size(); ++i)
    {
      QString path = urlList.at(i).toLocalFile();

      _INTR_STRING fileName, extension;
      StringUtil::extractFileNameAndExtension(path.toStdString().c_str(),
                                              fileName, extension);

      AssetRef existingAsset = AssetManager::_getResourceByName(fileName);
      if (!existingAsset.isValid())
      {
        AssetType::Enum assetType = AssetType::kNone;
        if (extension == ".fbx")
        {
          assetType = AssetType::kMesh;
        }
        else if (extension == ".TGA" || extension == ".tga")
        {
          assetType = AssetType::kColorTexture;
        }

        if (assetType != AssetType::kNone)
        {
          AssetRef assetRef = AssetManager::createAsset(fileName);
          AssetManager::resetToDefault(assetRef);

          AssetManager::_descAssetFileName(assetRef) = fileName + extension;
          AssetManager::_descAssetType(assetRef) = assetType;

          lastCreatedAsset = assetRef;
        }
      }
      else
      {
        QTreeWidgetItem* item = _resourceToItemMapping[existingAsset];
        item->setSelected(true);
        item->parent()->setExpanded(true);
        onItemSelected(item, nullptr);
      }
    }

    if (lastCreatedAsset.isValid())
    {
      onPopulateResourceTree();
      QTreeWidgetItem* item = _resourceToItemMapping[lastCreatedAsset];

      item->setSelected(true);
      item->parent()->setExpanded(true);
      onItemSelected(item, nullptr);
    }
  }
}


text:
local ffi = require "ffi"
local ffi_cdef = ffi.cdef
local ffi_typeof = ffi.typeof

ffi_cdef [[
void
nettle_arctwo_set_key_ekb(struct arctwo_ctx *ctx,
		                      size_t length, const uint8_t * key, unsigned ekb);

void
nettle_arctwo_set_key(struct arctwo_ctx *ctx, size_t length, const uint8_t *key);

void
nettle_arctwo40_set_key(struct arctwo_ctx *ctx, const uint8_t *key);

void
nettle_arctwo64_set_key(struct arctwo_ctx *ctx, const uint8_t *key);

void
nettle_arctwo128_set_key(struct arctwo_ctx *ctx, const uint8_t *key);

void
nettle_arctwo_set_key_gutmann(struct arctwo_ctx *ctx,
			                        size_t length, const uint8_t *key);
void
nettle_arctwo128_set_key_gutmann(struct arctwo_ctx *ctx,
			                           const uint8_t *key);

void
nettle_arctwo_encrypt(struct arctwo_ctx *ctx,
		                  size_t length, uint8_t *dst, const uint8_t *src);
void
nettle_arctwo_decrypt(struct arctwo_ctx *ctx,
		                  size_t length, uint8_t *dst, const uint8_t *src);
]]

return ffi_typeof [[
struct arctwo_ctx {
  uint16_t S[64];
}]]


text:
namespace Urho3D
{

#if defined(IOS) || defined(TVOS) || defined(__EMSCRIPTEN__)
// Code for supporting SDL_iPhoneSetAnimationCallback() and emscripten_set_main_loop_arg()
#if defined(__EMSCRIPTEN__)
#include <emscripten/emscripten.h>
#endif
void RunFrame(void* data)
{
    static_cast<Engine*>(data)->RunFrame();
}
#endif

#if DESKTOP
/// Command line parser.
static CLI::App commandLine_{};
#endif

Application::Application(Context* context) :
    Object(context),
    exitCode_(EXIT_SUCCESS)
{
    // Create the Engine, but do not initialize it yet. Subsystems except Graphics & Renderer are registered at this point
    engine_ = new Engine(context);

    // Subscribe to log messages so that can show errors if ErrorExit() is called with empty message
    SubscribeToEvent(E_LOGMESSAGE, URHO3D_HANDLER(Application, HandleLogMessage));
}

int Application::Run()
{
    // Profiler requires main thread to be named "Main" as fps calculations depend on it.
    URHO3D_PROFILE_THREAD("Main");
#if !defined(__GNUC__) || __EXCEPTIONS
    try
    {
#endif
        // Register application command line arguments or set up engine parameters
        Setup();

#if DESKTOP
        if (engine_->GetParameter(engineParameters_, EP_ENGINE_CLI_PARAMETERS, true).GetBool())
        {
            // Register engine command line arguments
            Engine::DefineParameters(commandLine_, engineParameters_);
        }
#endif

        if (exitCode_)
            return exitCode_;

#if DESKTOP
        // Parse command line parameters
        {
            const StringVector& rawArguments = GetArguments();
            std::vector<std::string> cliArgs;
            cliArgs.reserve(rawArguments.size());
            // CLI11 detail - arguments must be in reversed order.
            for (auto i = static_cast<int>(rawArguments.size() - 1); i >= 0; i--)
                cliArgs.emplace_back(rawArguments[static_cast<unsigned>(i)].c_str());

            try {
                commandLine_.parse(cliArgs);
            } catch(const CLI::ParseError &e) {
                exitCode_ = commandLine_.exit(e);
                return exitCode_;
            }
        }
#endif

        if (!engine_->Initialize(engineParameters_))
        {
            ErrorExit();
            return exitCode_;
        }

#if URHO3D_PLUGINS && URHO3D_CSHARP
        if (engine_->GetParameter(engineParameters_, EP_ENGINE_AUTO_LOAD_SCRIPTS, true).GetBool())
        {
            if (auto* api = Script::GetRuntimeApi())
            {
                scriptsPlugin_ = api->CompileResourceScriptPlugin();
                if (scriptsPlugin_.NotNull())
                {
                    scriptsPlugin_->SendEvent(E_PLUGINLOAD);
                    scriptsPlugin_->Load();
                    scriptsPlugin_->SendEvent(E_PLUGINSTART);
                    scriptsPlugin_->Start();
                }
            }
        }
#endif

        Start();
        if (exitCode_ || engine_->IsExiting())
        {
            Stop();
            return exitCode_;
        }

        SendEvent(E_APPLICATIONSTARTED);

        // Platforms other than iOS/tvOS and Emscripten run a blocking main loop
#if !defined(IOS) && !defined(TVOS) && !defined(__EMSCRIPTEN__)
        while (!engine_->IsExiting())
            engine_->RunFrame();

#if URHO3D_PLUGINS && URHO3D_CSHARP
        if (scriptsPlugin_.NotNull())
        {
            scriptsPlugin_->SendEvent(E_PLUGINSTOP);
            scriptsPlugin_->Stop();
        }
#endif

        Stop();

#if URHO3D_PLUGINS && URHO3D_CSHARP
        if (scriptsPlugin_.NotNull())
        {
            scriptsPlugin_->SendEvent(E_PLUGINUNLOAD);
            scriptsPlugin_->Unload();
            Script::GetRuntimeApi()->DereferenceAndDispose(scriptsPlugin_.Detach());
        }
#endif

        // iOS/tvOS will setup a timer for running animation frames so eg. Game Center can run. In this case we do not
        // support calling the Stop() function, as the application will never stop manually
#else
#if defined(IOS) || defined(TVOS)
        SDL_iPhoneSetAnimationCallback(GetSubsystem<Graphics>()->GetWindow(), 1, &RunFrame, engine_);
#elif defined(__EMSCRIPTEN__)
        emscripten_set_main_loop_arg(RunFrame, engine_, 0, 1);
#endif
#endif

        return exitCode_;
#if !defined(__GNUC__) || __EXCEPTIONS
    }
    catch (std::bad_alloc&)
    {
        ErrorDialog(GetTypeName(), "An out-of-memory error occurred. The application will now exit.");
        return EXIT_FAILURE;
    }
#endif
}

void Application::ErrorExit(const ea::string& message)
{
    engine_->Exit(); // Close the rendering window
    exitCode_ = EXIT_FAILURE;

    std::function<void(const ea::string&)> showError;
    if (engineParameters_[EP_HEADLESS].GetBool())
    {
        showError = [this](const ea::string& message)
        {
            URHO3D_LOGERROR(message.c_str());
        };
    }
    else
    {
        showError = [this](const ea::string& message)
        {
            ErrorDialog(GetTypeName(), message);
        };
    }

    if (!message.length())
    {
        showError(startupErrors_.length() ?
            startupErrors_ : ea::string("Application has been terminated due to unexpected error."));
    }
    else
        showError(message);
}

void Application::HandleLogMessage(StringHash eventType, VariantMap& eventData)
{
    using namespace LogMessage;

    if (eventData[P_LEVEL].GetInt() == LOG_ERROR)
    {
        // Strip the timestamp if necessary
        ea::string error = eventData[P_MESSAGE].GetString();
        unsigned bracketPos = error.find(']');
        if (bracketPos != ea::string::npos)
            error = error.substr(bracketPos + 2);

        startupErrors_ += error + "\n";
    }
}
#if DESKTOP
CLI::App& Application::GetCommandLineParser()
{
    return commandLine_;
}
#endif

}


text:
layout: post
title: Docker and Mac OSX
---

## Intro

Running docker on mac osx environment is working but when you're running some serious project with many dockers it's really slowing down and creates many problems.

## Docker Machine

There's no native support for docker in mac osx so to use docker, you must use ```docker-machine``` (used to known as: ```boot2docker```) which talks with Virtualbox API like ```vagrant``` to create tiny virtual machine with linux distro: busybox (in fact it's by default uses old boot2docker.iso but you can use your custom iso) with preinstalled docker daemon. Now docker client installed on mac osx will talk to docker daemon located on this linux virtualmachine throw forwarded port. So all networking base on virtualbox network interfaces ```vboxnet#``` and inside vm there's ```vboxsf``` for mounting files from your osx host.

## Problem Case #1

Let's say we want to create container with dns based on consul, so we could autodiscover our other containers. Let's assume that we won't change dhcp ip range in virtualbox configuration for our docker-machine virtual machine, so we create interface which will be used by our docker dns container.

```bash
docker-machine create -d virtualbox --virtual-memory 4096 vm_1
eval "$(docker-machine env vm_1)"
docker-machine ssh vm_1 "sudo ifconfig eth1:1 172.17.255.253 network 255.255.255.0"
```

We will use this dns server in other containers so we need to change some docker daemon options:

```bash
docker-machine ssh vm_1 "/usr/local/bin/docker daemon -D -g /var/lib/docker -H unix:// -H tcp://0.0.0.0:2376 --bip=172.17.0.1/16
--dns=172.17.255.253  --label provider=virtualbox --tlsverify --tlscacert=/var/lib/boot2docker/ca.pem --tlscert=/var/l
ib/boot2docker/server.pem --tlskey=/var/lib/boot2docker/server-key.pem -s aufs &"
```

bip it's docker0 interface ip address class from virtual machine and dns is static address of our dns container. When daemon starts we need to do one more thing. On host. But first get ip of our docker daemon URL

```bash
docker-machine ls
NAME       ACTIVE   DRIVER       STATE     URL                         SWARM   DOCKER    ERRORS
vm_1      *        virtualbox   Running   tcp://192.168.99.100:2376           v1.11.0
```

Now we need add static route to our docker network

```bash
sudo route -n add 172.17.0.0/16 192.168.99.100
```

Check if our route uses vboxnet interface to route traffic to 172.17 network

```bash
netstat -nr | grep 172.17
```

Now we can test if our traffic goes to our dockers:

```bash
docker run -it ubuntu bash
root@containerhash:/# ifconfig # get ip of container
 nc -l 7777
```

from host:

```bash
telnet 172.17.0.8 777
```

Sweet if connected :wink:

## Problem case #2

TBD


text:
<?php

class ProjectUserGroupPermission
extends AppModel {
  public $belongsTo = array( 'Project', 'UserGroup' );
};


text:
import stringIndexIterator from './stringIndexIterator'

describe('stringIndexIterator', () => {
  test('returns an Array of the indexes of the String', () => {
    const string = 'abc'
    const result = stringIndexIterator(string)
    expect(result.next).toBeInstanceOf(Function)
    expect(result.next()).toEqual({
      done: false,
      value: 0
    })
    expect(result.next()).toEqual({
      done: false,
      value: 1
    })
    expect(result.next()).toEqual({
      done: false,
      value: 2
    })
    expect(result.next()).toEqual({
      done: true
    })
  })
})


text:
layout: post
title:  "Joke"
date:   2015-09-22 10:18:00
categories: jokes funny
---

During his physical, the doctor asked the patient about his daily activity level. He described a typical day this way:
"Well, yesterday afternoon, I waded along the edge of a lake, drank eight beers, escaped from wild dogs in the heavy brush, jumped away from an aggressive rattlesnake, marched up and down several rocky hills, stood in a patch of poison ivy, crawled out of quicksand and took four leaks behind big trees."
Inspired by the story, the doctor said, "You must be one hell of an outdoors man!"
"NAH," he replied, "I'm just a shitty golfer."


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import $ from 'jquery';

moduleForComponent('foo-bar', 'Integration | Polymer | Shadow DOM', {
  integration: true
});

test('Uses native Shadow DOM if available', function(assert) {
  if (!window.Polymer.Settings.nativeShadow) {
    return assert.expect(0);
  }

  assert.expect(2);

  this.render(hbs`<paper-button></paper-button>`);

  assert.ok(document.querySelector('paper-button').shadowRoot,
    'paper-button has shadowRoot');
  assert.equal($('paper-button').attr('role'), 'button',
    'role is attached to button immediately');
});


text:
using CharacterGen.Abilities;
using CharacterGen.Domain.Selectors.Selections;
using CharacterGen.Feats;
using CharacterGen.Races;
using NUnit.Framework;
using System.Collections.Generic;

namespace CharacterGen.Tests.Unit.Selectors.Selections
{
    [TestFixture]
    public class RacialFeatSelectionTests
    {
        private RacialFeatSelection selection;
        private Race race;
        private Dictionary<string, Ability> stats;
        private List<Feat> feats;

        [SetUp]
        public void Setup()
        {
            selection = new RacialFeatSelection();
            race = new Race();
            stats = new Dictionary<string, Ability>();
            feats = new List<Feat>();

            stats["stat"] = new Ability("stat");
            stats["stat"].Value = 42;
        }

        [Test]
        public void RacialFeatSelectionInitialization()
        {
            Assert.That(selection.Feat, Is.Empty);
            Assert.That(selection.Power, Is.EqualTo(0));
            Assert.That(selection.MinimumHitDieRequirement, Is.EqualTo(0));
            Assert.That(selection.SizeRequirement, Is.Empty);
            Assert.That(selection.FocusType, Is.Empty);
            Assert.That(selection.Frequency, Is.Not.Null);
            Assert.That(selection.MaximumHitDieRequirement, Is.EqualTo(0));
            Assert.That(selection.MinimumAbilities, Is.Empty);
            Assert.That(selection.RandomFociQuantity, Is.Empty);
            Assert.That(selection.RequiredFeats, Is.Empty);
        }

        [Test]
        public void RequirementsMetIfNoRequirements()
        {
            var met = selection.RequirementsMet(race, 0, stats, feats);
            Assert.That(met, Is.True);
        }

        [Test]
        public void RequirementsNotMetIfWrongSize()
        {
            race.Size = "big";
            selection.SizeRequirement = "small";

            var met = selection.RequirementsMet(race, 0, stats, feats);
            Assert.That(met, Is.False);
        }

        [Test]
        public void RequirementsNotMetIfBelowHitDiceRange()
        {
            selection.MinimumHitDieRequirement = 3;

            var met = selection.RequirementsMet(race, 2, stats, feats);
            Assert.That(met, Is.False);
        }

        [Test]
        public void RequirementsNotMetIfAboveHitDiceRange()
        {
            selection.MaximumHitDieRequirement = 3;

            var met = selection.RequirementsMet(race, 4, stats, feats);
            Assert.That(met, Is.False);
        }

        [Test]
        public void RequirementsMetIfAboveMaximumOfZero()
        {
            var met = selection.RequirementsMet(race, 4, stats, feats);
            Assert.That(met, Is.True);
        }

        [Test]
        public void RequirementsMetForMinimumHitDice()
        {
            selection.MinimumHitDieRequirement = 4;

            var met = selection.RequirementsMet(race, 4, stats, feats);
            Assert.That(met, Is.True);
        }

        [Test]
        public void RequirementsMetForMaximumHitDice()
        {
            selection.MaximumHitDieRequirement = 4;

            var met = selection.RequirementsMet(race, 4, stats, feats);
            Assert.That(met, Is.True);
        }

        [Test]
        public void RequirementsNotMetIfDoesNotHaveMinimumStat()
        {
            selection.MinimumAbilities["stat"] = 9266;

            var met = selection.RequirementsMet(race, 4, stats, feats);
            Assert.That(met, Is.False);
        }

        [Test]
        public void RequirementsMetIfAnyMinimumStatIsMet()
        {
            selection.MinimumAbilities["stat"] = 9266;
            selection.MinimumAbilities["stat 2"] = 600;

            stats["stat 2"] = new Ability("stat 2");
            stats["stat 2"].Value = 600;

            var met = selection.RequirementsMet(race, 4, stats, feats);
            Assert.That(met, Is.True);
        }

        [Test]
        public void MetIfNoRequiredFeats()
        {
            var requirementsMet = selection.RequirementsMet(race, 0, stats, feats);
            Assert.That(requirementsMet, Is.True);
        }

        [Test]
        public void MetWithAllRequiredFeats()
        {
            selection.RequiredFeats = new[] { new RequiredFeatSelection { Feat = "feat 1" }, new RequiredFeatSelection { Feat = "feat 2" } };
            feats.Add(new Feat { Name = "feat 1" });
            feats.Add(new Feat { Name = "feat 2" });

            var requirementsMet = selection.RequirementsMet(race, 0, stats, feats);
            Assert.That(requirementsMet, Is.True);
        }

        [Test]
        public void NotMetWithSomeRequiredFeats()
        {
            selection.RequiredFeats = new[] { new RequiredFeatSelection { Feat = "feat 1" }, new RequiredFeatSelection { Feat = "feat 2" } };
            feats.Add(new Feat { Name = "feat 1" });

            var requirementsMet = selection.RequirementsMet(race, 0, stats, feats);
            Assert.That(requirementsMet, Is.False);
        }

        [Test]
        public void NotMetWithNoRequiredFeats()
        {
            selection.RequiredFeats = new[] { new RequiredFeatSelection { Feat = "feat 1" }, new RequiredFeatSelection { Feat = "feat 2" } };

            var requirementsMet = selection.RequirementsMet(race, 0, stats, feats);
            Assert.That(requirementsMet, Is.False);
        }

        [Test]
        public void MetWithAllRequiredFeatsAndFoci()
        {
            selection.RequiredFeats = new[]
            {
                new RequiredFeatSelection { Feat = "feat 1", Focus = "focus 1" },
                new RequiredFeatSelection { Feat = "feat 2", Focus = "focus 2" }
            };

            feats.Add(new Feat { Name = "feat 1", Foci = new[] { "focus 1", "focus 3" } });
            feats.Add(new Feat { Name = "feat 2", Foci = new[] { "focus 4", "focus 2" } });

            var requirementsMet = selection.RequirementsMet(race, 0, stats, feats);
            Assert.That(requirementsMet, Is.True);
        }

        [Test]
        public void MetWithExtraRequiredFeatsAndFoci()
        {
            selection.RequiredFeats = new[]
            {
                new RequiredFeatSelection { Feat = "feat 1", Focus = "focus 1" },
                new RequiredFeatSelection { Feat = "feat 2", Focus = "focus 2" }
            };

            feats.Add(new Feat { Name = "feat 1", Foci = new[] { "focus 1", "focus 2" } });
            feats.Add(new Feat { Name = "feat 2", Foci = new[] { "focus 2", "focus 1", "focus 3" } });
            feats.Add(new Feat { Name = "feat 3" });
            feats.Add(new Feat { Name = "feat 4", Foci = new[] { "focus 4" } });

            var requirementsMet = selection.RequirementsMet(race, 0, stats, feats);
            Assert.That(requirementsMet, Is.True);
        }

        [Test]
        public void NotMetWithSomeRequiredFeatsAndFoci()
        {
            selection.RequiredFeats = new[]
            {
                new RequiredFeatSelection { Feat = "feat 1", Focus = "focus 1" },
                new RequiredFeatSelection { Feat = "feat 2", Focus = "focus 2" }
            };

            feats.Add(new Feat { Name = "feat 1", Foci = new[] { "focus 2" } });
            feats.Add(new Feat { Name = "feat 2", Foci = new[] { "focus 2", "focus 1" } });
            feats.Add(new Feat { Name = "feat 3", Foci = new[] { "focus 1" } });

            var requirementsMet = selection.RequirementsMet(race, 0, stats, feats);
            Assert.That(requirementsMet, Is.False);
        }

        [Test]
        public void NotMetWithNoRequiredFeatsAndFoci()
        {
            selection.RequiredFeats = new[]
            {
                new RequiredFeatSelection { Feat = "feat 1", Focus = "focus 1" },
                new RequiredFeatSelection { Feat = "feat 2", Focus = "focus 2" }
            };

            feats.Add(new Feat { Name = "feat 1", Foci = new[] { "focus 2" } });
            feats.Add(new Feat { Name = "feat 2", Foci = new[] { "focus 1" } });
            feats.Add(new Feat { Name = "feat 3", Foci = new[] { "focus 1", "focus 2" } });

            var requirementsMet = selection.RequirementsMet(race, 0, stats, feats);
            Assert.That(requirementsMet, Is.False);
        }

        [Test]
        public void AllRequirementsMet()
        {
            race.Size = "big";

            selection.SizeRequirement = race.Size;
            selection.MinimumHitDieRequirement = 3;
            selection.MaximumHitDieRequirement = 5;
            selection.MinimumAbilities["stat"] = 42;

            selection.RequiredFeats = new[]
            {
                new RequiredFeatSelection { Feat = "feat 1" },
                new RequiredFeatSelection { Feat = "feat 2", Focus = "focus 2" }
            };

            feats.Add(new Feat { Name = "feat 1" });
            feats.Add(new Feat { Name = "feat 2", Foci = new[] { "focus 2" } });

            var met = selection.RequirementsMet(race, 4, stats, feats);
            Assert.That(met, Is.True);
        }
    }
}


text:
'use strict';

module.exports = {
    db: 'mongodb://localhost/mean-dev',
    //db:'mongodb://cuongcua:12345678@kahana.mongohq.com:10069/piolist',
    app: {
        name: 'MEAN - FullStack JS - Development'
    },
    facebook: {
        clientID: 'APP_ID',
        clientSecret: 'APP_SECRET',
        callbackURL: 'http://localhost:3000/auth/facebook/callback'
    },
    twitter: {
        clientID: 'g7oiUjkYaFAocZPA7HaTALGED',
        clientSecret: '68z1fmwRKj8l77cYJeMXmjQGJJn5AcIpmwXw3xkcG65SmblUJZ',
        callbackURL: 'http://localhost:3000/auth/twitter/callback'
    },
    github: {
        clientID: '3a9a74b2bdce0487024f',
        clientSecret: '19aca50afa70ec5b025d7c87aad5db48e237ce1c',
        callbackURL: 'http://localhost:3000/auth/github/callback'
    },
    google: {
        clientID: 'APP_ID',
        clientSecret: 'APP_SECRET',
        callbackURL: 'http://localhost:3000/auth/google/callback'
    },
    linkedin: {
        clientID: 'API_KEY',
        clientSecret: 'SECRET_KEY',
        callbackURL: 'http://localhost:3000/auth/linkedin/callback'
    }
};


text:
fontutil is a small collection of utility functions to make working with fonts easier.

## Functions

### Find

Find returns the path to a font file given a font name. It's (intended to be) an OS-agnostic way to locate font files installed on the system. If you need to include fonts with your application instead of finding them on the system, this isn't for you.

Find currently only supports Windows but contributions for other systems are quite welcome! I'm also open to changing the interface. For example, separately specifying style, variant, or weight or a css-like list of prioritized font or family names. I'm unsure if/how these changes could be implemented on the different systems.

##### Supported platforms and resources for future implementation

- [x] Windows ([REG: Fonts Entries](windows))
- [ ] OS X ([Font locations and their purposes](mac))
- [ ] Linux ([Debian](debian), [Ubuntu](ubuntu), others?)

### FindAndParse

FindAndParse calls Find to find a font file, reads it, parses it, and returns the `*truetype.Font`.

### DrawWidth

DrawWidth returns the width of a string if it were drawn to a Context, as the X coordinate of a `raster.Point`.

### CenterX

CenterX returns the the start point required to center a string within a Rectangle, as the X coordinate of a `raster.Point`.

[windows]: https://support.microsoft.com/en-us/kb/102960
[mac]: https://support.apple.com/en-us/HT201722
[debian]: https://wiki.debian.org/Fonts
[ubuntu]: https://wiki.ubuntu.com/Fonts


text:
package org.wso2.carbon.identity.sts.mgt.ui.client;

import org.apache.axis2.AxisFault;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.sts.mgt.stub.IdentitySTSAdminServiceStub;
import org.wso2.carbon.identity.sts.mgt.stub.dto.CardIssuerDTO;
import org.wso2.carbon.identity.sts.mgt.stub.dto.CardIssuerTokenDTO;

public class STSAdminServiceClient {

    private static final Log log = LogFactory.getLog(STSAdminServiceClient.class);
    private IdentitySTSAdminServiceStub stub;

    /**
     * Instantiates STSAdminServiceClient
     *
     * @param cookie           For session management
     * @param backendServerURL URL of the back end server where IdentitySTSAdminService is running.
     * @param configCtx        ConfigurationContext
     * @throws AxisFault
     */
    public STSAdminServiceClient(String cookie, String backendServerURL,
                                 ConfigurationContext configCtx) throws AxisFault {
        String serviceURL = backendServerURL + "IdentitySTSAdminService";
        stub = new IdentitySTSAdminServiceStub(configCtx, serviceURL);
        ServiceClient client = stub._getServiceClient();
        Options option = client.getOptions();
        option.setManageSession(true);
        option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
    }

    public CardIssuerDTO readCardIssuerConfiguration() throws AxisFault {
        try {
            return stub.readCardIssuerConfiguration();
        } catch (Exception e) {
            handleException(
                    "Error ouccured while reading card issuer configurations from the backend service",
                    e);
        }
        return null;
    }

    public void updateCardIssueConfiguration(CardIssuerDTO issuer) throws AxisFault {
        try {
            stub.updateCardIssueConfiguration(issuer);
        } catch (Exception e) {
            handleException(
                    "Error ouccured while updating card issuer configurations at the backend service",
                    e);
        }
    }

    public String getSupportingTokens(CardIssuerTokenDTO[] tokens) {
        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < tokens.length; i++) {
            if (tokens[i].getSupported()) {
                if (i < tokens.length - 1) {
                    buffer.append(tokens[i].getTokenType() + ",");
                } else {
                    buffer.append(tokens[i].getTokenType());
                }
            }
        }
        return buffer.toString();
    }

    /**
     * Logs and wraps the given exception.
     *
     * @param msg Error message
     * @param e   Exception
     * @throws AxisFault
     */
    private void handleException(String msg, Exception e) throws AxisFault {
        log.error(msg, e);
        throw new AxisFault(msg, e);
    }

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="AnimationNodeOneShot" inherits="AnimationNode" version="4.0">
	<brief_description>
		Plays an animation once in [AnimationNodeBlendTree].
	</brief_description>
	<description>
		A resource to add to an [AnimationNodeBlendTree]. This node will execute a sub-animation and return once it finishes. Blend times for fading in and out can be customized, as well as filters.
	</description>
	<tutorials>
		<link title="AnimationTree">https://docs.godotengine.org/en/latest/tutorials/animation/animation_tree.html</link>
		<link title="Third Person Shooter Demo">https://godotengine.org/asset-library/asset/678</link>
	</tutorials>
	<methods>
		<method name="get_mix_mode" qualifiers="const">
			<return type="int" enum="AnimationNodeOneShot.MixMode">
			</return>
			<description>
			</description>
		</method>
		<method name="set_mix_mode">
			<return type="void">
			</return>
			<argument index="0" name="mode" type="int" enum="AnimationNodeOneShot.MixMode">
			</argument>
			<description>
			</description>
		</method>
	</methods>
	<members>
		<member name="autorestart" type="bool" setter="set_autorestart" getter="has_autorestart" default="false">
			If [code]true[/code], the sub-animation will restart automatically after finishing.
		</member>
		<member name="autorestart_delay" type="float" setter="set_autorestart_delay" getter="get_autorestart_delay" default="1.0">
			The delay after which the automatic restart is triggered, in seconds.
		</member>
		<member name="autorestart_random_delay" type="float" setter="set_autorestart_random_delay" getter="get_autorestart_random_delay" default="0.0">
			If [member autorestart] is [code]true[/code], a random additional delay (in seconds) between 0 and this value will be added to [member autorestart_delay].
		</member>
		<member name="fadein_time" type="float" setter="set_fadein_time" getter="get_fadein_time" default="0.1">
		</member>
		<member name="fadeout_time" type="float" setter="set_fadeout_time" getter="get_fadeout_time" default="0.1">
		</member>
		<member name="sync" type="bool" setter="set_use_sync" getter="is_using_sync" default="false">
		</member>
	</members>
	<constants>
		<constant name="MIX_MODE_BLEND" value="0" enum="MixMode">
		</constant>
		<constant name="MIX_MODE_ADD" value="1" enum="MixMode">
		</constant>
	</constants>
</class>


text:
package github

import (
	"flag"
	"os"
	"testing"

	"github.com/laher/goxc/tasks"
	"github.com/laher/goxc/tasks/httpc"
)

var apikey = flag.String("api-key", "", "API key")

var (
	version   = "v0.16.0-testx2"
	tagName   = "v0.16.0-testx"
	apihost   = "https://api.github.com"
	owner     = "laher"
	repo      = "goxc"
	isVerbose = true
)

func TestCreateRelease(t *testing.T) {
	if *apikey == "" {
		t.Skip("api-key is required to run this integration test")
	}
	t.Logf("create release")
	err := createRelease(apihost, owner, *apikey, repo, tagName, version, "Built by goxc", true, isVerbose)
	if err != nil {
		t.Errorf("Error creating release %v", err)
	}
}

///repos/:owner/:repo/releases/tags/:tag
func TestGetTagRelease(t *testing.T) {
	if *apikey == "" {
		t.Skip("api-key is required to run this integration test")
	}
	id, err := ghGetReleaseForTag(apihost, owner, *apikey, repo, tagName, isVerbose)
	if err != nil {
		t.Errorf("Error getting release %v", err)
	}
	t.Logf("ID: %s", id)
}

func TestGetReleases(t *testing.T) {
	if *apikey == "" {
		t.Skip("api-key is required to run this integration test")
	}
	r, err := httpc.DoHttp("GET", apihost+"/repos/"+owner+"/"+repo+"/releases", "", owner, *apikey, "", nil, 0, isVerbose)
	if err != nil {
		t.Errorf("Error getting release %v", err)
	}
	a, err := httpc.ParseSlice(r, isVerbose)
	if err != nil {
		t.Errorf("Error getting release %v", err)
	}
	for _, i := range a {
		id := i["id"]
		name := i["name"]
		t.Logf("ID: %0.f  Name: %s", id, name)
		//		for k, v := range i {
		//			t.Logf("Entry: %s %+v", k, v)
		//		}
	}
	//t.Logf("Response data: %v", a)
}

func TestGhDoUpload(t *testing.T) {

	if *apikey == "" {
		t.Skip("api-key is required to run this integration test")
	}
	t.Logf("do upload")
	apihost := "https://uploads.github.com"
	version := "v0.16.0-testx"
	relativePath := "tasks.go"
	fullPath := "tasks.go"
	contentType := "text/plain"
	err := ghDoUpload(apihost, *apikey, owner, repo, version, relativePath, fullPath, contentType, true, false)
	if err != nil {
		t.Errorf("Error creating release %v", err)
	}
}

func TestGhWalkFunc(t *testing.T) {

	t.Skip()
	fullPath := ""
	var fi2 os.FileInfo
	var errIn error
	reportFilename := ""
	dirs := []string{}
	var tp tasks.TaskParams
	var report tasks.BtReport
	format := ""
	err := ghWalkFunc(fullPath, fi2, errIn, reportFilename, dirs, tp, format, report)
	if err != nil {

		t.Errorf("Error doing walkFunc %v", err)
	}
}


text:
/*
	locale styles: load fonts, change directions, etc.
*/
body {
	font-family: tahoma;
}
#image {
	float: right;
	padding-right:inherit;
	padding-left:10px;
}


text:
import sys
import simplejson as json
import pytumblr

def login(oauth_filename="oauth.json"):
    oauth_data = json.load(open(oauth_filename, 'r'))

    client = pytumblr.TumblrRestClient(
        oauth_data['consumer_key'],
        oauth_data['consumer_secret'],
        oauth_data['oauth_token'],
        oauth_data['oauth_secret']
    )
    return client.info()

def change_state(client, blogname, post_id, new_state):
    return client.send_api_request("post", "/v2/blog/%s/post/edit" % blogname, {"id": post_id, "state": new_state}, ["id", "state"], True)

#client = pytumblr.TumblrRestClient("1234", "abcde", "token", "ThIsIsAsEcreT")


text:
/**
 * Minimalist TypeScript description file for YUITest including only Asserts to give the compiler
 * near the exact necessary to be able to compile the PureMVC framework Unit Tests.
 */
declare module YUITest
{
	export class Assert
	{
		/**
		 * Forces an assertion error to occur.
		 * @param message The message to display with the failure.
		 */
		static fail( message?:string ):void;

		//-------------------------------------------------------------------------
		// Equality Assertion Methods
		//-------------------------------------------------------------------------

		/**
		 * Asserts that a value is equal to another. This uses the double equals sign
		 * so type cohersion may occur.
		 * @param expected The expected value.
		 * @param actual The actual value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static areEqual( expected:any, actual:any, message?:string ):void;

		/**
		 * Asserts that a value is not equal to another. This uses the double equals sign
		 * so type cohersion may occur.
		 * @param unexpected The unexpected value.
		 * @param actual The actual value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static areNotEqual( unexpected:any, actual:any, message?:string ):void;

		/**
		 * Asserts that a value is not the same as another. This uses the triple equals sign
		 * so no type cohersion may occur.
		 * @param unexpected The unexpected value.
		 * @param actual The actual value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static areNotSame(unexpected:any, actual:any, message?:string ):void;

		/**
		 * Asserts that a value is the same as another. This uses the triple equals sign
		 * so no type cohersion may occur.
		 * @param expected The expected value.
		 * @param actual The actual value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static areSame(expected:any, actual:any, message?:string ):void;

		//-------------------------------------------------------------------------
		// Boolean Assertion Methods
		//-------------------------------------------------------------------------

		/**
		 * Asserts that a value is false. This uses the triple equals sign
		 * so no type cohersion may occur.
		 * @param actual The actual value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static isFalse( actual:any, message?:string ):void;

		/**
		 * Asserts that a value is true. This uses the triple equals sign
		 * so no type cohersion may occur.
		 * @param actual The actual value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static isTrue( actual:any, message?:string ):void;

		//-------------------------------------------------------------------------
		// Special Value Assertion Methods
		//-------------------------------------------------------------------------

		/**
		 * Asserts that a value is not a number.
		 * @param actual The value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static isNaN( actual:any, message?:string ):void;

		/**
		 * Asserts that a value is not the special NaN value.
		 * @param actual The value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static isNotNaN( actual:any, message?:string ):void;

		/**
		 * Asserts that a value is not null. This uses the triple equals sign
		 * so no type cohersion may occur.
		 * @param actual The actual value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static isNotNull( actual:any, message?:string ):void;

		/**
		 * Asserts that a value is not undefined. This uses the triple equals sign
		 * so no type cohersion may occur.
		 * @param actual The actual value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static isNotUndefined( actual:any, message?:string ):void;

		/**
		 * Asserts that a value is null. This uses the triple equals sign
		 * so no type cohersion may occur.
		 * @param actual The actual value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static isNull( actual:any, message?:string ):void;

		/**
		 * Asserts that a value is undefined. This uses the triple equals sign
		 * so no type cohersion may occur.
		 * @param actual The actual value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static isUndefined( actual:any, message?:string ):void;

		//--------------------------------------------------------------------------
		// Instance Assertion Methods
		//--------------------------------------------------------------------------

		/**
		 * Asserts that a value is an array.
		 * @param actual The value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static isArray( actual:any, message?:string ):void;

		/**
		 * Asserts that a value is a Boolean.
		 * @param actual The value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static isBoolean( actual:any, message?:string ):void;

		/**
		 * Asserts that a value is a function.
		 * @param actual The value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static isFunction( actual:any, message?:string ):void;

		/**
		 * Asserts that a value is an instance of a particular object. This may return
		 * incorrect results when comparing objects from one frame to constructors in
		 * another frame. For best results, don't use in a cross-frame manner.
		 * @param {Function} expected The function that the object should be an instance of.
		 * @param actual The object to test.
		 * @param message The message to display if the assertion fails.
		 */
		static isInstanceOf( expected:any, actual:any, message?:string ):void;

		/**
		 * Asserts that a value is a number.
		 * @param actual The value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static isNumber( actual:any, message?:string ):void;

		/**
		 * Asserts that a value is an object.
		 * @param actual The value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static isObject( actual:any, message?:string ):void;

		/**
		 * Asserts that a value is a string.
		 * @param actual The value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static isString( actual:any, message?:string ):void;

		/**
		 * Asserts that a value is of a particular type.
		 * @param expectedType The expected type of the variable.
		 * @param actualValue The actual value to test.
		 * @param message The message to display if the assertion fails.
		 */
		static isTypeOf( expectedType:string, actualValue:any, message?:string ):void;

		//--------------------------------------------------------------------------
		// Error Detection Methods
		//--------------------------------------------------------------------------

		/**
		 * Asserts that executing a particular method should throw an error of
		 * a specific type. This is a replacement for _should.error.
		 *
		 * @param {String|Function|Object} expectedError
		 *      If a string, this  is the error message that the error must have; if a function,
		 *      this is the constructor that should have been used to create the thrown error; if an
		 *      object, this is an instance of a particular error type with a specific error message
		 *      (both must match).
		 * @param method The method to execute that should throw the error.
		 * @param message The message to display if the assertion
		 *      fails.
		 */
		static throwsError( expectedError:any, method:Function, message?:string ):void;
	}
}


text:
namespace blink {

class MediaStream;
class MediaStreamTrack;
class RTCRtpReceiver;
class RTCRtpTransceiver;
class RTCTrackEventInit;

// https://w3c.github.io/webrtc-pc/#rtctrackevent
class RTCTrackEvent final : public Event {
  DEFINE_WRAPPERTYPEINFO();

 public:
  static RTCTrackEvent* Create(const AtomicString& type,
                               const RTCTrackEventInit* eventInitDict);
  RTCTrackEvent(RTCRtpReceiver*,
                MediaStreamTrack*,
                const HeapVector<Member<MediaStream>>&,
                RTCRtpTransceiver*);
  RTCTrackEvent(const AtomicString& type,
                const RTCTrackEventInit* eventInitDict);

  RTCRtpReceiver* receiver() const;
  MediaStreamTrack* track() const;
  const HeapVector<Member<MediaStream>>& streams() const;
  RTCRtpTransceiver* transceiver() const;

  void Trace(Visitor*) const override;

 private:
  Member<RTCRtpReceiver> receiver_;
  Member<MediaStreamTrack> track_;
  HeapVector<Member<MediaStream>> streams_;
  Member<RTCRtpTransceiver> transceiver_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_TRACK_EVENT_H_


text:
<?php

namespace WeinBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use WeinBundle\Entity\Weinstil;
use WeinBundle\Form\WeinstilType;

/**
 * Weinstil controller.
 *
 * @Route("/weinstil")
 */
class WeinstilController extends Controller
{

    /**
     * Lists all Weinstil entities.
     *
     * @Route("/", name="weinstil")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('WeinBundle:Weinstil')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new Weinstil entity.
     *
     * @Route("/", name="weinstil_create")
     * @Method("POST")
     * @Template("WeinBundle:Weinstil:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Weinstil();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('weinstil_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a form to create a Weinstil entity.
     *
     * @param Weinstil $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Weinstil $entity)
    {
        $form = $this->createForm(new WeinstilType(), $entity, array(
            'action' => $this->generateUrl('weinstil_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Erstellen'));

        return $form;
    }

    /**
     * Displays a form to create a new Weinstil entity.
     *
     * @Route("/new", name="weinstil_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Weinstil();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Weinstil entity.
     *
     * @Route("/{id}", name="weinstil_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('WeinBundle:Weinstil')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Weinstil entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Weinstil entity.
     *
     * @Route("/{id}/edit", name="weinstil_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('WeinBundle:Weinstil')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Weinstil entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a Weinstil entity.
    *
    * @param Weinstil $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Weinstil $entity)
    {
        $form = $this->createForm(new WeinstilType(), $entity, array(
            'action' => $this->generateUrl('weinstil_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Weinstil entity.
     *
     * @Route("/{id}", name="weinstil_update")
     * @Method("PUT")
     * @Template("WeinBundle:Weinstil:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('WeinBundle:Weinstil')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Weinstil entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('weinstil_show', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Weinstil entity.
     *
     * @Route("/{id}", name="weinstil_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('WeinBundle:Weinstil')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Weinstil entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('weinstil'));
    }

    /**
     * Creates a form to delete a Weinstil entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('weinstil_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => ' Löschen', 'attr' => array('class'=>'fi-trash')))
            ->getForm()
        ;
    }
}


text:
from ..assetsmanager import AssetsManager
from nagare import log
from PIL import Image
from PIL import ImageOps
import json
import os
import uuid

class SimpleAssetsManager(AssetsManager):

    thumb_size = (68, 68)
    medium_width = 425
    cover_size = (medium_width, 250)

    def __init__(self, basedirectory, app_name, **config):
        self.basedirectory = basedirectory
        self.app_name = app_name
        self.max_size = config['max_size']
        super(SimpleAssetsManager, self).__init__()

    def _get_filename(self, file_id, size=None):
        filename = os.path.join(self.basedirectory, file_id)
        if size and size != 'large':
            filename += '.' + size
        return filename

    def _get_metadata_filename(self, file_id):
        return os.path.join(self.basedirectory, '%s.metadata' % file_id)

    def save(self, data, file_id=None, metadata={}, thumb_size=()):
        if file_id is None:
            file_id = unicode(uuid.uuid4())
        with open(self._get_filename(file_id), "w") as f:
            f.write(data)
        # Store metadata
        with open(self._get_metadata_filename(file_id), "w") as f:
            f.write(json.dumps(metadata))

        img = None
        try:
            img = Image.open(self._get_filename(file_id))
        except IOError:
            log.info('Not an image file, skipping medium & thumbnail generation')
        else:
            # Store thumbnail & medium
            kw = {}
            if 'transparency' in img.info:
                kw['transparency'] = img.info["transparency"]

            orig_width, orig_height = img.size

            medium_size = self.medium_width, int(float(self.medium_width) * orig_height / orig_width)
            medium = img.copy()

            medium.thumbnail(medium_size, Image.ANTIALIAS)
            medium.save(self._get_filename(file_id, 'medium'), img.format, quality=75, **kw)  # 'JPEG')

            thumb = ImageOps.fit(img, thumb_size if thumb_size else self.thumb_size, Image.ANTIALIAS)
            thumb.save(self._get_filename(file_id, 'thumb'), img.format, quality=75, **kw)  # 'JPEG')

        return file_id

    def delete(self, file_id):
        files = [self._get_filename(file_id),
                 self._get_filename(file_id, 'thumb'),
                 self._get_filename(file_id, 'medium'),
                 self._get_filename(file_id, 'cover'),
                 self._get_filename(file_id, 'large'),
                 self._get_metadata_filename(file_id)]
        for f in files:
            try:
                os.remove(f)
            except OSError:  # File does not exist
                pass

    def load(self, file_id, size=None):
        filename = self._get_filename(file_id, size)
        with open(filename, "r") as f:
            data = f.read()
        return data, self.get_metadata(file_id)

    def update_metadata(self, file_id, metadata):
        pass

    def get_metadata(self, file_id):
        with open(self._get_metadata_filename(file_id), "r") as f:
            metadata = f.read()
        return json.loads(metadata)

    def get_image_size(self, fileid):
        """Return the image dimensions
        In:
            - ``fileid`` -- file identifier
        Return:
            - a tuple representing the image dimensions (width, height) or (None, None) in case of error
        """
        dim = (None, None)
        try:
            dim = Image.open(self._get_filename(fileid)).size
        except:
            log.error('Could not get image dimensions of %r', fileid, exc_info=True)
        return dim

    def get_image_url(self, file_id, size=None, include_filename=True):
        """Return an image significant URL
        In:
            - ``file_id`` -- file identifier
            - ``size`` -- size to get (thumb, medium, cover, large)
            - ``include_filename`` -- add the filename to the URL or not

        Return:
            - image significant URL
        """
        if self.app_name:
            url = ['', self.app_name, 'assets', file_id, size or 'large']
        else:
            url = ['', 'assets', file_id, size or 'large']
        if include_filename:
            url.append(self.get_metadata(file_id)['filename'])
        return '/'.join(url)

    def create_cover(self, file_id, left, top, width, height):
        """Create the cover version for a file

        In :
          - ``file_id`` -- The asset to make as cover
          - ``left`` -- Left coordinate of the crop origin
          - ``top`` -- Top coordinate of the crop origin
          - ``width`` -- Crop width
          - ``height`` -- Crop height
        """

        # The crop dimensions are given for the medium version.
        # Calculate them for the large version

        medium_img = Image.open(self._get_filename(file_id, 'medium'))
        medium_w, medium_h = medium_img.size

        large_img = Image.open(self._get_filename(file_id))
        large_w, large_h = large_img.size
        kw = {}
        if 'transparency' in large_img.info:
            kw['transparency'] = large_img.info["transparency"]

        left, width = int(float(left) * large_w / medium_w), int(float(width) * large_w / medium_w)
        top, height = int(float(top) * large_h / medium_h), int(float(height) * large_h / medium_h)

        n_img = large_img.crop((left, top, left + width, top + height))
        n_img.thumbnail(self.cover_size, Image.ANTIALIAS)
        n_img.save(self._get_filename(file_id, 'cover'), large_img.format, quality=75, **kw)


text:
/*global availity, describe, inject, it, beforeEach, expect, module*/

describe('avTemplateCache', function() {

  'use strict';

  var $httpBackend;
  var avTemplateCache;

  beforeEach(function() {
    module('availity');
    module('availity.ui');
  });

  beforeEach(inject(function(_$httpBackend_, _avTemplateCache_) {
    $httpBackend = _$httpBackend_;
    avTemplateCache = _avTemplateCache_;
  }));

  availity.mock.serviceSpecHelper();

  var fixtures = {
    'default': '
hi
'
  };

  it('should respond with markup with option `template`', function() {

    var options = {template: fixtures['default']};

    avTemplateCache.get(options).then(function(template) {
      expect(template).toBe(fixtures['default']);
    });

    availity.mock.$scope.$apply();

  });

  it('should respond with markup with option `tempalteUrl`', function() {

    $httpBackend.expectGET('demo/tpl.html').respond(fixtures['default']);

    var options = {templateUrl: 'demo/tpl.html'};

    avTemplateCache.get(options).then(function(template) {
      expect(template).toBe(fixtures['default']);
    });

    $httpBackend.flush();
    availity.mock.$scope.$apply();

  });

});


text:
Thank you for contributing to the Mattermost Android App - Pull Requests to this repository are reviewed monthly.

Please test your PRs before submitting, and if applicable include unit tests.

If this is your first pull request to a Mattermost repository, please also fill in the Contributor License Agreement at:
http://www.mattermost.org/mattermost-contributor-agreement/

You will then be added to our list of [approved contributors](https://docs.google.com/spreadsheets/d/1NTCeG-iL_VS9bFqtmHSfwETo5f-8MQ7oMDE5IUYJi_Y/pubhtml?gid=0&single=true).


text:
module SparseSeq where

import Data.Monoid
import qualified Data.Sequence as S

import Control.Applicative

data Movement a = Left Int
                | Right Int
                | MoveDown
                | ApplyOn (a -> a)

data Trav s z e =
  Trav
    {
      toTrav :: s -> z
    , fromTrav :: z -> s
    , extractElement :: z -> e
    , moveLeftTrav :: Int -> z -> z
    , moveRightTrav :: Int -> z -> z
    , applyOnTrav :: (e -> e) -> z -> z
    }

data SeqZip a = SeqZip { behind :: S.Seq a, focus :: a, ahead :: S.Seq a }

seqtoZip seq = SeqZip (seqTail seq) (seqHead seq) S.empty

seqFromZip (SeqZip left center right) = left S.>< (center S.<| right)

seqHead s = S.index s 0
seqTail s = S.drop 1 s

moveLeft 0 s = s
moveLeft n (SeqZip b c a) = SeqZip b' c' a' where
  (grabbed, left) = S.splitAt (n-1) a'
  b' = b S.>< (c S.<| (seqTail grabbed))
  c' = seqHead grabbed
  a' = left

moveRight 0 s = s
moveRight n (SeqZip b c a) = SeqZip b' c' a' where
  (grabbed, left) = S.splitAt (n-1) b'
  b' = left
  c' = seqHead grabbed
  a' = b S.>< (c S.<| (seqTail grabbed))

applyOn f (SeqZip b c a) = SeqZip b (f c) a

seqTrav :: Trav (S.Seq a) (SeqZip a) a
seqTrav = Trav seqtoZip seqFromZip focus moveLeft moveRight applyOn

movements :: [Int] -> [(Int, a -> a)] -> [Movement a]
movements shape indices = undefined

--The type of sparse sequences. This type holds its size,
--as it cannot be determined from its elements as in a normal sequence
--The sequence of elements contains the number of unused places between
--consequtive elements.
data SparseSeq a = SparseSeq { seqSize :: Int, seq :: S.Seq (Int, a) } deriving (Show)

fromSeq seq = SparseSeq len (S.zip (S.fromList (replicate len 0)) seq) where len = S.length seq
toSeq filler (SparseSeq size elements) = elements `mergeSparse` (S.replicate size filler)
sparseFromList = fromSeq . S.fromList
--sparseToList filler = S.fromList . toSeq filler

sparseSingleton a = SparseSeq 1 (S.singleton a)

offsetElements offset elements = ((\ (ix, a) -> (ix + offset, a)) <$> elements)

instance Monoid (SparseSeq a) where
  mempty = SparseSeq 0 S.empty
  (SparseSeq size elements) `mappend` (SparseSeq size' elements') =
    SparseSeq resultSize resultElements where
      resultSize = size + size'
      resultElements = elements S.>< (offsetElements size elements')

breakAt seq ix = let (front, back) = S.splitAt ix seq in (front, seqHead back, seqTail back)
sparseApply :: SparseSeq (a -> a) -> S.Seq a -> S.Seq a
sparseApply (SparseSeq size fs) as = sparseApply' fs as

sparseApply' fs as | S.null fs = as
sparseApply' fs as =
  let
    (ix, f) = seqHead fs
    (front, a, back) = as `breakAt` ix
  in
    front S.>< S.singleton (f a) S.>< sparseApply' (seqTail fs) back

--requires knowing distance from last element to end of sequence.
mergeSparseWith :: (a -> a -> a) -> S.Seq (Int, a) -> S.Seq (Int, a) -> S.Seq (Int, a)
mergeSparseWith f seq seq' = undefined
mergeSparse seq seq' = mergeSparseWith const

n `fitIn` m = (m `div` n) + if m `mod` n == 0 then 0 else 1
deepen :: Int -> SparseSeq a -> SparseSeq (SparseSeq a)
deepen n (SparseSeq size as) = SparseSeq (n `fitIn` size) as' where
  as' =

--applyOver :: (SparseSeq (a -> b)) -> S.Seq a -> S.Seq b
--applyOver sparse dense = mergeSparseWith ($) sparse (fromSeq dense)


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package rs.fon.eklub.dao.implementation;

import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
import rs.fon.eklub.core.data.DataAccessService;
import rs.fon.eklub.core.entities.Member;
import rs.fon.eklub.core.exceptions.DataAccessServiceException;
import rs.fon.eklub.util.Util;

/**
 *
 * @author milos
 */
@Repository
public class MemberDao implements DataAccessService<Member> {

    private SessionFactory sessionFactory;

    public MemberDao() {
    }

    public MemberDao(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public Member getEntity(long id) throws DataAccessServiceException {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Member member = session.get(Member.class, id);
            tx.commit();
            return member;
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
            throw new DataAccessServiceException(e.getMessage());
        } finally {
            session.close();
        }
    }

    @Override
    public List<Member> getAllEntities() throws DataAccessServiceException {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            List<Member> members = session.createQuery("from Member m").list();
            tx.commit();
            return members;
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
            throw new DataAccessServiceException(e.getMessage());
        } finally {
            session.close();
        }
    }

    @Override
    public List<Member> getEntities(Map<String, String> searchCriteria) throws DataAccessServiceException {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            String whereClause = Util.generateHibernateLikeClause(searchCriteria);
            List<Member> members = session.createQuery("from Member m " + whereClause).list();
            tx.commit();
            return members;
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
            throw new DataAccessServiceException(e.getMessage());
        } finally {
            session.close();
        }
    }

    @Override
    public void insertOrUpdateEntity(Member entity) throws DataAccessServiceException {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Member persistentMember = session.get(Member.class, new Long(entity.getId()));
            if (persistentMember == null) {
                session.save(entity);
            } else {
                persistentMember.setAddress(entity.getAddress());
                persistentMember.setDateOfBirth(entity.getDateOfBirth());
                persistentMember.setDateOfMembership(entity.getDateOfMembership());
                persistentMember.setEmail(entity.getEmail());
                persistentMember.setGender(entity.getGender());
                persistentMember.setGroup(entity.getGroup());
                persistentMember.setIdCard(entity.getIdCard());
                persistentMember.setNameSurname(entity.getNameSurname());
                persistentMember.setPhone(entity.getPhone());
                persistentMember.setRemark(entity.getRemark());
            }
            tx.commit();
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
            throw new DataAccessServiceException(e.getMessage());
        } finally {
            session.close();
        }
    }

    @Override
    public boolean deleteEntity(long id) throws DataAccessServiceException {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Query query = session.createQuery("delete from Member where id = :ID");
            query.setParameter("ID", id);
            int result = query.executeUpdate();
            tx.commit();
            return result > 0;
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
            throw new DataAccessServiceException(e.getMessage());
        } finally {
            session.close();
        }
    }
}


text:
// This file was generated by Mendix Modeler.
//
// WARNING: Code you write here will be lost the next time you deploy the project.

package datatablestestmodule.proxies;

public class ImportData
{
	private final com.mendix.systemwideinterfaces.core.IMendixObject importDataMendixObject;

	private final com.mendix.systemwideinterfaces.core.IContext context;

	/**
	 * Internal name of this entity
	 */
	public static final java.lang.String entityName = "DataTablesTestModule.ImportData";

	/**
	 * Enum describing members of this entity
	 */
	public enum MemberNames
	{
		JSON("JSON"),
		datalist("DataTablesTestModule.datalist");

		private java.lang.String metaName;

		MemberNames(java.lang.String s)
		{
			metaName = s;
		}

		@Override
		public java.lang.String toString()
		{
			return metaName;
		}
	}

	public ImportData(com.mendix.systemwideinterfaces.core.IContext context)
	{
		this(context, com.mendix.core.Core.instantiate(context, "DataTablesTestModule.ImportData"));
	}

	protected ImportData(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject importDataMendixObject)
	{
		if (importDataMendixObject == null)
			throw new java.lang.IllegalArgumentException("The given object cannot be null.");
		if (!com.mendix.core.Core.isSubClassOf("DataTablesTestModule.ImportData", importDataMendixObject.getType()))
			throw new java.lang.IllegalArgumentException("The given object is not a DataTablesTestModule.ImportData");

		this.importDataMendixObject = importDataMendixObject;
		this.context = context;
	}

	/**
	 * @deprecated Use 'ImportData.load(IContext, IMendixIdentifier)' instead.
	 */
	@Deprecated
	public static datatablestestmodule.proxies.ImportData initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
	{
		return datatablestestmodule.proxies.ImportData.load(context, mendixIdentifier);
	}

	/**
	 * Initialize a proxy using context (recommended). This context will be used for security checking when the get- and set-methods without context parameters are called.
	 * The get- and set-methods with context parameter should be used when for instance sudo access is necessary (IContext.createSudoClone() can be used to obtain sudo access).
	 */
	public static datatablestestmodule.proxies.ImportData initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject mendixObject)
	{
		return new datatablestestmodule.proxies.ImportData(context, mendixObject);
	}

	public static datatablestestmodule.proxies.ImportData load(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
	{
		com.mendix.systemwideinterfaces.core.IMendixObject mendixObject = com.mendix.core.Core.retrieveId(context, mendixIdentifier);
		return datatablestestmodule.proxies.ImportData.initialize(context, mendixObject);
	}

	/**
	 * Commit the changes made on this proxy object.
	 */
	public final void commit() throws com.mendix.core.CoreException
	{
		com.mendix.core.Core.commit(context, getMendixObject());
	}

	/**
	 * Commit the changes made on this proxy object using the specified context.
	 */
	public final void commit(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException
	{
		com.mendix.core.Core.commit(context, getMendixObject());
	}

	/**
	 * Delete the object.
	 */
	public final void delete()
	{
		com.mendix.core.Core.delete(context, getMendixObject());
	}

	/**
	 * Delete the object using the specified context.
	 */
	public final void delete(com.mendix.systemwideinterfaces.core.IContext context)
	{
		com.mendix.core.Core.delete(context, getMendixObject());
	}
	/**
	 * @return value of JSON
	 */
	public final java.lang.String getJSON()
	{
		return getJSON(getContext());
	}

	/**
	 * @param context
	 * @return value of JSON
	 */
	public final java.lang.String getJSON(com.mendix.systemwideinterfaces.core.IContext context)
	{
		return (java.lang.String) getMendixObject().getValue(context, MemberNames.JSON.toString());
	}

	/**
	 * Set value of JSON
	 * @param json
	 */
	public final void setJSON(java.lang.String json)
	{
		setJSON(getContext(), json);
	}

	/**
	 * Set value of JSON
	 * @param context
	 * @param json
	 */
	public final void setJSON(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String json)
	{
		getMendixObject().setValue(context, MemberNames.JSON.toString(), json);
	}

	/**
	 * @return value of datalist
	 */
	public final java.util.List<datatablestestmodule.proxies.Person> getdatalist() throws com.mendix.core.CoreException
	{
		return getdatalist(getContext());
	}

	/**
	 * @param context
	 * @return value of datalist
	 */
	@SuppressWarnings("unchecked")
	public final java.util.List<datatablestestmodule.proxies.Person> getdatalist(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException
	{
		java.util.List<datatablestestmodule.proxies.Person> result = new java.util.ArrayList<datatablestestmodule.proxies.Person>();
		Object valueObject = getMendixObject().getValue(context, MemberNames.datalist.toString());
		if (valueObject == null)
			return result;
		for (com.mendix.systemwideinterfaces.core.IMendixObject mendixObject : com.mendix.core.Core.retrieveIdList(context, (java.util.List<com.mendix.systemwideinterfaces.core.IMendixIdentifier>) valueObject))
			result.add(datatablestestmodule.proxies.Person.initialize(context, mendixObject));
		return result;
	}

	/**
	 * Set value of datalist
	 * @param datalist
	 */
	public final void setdatalist(java.util.List<datatablestestmodule.proxies.Person> datalist)
	{
		setdatalist(getContext(), datalist);
	}

	/**
	 * Set value of datalist
	 * @param context
	 * @param datalist
	 */
	public final void setdatalist(com.mendix.systemwideinterfaces.core.IContext context, java.util.List<datatablestestmodule.proxies.Person> datalist)
	{
		java.util.List<com.mendix.systemwideinterfaces.core.IMendixIdentifier> identifiers = new java.util.ArrayList<com.mendix.systemwideinterfaces.core.IMendixIdentifier>();
		for (datatablestestmodule.proxies.Person proxyObject : datalist)
			identifiers.add(proxyObject.getMendixObject().getId());
		getMendixObject().setValue(context, MemberNames.datalist.toString(), identifiers);
	}

	/**
	 * @return the IMendixObject instance of this proxy for use in the Core interface.
	 */
	public final com.mendix.systemwideinterfaces.core.IMendixObject getMendixObject()
	{
		return importDataMendixObject;
	}

	/**
	 * @return the IContext instance of this proxy, or null if no IContext instance was specified at initialization.
	 */
	public final com.mendix.systemwideinterfaces.core.IContext getContext()
	{
		return context;
	}

	@Override
	public boolean equals(Object obj)
	{
		if (obj == this)
			return true;

		if (obj != null && getClass().equals(obj.getClass()))
		{
			final datatablestestmodule.proxies.ImportData that = (datatablestestmodule.proxies.ImportData) obj;
			return getMendixObject().equals(that.getMendixObject());
		}
		return false;
	}

	@Override
	public int hashCode()
	{
		return getMendixObject().hashCode();
	}

	/**
	 * @return String name of this class
	 */
	public static java.lang.String getType()
	{
		return "DataTablesTestModule.ImportData";
	}

	/**
	 * @return String GUID from this object, format: ID_0000000000
	 * @deprecated Use getMendixObject().getId().toLong() to get a unique identifier for this object.
	 */
	@Deprecated
	public java.lang.String getGUID()
	{
		return "ID_" + getMendixObject().getId().toLong();
	}
}


text:
#include "config.h"
#include "core/html/HTMLFrameOwnerElement.h"

#include "core/dom/ExceptionCode.h"
#include "core/loader/FrameLoader.h"
#include "core/page/Frame.h"
#include "core/rendering/RenderPart.h"
#include "core/svg/SVGDocument.h"

namespace WebCore {

HTMLFrameOwnerElement::HTMLFrameOwnerElement(const QualifiedName& tagName, Document* document)
    : HTMLElement(tagName, document)
    , m_contentFrame(0)
    , m_sandboxFlags(SandboxNone)
{
}

RenderPart* HTMLFrameOwnerElement::renderPart() const
{
    // HTMLObjectElement and HTMLEmbedElement may return arbitrary renderers
    // when using fallback content.
    if (!renderer() || !renderer()->isRenderPart())
        return 0;
    return toRenderPart(renderer());
}

void HTMLFrameOwnerElement::setContentFrame(Frame* frame)
{
    // Make sure we will not end up with two frames referencing the same owner element.
    ASSERT(!m_contentFrame || m_contentFrame->ownerElement() != this);
    ASSERT(frame);
    // Disconnected frames should not be allowed to load.
    ASSERT(inDocument());
    m_contentFrame = frame;

    for (ContainerNode* node = this; node; node = node->parentOrShadowHostNode())
        node->incrementConnectedSubframeCount();
}

void HTMLFrameOwnerElement::clearContentFrame()
{
    if (!m_contentFrame)
        return;

    m_contentFrame = 0;

    for (ContainerNode* node = this; node; node = node->parentOrShadowHostNode())
        node->decrementConnectedSubframeCount();
}

void HTMLFrameOwnerElement::disconnectContentFrame()
{
    // FIXME: Currently we don't do this in removedFrom because this causes an
    // unload event in the subframe which could execute script that could then
    // reach up into this document and then attempt to look back down. We should
    // see if this behavior is really needed as Gecko does not allow this.
    if (Frame* frame = contentFrame()) {
        RefPtr<Frame> protect(frame);
        frame->loader()->frameDetached();
        frame->disconnectOwnerElement();
    }
}

HTMLFrameOwnerElement::~HTMLFrameOwnerElement()
{
    if (m_contentFrame)
        m_contentFrame->disconnectOwnerElement();
}

Document* HTMLFrameOwnerElement::contentDocument() const
{
    return m_contentFrame ? m_contentFrame->document() : 0;
}

DOMWindow* HTMLFrameOwnerElement::contentWindow() const
{
    return m_contentFrame ? m_contentFrame->document()->domWindow() : 0;
}

void HTMLFrameOwnerElement::setSandboxFlags(SandboxFlags flags)
{
    m_sandboxFlags = flags;
}

bool HTMLFrameOwnerElement::isKeyboardFocusable(KeyboardEvent* event) const
{
    return m_contentFrame && HTMLElement::isKeyboardFocusable(event);
}

SVGDocument* HTMLFrameOwnerElement::getSVGDocument(ExceptionCode& ec) const
{
    Document* doc = contentDocument();
    if (doc && doc->isSVGDocument())
        return toSVGDocument(doc);
    // Spec: http://www.w3.org/TR/SVG/struct.html#InterfaceGetSVGDocument
    ec = NOT_SUPPORTED_ERR;
    return 0;
}

} // namespace WebCore


text:
The module is published to the [rubygems.org][1] under the gem name [plaid][2].

The publishing process is handled by [rake][3].

After updating the package version, run:

```console
$ rake spec
$ rake build
$ rake release
```

See the [semantic versioning][4] guidelines to determine what level of release to publish.

[1]: https://rubygems.org
[2]: https://rubygems.org/gems/plaid
[3]: https://github.com/ruby/rake
[4]: http://semver.org


text:
package dmillerw.remoteio.tile;

import cpw.mods.fml.common.Optional;
import dmillerw.remoteio.lib.DependencyInfo;
import dmillerw.remoteio.tile.core.TileCore;
import ic2.api.energy.tile.IHeatSource;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFurnace;
import net.minecraft.init.Blocks;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityFurnace;
import net.minecraftforge.common.util.ForgeDirection;

/**
 * @author dmillerw
 */
@Optional.Interface(iface = DependencyInfo.Paths.IC2.IHEATSOURCE, modid = DependencyInfo.ModIds.IC2)
public class TileMachineHeater extends TileCore implements IHeatSource {

    public boolean filled = false;

    @Override
    public void writeCustomNBT(NBTTagCompound nbt) {
        nbt.setBoolean("filled", filled);
    }

    @Override
    public void readCustomNBT(NBTTagCompound nbt) {
        filled = nbt.getBoolean("filled");
    }

    @Override
    public void updateEntity() {
        if (!worldObj.isRemote && worldObj.getTotalWorldTime() % 20 == 0) {
            update();
            if (filled) push();
        }
    }

    @Override
    public void onNeighborUpdated() {
        update();
    }

    private void update() {
        int found = 0;
        for (ForgeDirection forgeDirection : ForgeDirection.VALID_DIRECTIONS) {
            Block block = worldObj.getBlock(xCoord + forgeDirection.offsetX, yCoord + forgeDirection.offsetY, zCoord + forgeDirection.offsetZ);
            if (block != null && (block == Blocks.lava || block == Blocks.flowing_lava)) found++;
        }
        boolean newFilled = found >= 2;
        if (filled != newFilled) worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
        filled = newFilled;
    }

    private void push() {
        for (ForgeDirection forgeDirection : ForgeDirection.VALID_DIRECTIONS) {
            TileEntity tileEntity = worldObj.getTileEntity(xCoord + forgeDirection.offsetX, yCoord + forgeDirection.offsetY, zCoord + forgeDirection.offsetZ);
            if (tileEntity != null && tileEntity instanceof TileEntityFurnace) {
                ((TileEntityFurnace) tileEntity).furnaceBurnTime = 200;
                if (tileEntity.getBlockType() == Blocks.furnace) {
                    BlockFurnace.updateFurnaceBlockState(true, worldObj, xCoord + forgeDirection.offsetX, yCoord + forgeDirection.offsetY, zCoord + forgeDirection.offsetZ);
                }
            }
        }
    }

    /* IHEATSOURCE */
    @Override
    @Optional.Method(modid = DependencyInfo.ModIds.IC2)
    public int maxrequestHeatTick(ForgeDirection directionFrom) {
        return 1;
    }

    @Override
    @Optional.Method(modid = DependencyInfo.ModIds.IC2)
    public int requestHeat(ForgeDirection directionFrom, int requestheat) {
        return filled ? requestheat : 0;
    }
}