text:
namespace rx
{
namespace
{
void FillTextureFormatCaps(RendererVk *renderer, VkFormat format, gl::TextureCaps *outTextureCaps)
{
    const VkPhysicalDeviceLimits &physicalDeviceLimits =
        renderer->getPhysicalDeviceProperties().limits;
    bool hasColorAttachmentFeatureBit =
        renderer->hasImageFormatFeatureBits(format, VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT);
    bool hasDepthAttachmentFeatureBit =
        renderer->hasImageFormatFeatureBits(format, VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT);

    outTextureCaps->texturable =
        renderer->hasImageFormatFeatureBits(format, VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT);
    outTextureCaps->filterable = renderer->hasImageFormatFeatureBits(
        format, VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT);
    outTextureCaps->blendable =
        renderer->hasImageFormatFeatureBits(format, VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT);

    // For renderbuffer and texture attachments we require transfer and sampling for
    // GLES 2.0 CopyTexImage support. Sampling is also required for other features like
    // blits and EGLImages.
    outTextureCaps->textureAttachment =
        outTextureCaps->texturable &&
        (hasColorAttachmentFeatureBit || hasDepthAttachmentFeatureBit);
    outTextureCaps->renderbuffer = outTextureCaps->textureAttachment;

    if (outTextureCaps->renderbuffer)
    {
        if (hasColorAttachmentFeatureBit)
        {
            vk_gl::AddSampleCounts(physicalDeviceLimits.framebufferColorSampleCounts,
                                   &outTextureCaps->sampleCounts);
        }
        if (hasDepthAttachmentFeatureBit)
        {
            // Some drivers report different depth and stencil sample counts.  We'll AND those
            // counts together, limiting all depth and/or stencil formats to the lower number of
            // sample counts.
            vk_gl::AddSampleCounts((physicalDeviceLimits.framebufferDepthSampleCounts &
                                    physicalDeviceLimits.framebufferStencilSampleCounts),
                                   &outTextureCaps->sampleCounts);
        }
    }
}

bool HasFullBufferFormatSupport(RendererVk *renderer, VkFormat vkFormat)
{
    return renderer->hasBufferFormatFeatureBits(vkFormat, VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT);
}

using SupportTest = bool (*)(RendererVk *renderer, VkFormat vkFormat);

template <class FormatInitInfo>
int FindSupportedFormat(RendererVk *renderer,
                        const FormatInitInfo *info,
                        size_t skip,
                        int numInfo,
                        SupportTest hasSupport)
{
    ASSERT(numInfo > 0);
    const int last = numInfo - 1;

    for (int i = static_cast<int>(skip); i < last; ++i)
    {
        ASSERT(info[i].format != angle::FormatID::NONE);
        if (hasSupport(renderer, info[i].vkFormat))
            return i;
    }

    if (skip > 0 && !hasSupport(renderer, info[last].vkFormat))
    {
        // We couldn't find a valid fallback, try again without skip
        return FindSupportedFormat(renderer, info, 0, numInfo, hasSupport);
    }

    ASSERT(info[last].format != angle::FormatID::NONE);
    ASSERT(hasSupport(renderer, info[last].vkFormat));
    return last;
}

}  // anonymous namespace

namespace vk
{

// Format implementation.
Format::Format()
    : intendedFormatID(angle::FormatID::NONE),
      internalFormat(GL_NONE),
      actualImageFormatID(angle::FormatID::NONE),
      vkImageFormat(VK_FORMAT_UNDEFINED),
      actualBufferFormatID(angle::FormatID::NONE),
      vkBufferFormat(VK_FORMAT_UNDEFINED),
      imageInitializerFunction(nullptr),
      textureLoadFunctions(),
      vertexLoadRequiresConversion(false),
      vkBufferFormatIsPacked(false),
      vkFormatIsInt(false),
      vkFormatIsUnsigned(false)
{}

void Format::initImageFallback(RendererVk *renderer, const ImageFormatInitInfo *info, int numInfo)
{
    size_t skip                 = renderer->getFeatures().forceFallbackFormat.enabled ? 1 : 0;
    SupportTest testFunction    = HasFullTextureFormatSupport;
    const angle::Format &format = angle::Format::Get(info[0].format);
    if (format.isInt() || (format.isFloat() && format.redBits >= 32))
    {
        // Integer formats don't support filtering in GL, so don't test for it.
        // Filtering of 32-bit float textures is not supported on Android, and
        // it's enabled by the extension OES_texture_float_linear, which is
        // enabled automatically by examining format capabilities.
        testFunction = HasNonFilterableTextureFormatSupport;
    }
    if (format.isSnorm() || format.isBlock)
    {
        // Rendering to SNORM textures is not supported on Android, and it's
        // enabled by the extension EXT_render_snorm.
        // Compressed textures also need to perform this check.
        testFunction = HasNonRenderableTextureFormatSupport;
    }
    int i = FindSupportedFormat(renderer, info, skip, static_cast<uint32_t>(numInfo), testFunction);

    actualImageFormatID      = info[i].format;
    vkImageFormat            = info[i].vkFormat;
    imageInitializerFunction = info[i].initializer;
}

void Format::initBufferFallback(RendererVk *renderer, const BufferFormatInitInfo *info, int numInfo)
{
    size_t skip = renderer->getFeatures().forceFallbackFormat.enabled ? 1 : 0;
    int i       = FindSupportedFormat(renderer, info, skip, static_cast<uint32_t>(numInfo),
                                HasFullBufferFormatSupport);

    actualBufferFormatID         = info[i].format;
    vkBufferFormat               = info[i].vkFormat;
    vkBufferFormatIsPacked       = info[i].vkFormatIsPacked;
    vertexLoadFunction           = info[i].vertexLoadFunction;
    vertexLoadRequiresConversion = info[i].vertexLoadRequiresConversion;
}

size_t Format::getImageCopyBufferAlignment() const
{
    // vkCmdCopyBufferToImage must have an offset that is a multiple of 4 as well as a multiple
    // of the texel size (if uncompressed) or pixel block size (if compressed).
    // https://www.khronos.org/registry/vulkan/specs/1.0/man/html/VkBufferImageCopy.html
    //
    // We need lcm(4, texelSize) (lcm = least common multiplier).  For compressed images,
    // |texelSize| would contain the block size.  Since 4 is constant, this can be calculated as:
    //
    //                      | texelSize             texelSize % 4 == 0
    //                      | 4 * texelSize         texelSize % 4 == 1
    // lcm(4, texelSize) = <
    //                      | 2 * texelSize         texelSize % 4 == 2
    //                      | 4 * texelSize         texelSize % 4 == 3
    //
    // This means:
    //
    // - texelSize % 2 != 0 gives a 4x multiplier
    // - else texelSize % 4 != 0 gives a 2x multiplier
    // - else there's no multiplier.
    //
    const angle::Format &format = actualImageFormat();

    ASSERT(format.pixelBytes != 0);
    const size_t texelSize  = format.pixelBytes;
    const size_t multiplier = texelSize % 2 != 0 ? 4 : texelSize % 4 != 0 ? 2 : 1;
    const size_t alignment  = multiplier * texelSize;

    return alignment;
}

bool Format::hasEmulatedImageChannels() const
{
    const angle::Format &angleFmt   = intendedFormat();
    const angle::Format &textureFmt = actualImageFormat();

    return (angleFmt.alphaBits == 0 && textureFmt.alphaBits > 0) ||
           (angleFmt.blueBits == 0 && textureFmt.blueBits > 0) ||
           (angleFmt.greenBits == 0 && textureFmt.greenBits > 0) ||
           (angleFmt.depthBits == 0 && textureFmt.depthBits > 0) ||
           (angleFmt.stencilBits == 0 && textureFmt.stencilBits > 0);
}

bool operator==(const Format &lhs, const Format &rhs)
{
    return &lhs == &rhs;
}

bool operator!=(const Format &lhs, const Format &rhs)
{
    return &lhs != &rhs;
}

// FormatTable implementation.
FormatTable::FormatTable() {}

FormatTable::~FormatTable() {}

void FormatTable::initialize(RendererVk *renderer,
                             gl::TextureCapsMap *outTextureCapsMap,
                             std::vector<GLenum> *outCompressedTextureFormats)
{
    for (size_t formatIndex = 0; formatIndex < angle::kNumANGLEFormats; ++formatIndex)
    {
        vk::Format &format               = mFormatData[formatIndex];
        const auto formatID              = static_cast<angle::FormatID>(formatIndex);
        const angle::Format &angleFormat = angle::Format::Get(formatID);

        format.initialize(renderer, angleFormat);
        const GLenum internalFormat = format.internalFormat;
        format.intendedFormatID     = formatID;

        if (!format.valid())
        {
            continue;
        }

        gl::TextureCaps textureCaps;
        FillTextureFormatCaps(renderer, format.vkImageFormat, &textureCaps);
        outTextureCapsMap->set(formatID, textureCaps);

        if (textureCaps.texturable)
        {
            format.textureLoadFunctions =
                GetLoadFunctionsMap(internalFormat, format.actualImageFormatID);
        }

        if (angleFormat.isBlock)
        {
            outCompressedTextureFormats->push_back(internalFormat);
        }
    }
}

VkImageUsageFlags GetMaximalImageUsageFlags(RendererVk *renderer, VkFormat format)
{
    constexpr VkFormatFeatureFlags kImageUsageFeatureBits =
        VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT |
        VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT |
        VK_FORMAT_FEATURE_TRANSFER_SRC_BIT | VK_FORMAT_FEATURE_TRANSFER_DST_BIT;
    VkFormatFeatureFlags featureBits =
        renderer->getImageFormatFeatureBits(format, kImageUsageFeatureBits);
    VkImageUsageFlags imageUsageFlags = 0;
    if (featureBits & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)
        imageUsageFlags |= VK_IMAGE_USAGE_SAMPLED_BIT;
    if (featureBits & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)
        imageUsageFlags |= VK_IMAGE_USAGE_STORAGE_BIT;
    if (featureBits & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)
        imageUsageFlags |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
    if (featureBits & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)
        imageUsageFlags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
    if (featureBits & VK_FORMAT_FEATURE_TRANSFER_SRC_BIT)
        imageUsageFlags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
    if (featureBits & VK_FORMAT_FEATURE_TRANSFER_DST_BIT)
        imageUsageFlags |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
    imageUsageFlags |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
    return imageUsageFlags;
}

}  // namespace vk

bool HasFullTextureFormatSupport(RendererVk *renderer, VkFormat vkFormat)
{
    constexpr uint32_t kBitsColor = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
                                    VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT |
                                    VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT;
    constexpr uint32_t kBitsDepth = VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT;

    return renderer->hasImageFormatFeatureBits(vkFormat, kBitsColor) ||
           renderer->hasImageFormatFeatureBits(vkFormat, kBitsDepth);
}

bool HasNonFilterableTextureFormatSupport(RendererVk *renderer, VkFormat vkFormat)
{
    constexpr uint32_t kBitsColor =
        VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT;
    constexpr uint32_t kBitsDepth = VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT;

    return renderer->hasImageFormatFeatureBits(vkFormat, kBitsColor) ||
           renderer->hasImageFormatFeatureBits(vkFormat, kBitsDepth);
}

bool HasNonRenderableTextureFormatSupport(RendererVk *renderer, VkFormat vkFormat)
{
    constexpr uint32_t kBitsColor =
        VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
    constexpr uint32_t kBitsDepth = VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT;

    return renderer->hasImageFormatFeatureBits(vkFormat, kBitsColor) ||
           renderer->hasImageFormatFeatureBits(vkFormat, kBitsDepth);
}

size_t GetVertexInputAlignment(const vk::Format &format)
{
    const angle::Format &bufferFormat = format.actualBufferFormat();
    size_t pixelBytes                 = bufferFormat.pixelBytes;
    return format.vkBufferFormatIsPacked ? pixelBytes : (pixelBytes / bufferFormat.channelCount);
}

GLenum GetSwizzleStateComponent(const gl::SwizzleState &swizzleState, GLenum component)
{
    switch (component)
    {
        case GL_RED:
            return swizzleState.swizzleRed;
        case GL_GREEN:
            return swizzleState.swizzleGreen;
        case GL_BLUE:
            return swizzleState.swizzleBlue;
        case GL_ALPHA:
            return swizzleState.swizzleAlpha;
        default:
            return component;
    }
}

// Places the swizzle obtained by applying second after first into out.
void ComposeSwizzleState(const gl::SwizzleState &first,
                         const gl::SwizzleState &second,
                         gl::SwizzleState *out)
{
    out->swizzleRed   = GetSwizzleStateComponent(first, second.swizzleRed);
    out->swizzleGreen = GetSwizzleStateComponent(first, second.swizzleGreen);
    out->swizzleBlue  = GetSwizzleStateComponent(first, second.swizzleBlue);
    out->swizzleAlpha = GetSwizzleStateComponent(first, second.swizzleAlpha);
}

void MapSwizzleState(const ContextVk *contextVk,
                     const vk::Format &format,
                     const bool sized,
                     const gl::SwizzleState &swizzleState,
                     gl::SwizzleState *swizzleStateOut)
{
    const angle::Format &angleFormat = format.intendedFormat();

    gl::SwizzleState internalSwizzle;

    if (angleFormat.isLUMA())
    {
        GLenum swizzleRGB, swizzleA;
        if (angleFormat.luminanceBits > 0)
        {
            swizzleRGB = GL_RED;
            swizzleA   = (angleFormat.alphaBits > 0 ? GL_GREEN : GL_ONE);
        }
        else
        {
            swizzleRGB = GL_ZERO;
            swizzleA   = GL_RED;
        }
        internalSwizzle.swizzleRed   = swizzleRGB;
        internalSwizzle.swizzleGreen = swizzleRGB;
        internalSwizzle.swizzleBlue  = swizzleRGB;
        internalSwizzle.swizzleAlpha = swizzleA;
    }
    else
    {
        if (angleFormat.hasDepthOrStencilBits())
        {
            bool hasRed = angleFormat.depthBits > 0;
            // In OES_depth_texture/ARB_depth_texture, depth
            // textures are treated as luminance.
            // If the internalformat was not sized, use OES_depth_texture behavior
            bool hasGB = hasRed && !sized;

            internalSwizzle.swizzleRed   = hasRed ? GL_RED : GL_ZERO;
            internalSwizzle.swizzleGreen = hasGB ? GL_RED : GL_ZERO;
            internalSwizzle.swizzleBlue  = hasGB ? GL_RED : GL_ZERO;
            internalSwizzle.swizzleAlpha = GL_ONE;
        }
        else
        {
            // Color bits are all zero for blocked formats
            if (!angleFormat.isBlock)
            {
                // Set any missing channel to default in case the emulated format has that channel.
                internalSwizzle.swizzleRed   = angleFormat.redBits > 0 ? GL_RED : GL_ZERO;
                internalSwizzle.swizzleGreen = angleFormat.greenBits > 0 ? GL_GREEN : GL_ZERO;
                internalSwizzle.swizzleBlue  = angleFormat.blueBits > 0 ? GL_BLUE : GL_ZERO;
                internalSwizzle.swizzleAlpha = angleFormat.alphaBits > 0 ? GL_ALPHA : GL_ONE;
            }
        }
    }
    ComposeSwizzleState(internalSwizzle, swizzleState, swizzleStateOut);
}
}  // namespace rx


text:
<?php if (!defined('APPLICATION')) exit();

/**
 * Message Model
 *
 * @package Conversations
 */

/**
 * Manages messages in a conversation.
 *
 * @since 2.0.0
 * @package Conversations
 */
class ConversationMessageModel extends Gdn_Model {
   /**
    * Class constructor. Defines the related database table name.
    *
    * @since 2.0.0
    * @access public
    */
   public function __construct() {
      parent::__construct('ConversationMessage');
      $this->PrimaryKey = 'MessageID';
   }

   /**
    * Get messages by conversation.
    *
    * Events: BeforeGet.
    *
    * @since 2.0.0
    * @access public
    *
    * @param int $ConversationID Unique ID of conversation being viewed.
    * @param int $ViewingUserID Unique ID of current user.
    * @param int $Offset Number to skip.
    * @param int $Limit Maximum to return.
    * @param array $Wheres SQL conditions.
    * @return Gdn_DataSet SQL results.
    */
   public function Get($ConversationID, $ViewingUserID, $Offset = '0', $Limit = '', $Wheres = '') {
      if ($Limit == '')
         $Limit = Gdn::Config('Conversations.Messages.PerPage', 50);

      $Offset = !is_numeric($Offset) || $Offset < 0 ? 0 : $Offset;
      if (is_array($Wheres))
         $this->SQL->Where($Wheres);

      $this->FireEvent('BeforeGet');
      return $this->SQL
         ->Select('cm.*')
         ->Select('iu.Name', '', 'InsertName')
         ->Select('iu.Email', '', 'InsertEmail')
         ->Select('iu.Photo', '', 'InsertPhoto')
         ->From('ConversationMessage cm')
         ->Join('Conversation c', 'cm.ConversationID = c.ConversationID')
         ->Join('UserConversation uc', 'c.ConversationID = uc.ConversationID and uc.UserID = '.$ViewingUserID, 'left')
         ->Join('User iu', 'cm.InsertUserID = iu.UserID', 'left')
         ->BeginWhereGroup()
         ->Where('uc.DateCleared is null')
         ->OrWhere('uc.DateCleared <', 'cm.DateInserted', TRUE, FALSE) // Make sure that cleared conversations do not show up unless they have new messages added.
         ->EndWhereGroup()
         ->Where('cm.ConversationID', $ConversationID)
         ->OrderBy('cm.DateInserted', 'asc')
         ->Limit($Limit, $Offset)
         ->Get();
   }

   /**
    * Get the data from the model based on its primary key.
    *
    * @param mixed $ID The value of the primary key in the database.
    * @param string $DatasetType The format of the result dataset.
    * @return Gdn_DataSet
    */
   public function GetID($ID, $DatasetType = FALSE) {
      $Result = $this->GetWhere(array("MessageID" => $ID))->FirstRow($DatasetType);
      return $Result;
   }

   /**
    * Get only new messages from conversation.
    *
    * @since 2.0.0
    * @access public
    *
    * @param int $ConversationID Unique ID of conversation being viewed.
    * @param int $LastMessageID Unique ID of last message to be viewed.
    * @return Gdn_DataSet SQL results.
    */
   public function GetNew($ConversationID, $LastMessageID) {
      $Session = Gdn::Session();
      $this->SQL->Where('MessageID > ', $LastMessageID);
      return $this->Get($ConversationID, $Session->UserID);
   }

   /**
    * Get number of messages in a conversation.
    *
    * @since 2.0.0
    * @access public
    *
    * @param int $ConversationID Unique ID of conversation being viewed.
    * @param int $ViewingUserID Unique ID of current user.
    * @param array $Wheres SQL conditions.
    * @return int Number of messages.
    */
   public function GetCount($ConversationID, $ViewingUserID, $Wheres = '') {
      if (is_array($Wheres))
         $this->SQL->Where($Wheres);

      $Data = $this->SQL
         ->Select('cm.MessageID', 'count', 'Count')
         ->From('ConversationMessage cm')
         ->Join('Conversation c', 'cm.ConversationID = c.ConversationID')
         ->Join('UserConversation uc', 'c.ConversationID = uc.ConversationID and uc.UserID = '.$ViewingUserID)
         ->BeginWhereGroup()
         ->Where('uc.DateCleared is null')
         ->OrWhere('uc.DateCleared >', 'c.DateUpdated', TRUE, FALSE) // Make sure that cleared conversations do not show up unless they have new messages added.
         ->EndWhereGroup()
         ->GroupBy('cm.ConversationID')
         ->Where('cm.ConversationID', $ConversationID)
         ->Get();

      if ($Data->NumRows() > 0)
         return $Data->FirstRow()->Count;

      return 0;
   }

   /**
    * Get number of messages that meet criteria.
    *
    * @since 2.0.0
    * @access public
    *
    * @param array $Wheres SQL conditions.
    * @return int Number of messages.
    */
   public function GetCountWhere($Wheres = '') {
      if (is_array($Wheres))
         $this->SQL->Where($Wheres);

      $Data = $this->SQL
         ->Select('MessageID', 'count', 'Count')
         ->From('ConversationMessage')
         ->Get();

      if ($Data->NumRows() > 0)
         return $Data->FirstRow()->Count;

      return 0;
   }

   /**
    * Save message from form submission.
    *
    * @since 2.0.0
    * @access public
    *
    * @param array $FormPostValues Values submitted via form.
    * @return int Unique ID of message created or updated.
    */
   public function Save($FormPostValues, $Conversation = NULL) {
      $Session = Gdn::Session();

      // Define the primary key in this model's table.
      $this->DefineSchema();

      // Add & apply any extra validation rules:
      $this->Validation->ApplyRule('Body', 'Required');
      $this->AddInsertFields($FormPostValues);

      $this->EventArguments['FormPostValues'] = $FormPostValues;
      $this->FireEvent('BeforeSaveValidation');

      // Validate the form posted values
      $MessageID = FALSE;
      if($this->Validate($FormPostValues)) {
         $Fields = $this->Validation->SchemaValidationFields(); // All fields on the form that relate to the schema
         TouchValue('Format', $Fields, C('Garden.InputFormatter', 'Html'));

         $this->EventArguments['Fields'] = $Fields;
         $this->FireEvent('BeforeSave');

         $MessageID = $this->SQL->Insert($this->Name, $Fields);
         $this->LastMessageID = $MessageID;
         $ConversationID = ArrayValue('ConversationID', $Fields, 0);

         if (!$Conversation)
            $Conversation = $this->SQL->GetWhere('Conversation', array('ConversationID' => $ConversationID))->FirstRow(DATASET_TYPE_ARRAY);

         $Message = $this->GetID($MessageID);
         $this->EventArguments['Conversation'] = $Conversation;
         $this->EventArguments['Message'] = $Message;
         $this->FireEvent('AfterSave');

         // Get the new message count for the conversation.
         $SQLR = $this->SQL
            ->Select('MessageID', 'count', 'CountMessages')
            ->Select('MessageID', 'max', 'LastMessageID')
            ->From('ConversationMessage')
            ->Where('ConversationID', $ConversationID)
            ->Get()->FirstRow(DATASET_TYPE_ARRAY);
         if (sizeof($SQLR)) {
            list($CountMessages, $LastMessageID) = array_values($SQLR);
         } else { return; }

         // Update the conversation's DateUpdated field.
         $DateUpdated = Gdn_Format::ToDateTime();

         $this->SQL
            ->Update('Conversation c')
            ->Set('CountMessages', $CountMessages)
            ->Set('LastMessageID', $LastMessageID)
            ->Set('UpdateUserID', Gdn::Session()->UserID)
            ->Set('DateUpdated', $DateUpdated)
            ->Where('ConversationID', $ConversationID)
            ->Put();

         // Update the last message of the users that were previously up-to-date on their read messages.
         $this->SQL
            ->Update('UserConversation uc')
            ->Set('uc.LastMessageID', $MessageID)
            ->Set('uc.DateConversationUpdated', $DateUpdated)
            ->Where('uc.ConversationID', $ConversationID)
            ->Where('uc.Deleted', '0')
            ->Where('uc.CountReadMessages', $CountMessages - 1)
            ->Where('uc.UserID <>', $Session->UserID)
            ->Put();

         // Update the date updated of the users that were not up-to-date.
         $this->SQL
            ->Update('UserConversation uc')
            ->Set('uc.DateConversationUpdated', $DateUpdated)
            ->Where('uc.ConversationID', $ConversationID)
            ->Where('uc.Deleted', '0')
            ->Where('uc.CountReadMessages <>', $CountMessages - 1)
            ->Where('uc.UserID <>', $Session->UserID)
            ->Put();

         // Update the sending user.
         $this->SQL
            ->Update('UserConversation uc')
            ->Set('uc.CountReadMessages', $CountMessages)
            ->Set('Deleted', 0)
            ->Set('uc.DateConversationUpdated', $DateUpdated)
            ->Where('ConversationID', $ConversationID)
            ->Where('UserID', $Session->UserID)
            ->Put();

         // Find users involved in this conversation
         $UserData = $this->SQL
            ->Select('UserID')
            ->Select('LastMessageID')
            ->Select('Deleted')
            ->From('UserConversation')
            ->Where('ConversationID', $ConversationID)
            ->Get()->Result(DATASET_TYPE_ARRAY);

         $UpdateCountUserIDs = array();
         $NotifyUserIDs = array();

         // Collapse for call to UpdateUserCache and ActivityModel.
         $InsertUserFound = FALSE;
         foreach ($UserData as $UpdateUser) {
            $LastMessageID = GetValue('LastMessageID', $UpdateUser);
            $UserID = GetValue('UserID', $UpdateUser);
            $Deleted = GetValue('Deleted', $UpdateUser);

            if ($UserID == GetValue('InsertUserID', $Fields)) {
               $InsertUserFound = TRUE;
               if ($Deleted) {
                  $this->SQL->Put('UserConversation', array('Deleted' => 0, 'DateConversationUpdated' => $DateUpdated), array('ConversationID' => $ConversationID, 'UserID' => $UserID));
               }
            }

            // Update unread for users that were up to date
            if ($LastMessageID == $MessageID)
               $UpdateCountUserIDs[] = $UserID;

            // Send activities to users that have not deleted the conversation
            if (!$Deleted)
               $NotifyUserIDs[] = $UserID;
         }

         if (!$InsertUserFound) {
            $UserConversation = array(
               'UserID' => GetValue('InsertUserID', $Fields),
               'ConversationID' => $ConversationID,
               'LastMessageID' => $LastMessageID,
               'CountReadMessages' => $CountMessages,
               'DateConversationUpdated' => $DateUpdated);
            $this->SQL->Insert('UserConversation', $UserConversation);
         }

         if (sizeof($UpdateCountUserIDs)) {
            $ConversationModel = new ConversationModel();
            $ConversationModel->UpdateUserUnreadCount($UpdateCountUserIDs, TRUE);
         }

         $this->FireEvent('AfterAdd');

         $ActivityModel = new ActivityModel();
         foreach ($NotifyUserIDs as $NotifyUserID) {
            if ($Session->UserID == $NotifyUserID)
               continue; // don't notify self.

            // Notify the users of the new message.
            $ActivityID = $ActivityModel->Add(
               $Session->UserID,
               'ConversationMessage',
               '',
               $NotifyUserID,
               '',
               "/messages/{$ConversationID}#{$MessageID}",
               FALSE
            );
            $Story = GetValue('Body', $Fields, '');

            if (C('Conversations.Subjects.Visible')) {
               $Story = ConcatSep("\n\n", GetValue('Subject', $Conversation, ''), $Story);
            }
            $ActivityModel->SendNotification($ActivityID, $Story);
         }
      }
      return $MessageID;
   }
}

redpajama_set_name: RedPajamaGithub


text:
@foreach($themes as $id => $theme)

{{ $theme->name }}

{{ $theme->description }}

	@if($id === $current)
		<button class="btn btn-block btn-warning disabled">
			{{ trans('orchestra/control::label.themes.current') }}
		</button>
	@else
		 true]) !!}" class="btn btn-block btn-primary">
			{{ trans('orchestra/control::label.themes.activate') }}

	@endif

@endforeach


text:
module Lightweight
  class InteractiveItem < ActiveRecord::Base
    attr_accessible :interactive, :interactive_page, :position

    belongs_to :interactive_page
    belongs_to :interactive, :polymorphic => true
  end
end


text:
// Karma configuration
// Generated on Wed Oct 23 2013 22:13:42 GMT+0100 (GMT Daylight Time)

module.exports = function(config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '',

    preprocessors: {
        '../**/*.htm': ['ng-html2js']
    },

    ngHtml2JsPreprocessor: {
        // strip this from the file path
        stripPrefix: '..',
    },

    // frameworks to use
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      '../lib/jquery-1.8.2.min.js',
      '../lib/angular.1.2.26.js',
      '../lib/angular-mocks.1.2.26.js',
      '../jasmine/spec/*.js',
      '../acute.select/*.js'
    ],

    // list of files to exclude
    exclude: [

    ],

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['Chrome'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};


text:
package com.accela.tetrixgame.conn.support.SocketConnectionCenter;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;

import com.accela.tetrixgame.Common;
import com.accela.tetrixgame.conn.connector.ClientDisconnectException;
import com.accela.tetrixgame.conn.connector.Connector;
import com.accela.tetrixgame.conn.shared.ClientID;
import com.accela.tetrixgame.conn.support.ObjectStreams.HPObjectInputStream;
import com.accela.tetrixgame.conn.support.ObjectStreams.HPObjectOutputStream;

/**
 * 这个Connector和SocketConnector完全相同,只是对象输入输出流使用了
 * HPObectInputStream和HPObjectOutputStream
 *
 */
public class HPObjectStreamSocketConnector extends Connector {
	private Socket client;
	private HPObjectInputStream inputStream;
	private HPObjectOutputStream outputStream;

	public HPObjectStreamSocketConnector(Socket client) {
		if (null == client) {
			throw new NullPointerException();
		}

		this.client = client;
	}

	@Override
	protected void closeImpl() throws IOException {
		try {
			inputStream.close();
			inputStream = null;
			outputStream.close();
			outputStream = null;
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			try {
				client.close();
			} catch (IOException ex) {
				throw ex;
			}

		}
	}

	@Override
	protected ClientID getClientIDImpl() {
		if (null == client) {
			throw new NullPointerException(
					"SocketConnector's property client is null.");
		}
		SocketClientID clientID = new SocketClientID(client.getInetAddress(),
				client.getPort());
		return clientID;
	}

	@Override
	protected void openImpl() {
		if (!SocketConnectionCenterUtilities.checkOpened(client)) {
			throw new IllegalStateException(
					"the socket used in SocketConnector is not opened");
		}

		try {
			inputStream = new HPObjectInputStream(new BufferedInputStream(
					client.getInputStream()));
			outputStream = new HPObjectOutputStream(new BufferedOutputStream(
					client.getOutputStream()));
		} catch (IOException ex) {
			throw new IllegalStateException(
					"failed to create input or output stream");
		}

	}

	@Override
	protected Object receiveMessageFromClient() throws IOException,
			ClassNotFoundException, InvocationTargetException,
			InstantiationException, ClientDisconnectException {
		try {
			Object message = inputStream.readObject();
			Common.LOG.info("HPObjectStreamSocketConnector received message: "+message);
			return message;
		} catch (EOFException ex) {
			throw new ClientDisconnectException();
		}
	}

	@Override
	protected void sendMessageToClient(Object message) throws IOException {
		outputStream.writeObject(message);
		outputStream.flush();
	}

}


text:
ctrlp() {
  local filesToEdit=()
  local previewCmd='cat -n 500'

  # Use bat as the previewer if available.
  if [ -x "$(command -v bat)" ]; then
    previewCmd='bat --color=always --style=numbers --line-range=:500 {}'
  fi

  # Prioritized list of fuzzy search tools used to find files.
  if [ -n "$(command -v fzf)" ]; then
    filesToEdit=($(fzf --preview "${previewCmd}"))
  elif [ -n "$(command -v fzy)" ]; then
    filesToEdit=($(fd -t f '.' . | fzy))
  fi

  if [ -n "${filesToEdit[*]}" ]; then
    edit "${filesToEdit[@]}"
  fi
}

# Open a number of files containing text matching an input pattern in the
# configured $EDITOR program.
# Optionally takes a second string of CLI options for the search command.
grepedit() {
  local searchCommand="grep -l"
  # The regex to search files for.
  local searchPattern="${1}"
  # Extra CLI options for the search command (not required).
  local extraOpts="${2}"

  if [ -z "${searchPattern}" ]; then
    err "No search pattern provided to patedit."
    return 1
  fi

  if [ -x "$(command -v rg)" ]; then
    # Use ripgrep if available.
    searchCommand="rg -l"
  elif [ -x "$(command -v ag)" ]; then
    # In lieu of ripgrep, the_silver_searcher is still better than grep.
    searchCommand="ag -l"
  fi

  # Add extra CLI args to search command if they were provided.
  [ -n "${extraOpts}" ] && searchCommand="${searchCommand} ${extraOpts}"

  # Add the search pattern to the end of the search command.
  searchCommand="${searchCommand} -- '${searchPattern}'"

  # Open the files in the configured editor
  eval "edit "$(eval "${searchCommand}")""
}

# Open a "source" file in the configured editor.
esf() {
  pushd "$DOTFILES_HOME/bash/source" &>/dev/null
  ctrlp
  popd &>/dev/null
}

# Remove all Vim swap files
rmvimswap() {
  rm -f "${VIM_SWAPS}"/*
}

# Remove all Vim backup files
rmvimbackup() {
  rm -f "${VIM_BACKUPS}"/*
}

# Open ~/.vimrc or ~/.config/nvim/init.vim in the configured editor, depending
# on whether EDITOR is configured for vim or nvim, respectively.
editvimrc() {
  # Set Vim config file based on which version is in use.
  local vimConfigFile="${HOME}/.vimrc"
  if [ "${EDITOR}" = "nvim" ]; then
    vimConfigFile="${USER_CONF}/nvim/init.vim"
  fi
  edit "${vimConfigFile}"
}

# vim:foldenable:foldmethod=indent


text:
@interface SWTiltTransitionAnimation : NSObject <UIViewControllerAnimatedTransitioning>

@property (nonatomic, assign) BOOL presenting;

@end


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Nicolaslopezj\Searchable\SearchableTrait;

class Product extends Model
{
    use SearchableTrait;

	protected $fillable = [
		'name',
		'price',
		'qty',
		'desc',
	];

    /**
     * Searchable rules.
     *
     * @var array
     */
    protected $searchable = [
        'columns' => [
            'name' => 10
        ]
    ];

    public function posts()
    {
        return $this->hasMany('Post');
    }

    /**
     * The Attributes that belong to the product.
     */
    public function attributes()
    {
        return $this->belongsToMany('App\Attribute')->withPivot('value')->withTimestamps();
    }
}


text:
layout: post
title: Buy In Activities
date: 2019-06-06 00:48
Tags: [ productivity, blog ]
permalink: /buy-in/
author: Kevin Olega
---
You have to buy in to play.

### BUY IN ACTIVITIES PART 1

Activities that allow me to do the things that I need to do.

- Avoid Phone = Alpha State (killed most of Dad's business, also an ambition killer)
- Overhead Squat or Air Squats (if you don't have any gear available)
- L-Theanine and/or 5-HTP
- Cold Shower (wakes you up and activates your good ideas)
- Journalling and/or wrtite in the morning (trap your worries and distractions on paper)
- Prayer (summon the power from the Creator)
- Headspace (put the smart you in charge and give the stupid you a break)
- Walk Fluffy (because it makes you a better person overall)

### BUY IN ACTIVITIES PART 2

Activities that allow me the resources to do the things that I want to do.

- 6 hours of work with TAW
- 2 hours of work for LKC
- Send 2 Job Applications

### BUY IN ACTIVITIES PART 3

Activities that I want to do that are good for me.

- Bike ride
- Drawing
- Blogging
- Prospecting for new clients
- Teaching Mitzi how to sell
- Out of area dates
- CrossFit
- Anime
- PS Vita

#### BUY IN ACTIVITIES PART 4

Activities that are fun but use up resources and are good for me sparingly and harmful frequently.

- Visit Friends
- Shopping
- Gadgets

### Note about Buy In Activities:

Buy in is a concept I picked up in CrossFit.

I'm copying this definition.

> Something you must complete before proceeding onto the main workout. Can also be called a "cash-in".

> For example, this workout: 5 min AMRAP (as many rounds as possible) of 12 handstand pushups and 20 situps. Buy in of 30 pushups.

> This means you must complete the buy in of 30 pushups before you start the AMRAP.

In my case I merged it to [Stephen Covey's 4 Quadrants of Time Management](https://succeedfeed.com/stephen-covey-4-quadrants-to-be-productive/) making the previous quadrant the "Buy in" for the next level of activities.


text:
<?xml version='1.0' encoding='UTF-8'?>
<hopsanobjectappearance version="0.3">
    <modelobject sourcecode="MechanicJLink2.hpp" typename="MechanicJLink2" displayname="MechanicJLink2">
        <icons>
            <icon scale="1" path="MechanicJLink.svg" iconrotation="ON" type="user"/>
            <icon scale="1" path="MechanicJLink.svg" iconrotation="ON" type="iso"/>
        </icons>
		<help>
            <text>Mechanical link with two linear ports. CDF-player for Mathematica documents can be found on http://www.wolfram.com/cdf-player/</text>
            <link>MechanicJLink.nb</link>
        </help>
        <ports>
            <port x="0.5" y="0.9" a="90" name="Pm0"/>
            <port x="0.5" y="1" a="90" name="Pm1"/>
            <port x="0.5" y="0" a="270" name="Pmr2"/>
        </ports>
    </modelobject>
</hopsanobjectappearance>


text:
"""Tests decoding metadata from log strings."""

import unittest

from pw_log_tokenized import FormatStringWithMetadata

class TestFormatStringWithMetadata(unittest.TestCase):
    """Tests extracting metadata from a pw_log_tokenized-style format string."""
    def test_all_fields(self):
        log = FormatStringWithMetadata(
            '■msg♦hello %d■file♦__FILE__■module♦log module name!')
        self.assertEqual(log.message, 'hello %d')
        self.assertEqual(log.module, 'log module name!')
        self.assertEqual(log.file, '__FILE__')

    def test_different_fields(self):
        log = FormatStringWithMetadata('■msg♦hello %d■module♦■THING♦abc123')
        self.assertEqual(log.message, 'hello %d')
        self.assertEqual(log.module, '')
        self.assertEqual(log.file, '')
        self.assertEqual(log.fields['THING'], 'abc123')

    def test_no_metadata(self):
        log = FormatStringWithMetadata('a■msg♦not formatted correctly')
        self.assertEqual(log.message, log.raw_string)
        self.assertEqual(log.module, '')
        self.assertEqual(log.file, '')

    def test_invalid_field_name(self):
        log = FormatStringWithMetadata('■msg♦M♦S♦G■1abc♦abc■other♦hi')
        self.assertEqual(log.message, 'M♦S♦G■1abc♦abc')
        self.assertEqual(log.fields['other'], 'hi')

    def test_delimiters_in_value(self):
        log = FormatStringWithMetadata('■msg♦♦■♦■yo■module♦M♦DU■E')
        self.assertEqual(log.message, '♦■♦■yo')
        self.assertEqual(log.module, 'M♦DU■E')

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


text:
class Client : public QObject {
    Q_OBJECT
friend class MainWindow;

public:
	explicit Client(QObject* parent = 0);
	Client(QString serverAddr = "127.0.0.1", QString portNr = "10013", QString username = "test user");

	QString getUsername() { return username; }

	void connectToServer();
	void sendPackage(QString package);

private:
	QString serverAddr;
    QString portNr;
	QString username;
	QSharedPointer<QTcpSocket> tcpSocket;
	QSharedPointer<QDataStream> dataStream;

	Packaging packaging;

signals:
    void readyRead();
    void error();
	void login();
	void receivedMessage(QString message);
	void receivedUsersList(QString usersList);
	void receivedPrivateMessage(QString receiver, QString message, QString sender);

public slots:
	void onLoginRequest();
	void onReadMsg();
	void onLogoutRequest();
	void onGlobalPackage(QString message);
	void onSendPrivateMessage(QString receiver, QString message, QString sender);
	void onSendFile(QByteArray blob, int fileSize, QString receiver, QString sender);
};

#endif // CLIENT_H


text:
package com.mx.popcorn.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Date;

/**
 * Created by Administrator on 2014-10-28.
 */
@Entity
public class MovieNew {

    @Id
    @GeneratedValue
    private Long id;

    @Column(length = 50)
    private String title;

    @Column(length = 3000)
    private String content;

    private Date createDate;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
}


text:
static LSSharedFileListRef shared_file_list() {
    static LSSharedFileListRef list;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        list = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
    });
    return list;
}

BOOL MJAutoLaunchGet(void) {
    NSURL *appURL = [[[NSBundle mainBundle] bundleURL] fileReferenceURL];

    UInt32 seed;
    NSArray *sharedFileListArray = (__bridge_transfer NSArray*)LSSharedFileListCopySnapshot(shared_file_list(), &seed);
    for (id item in sharedFileListArray) {
        LSSharedFileListItemRef sharedFileItem = (__bridge LSSharedFileListItemRef)item;
        CFURLRef url = NULL;

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        OSStatus result = LSSharedFileListItemResolve(sharedFileItem, 0, &url, NULL);
#pragma clang diagnostic pop
        if (result == noErr && url != NULL) {
            BOOL foundIt = [appURL isEqual: [(__bridge NSURL*)url fileReferenceURL]];

            CFRelease(url);

            if (foundIt) {
                return YES;
            }
        }
    }

    return NO;
}

void MJAutoLaunchSet(BOOL opensAtLogin) {
    NSURL *appURL = [[[NSBundle mainBundle] bundleURL] fileReferenceURL];

    if (!appURL) {
        NSLog(@"ERROR: Unable to get mainBundle URL");
        return;
    }

    if (opensAtLogin) {
        LSSharedFileListItemRef result = LSSharedFileListInsertItemURL(shared_file_list(),
                                                                       kLSSharedFileListItemLast,
                                                                       NULL,
                                                                       NULL,
                                                                       (__bridge CFURLRef)appURL,
                                                                       NULL,
                                                                       NULL);
        if (result) CFRelease(result);
    }
    else {
        UInt32 seed;
        NSArray *sharedFileListArray = (__bridge_transfer NSArray*)LSSharedFileListCopySnapshot(shared_file_list(), &seed);
        for (id item in sharedFileListArray) {
            LSSharedFileListItemRef sharedFileItem = (__bridge LSSharedFileListItemRef)item;
            CFURLRef url = NULL;

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
            OSStatus result = LSSharedFileListItemResolve(sharedFileItem, 0, &url, NULL);
#pragma clang diagnostic pop
            if (result == noErr && url != nil) {
                if ([appURL isEqual: [(__bridge NSURL*)url fileReferenceURL]])
                    LSSharedFileListItemRemove(shared_file_list(), sharedFileItem);

                CFRelease(url);
            }
        }
    }
}


text:
#import "UserProfileUtils.h"
#import "SocialActionUtils.h"

@class UserProfile;
@class Reward;

// Events
#define EVENT_UP_PROFILE_INITIALIZED            @"up_profile_initialized"

#define EVENT_UP_USER_PROFILE_UPDATED           @"up_user_profile_updated"

#define EVENT_UP_USER_RATING                    @"up_user_rating"

#define EVENT_UP_LOGIN_STARTED                  @"up_login_started"
#define EVENT_UP_LOGIN_FINISHED                 @"up_login_finished"
#define EVENT_UP_LOGIN_FAILED                   @"up_login_failed"
#define EVENT_UP_LOGIN_CANCELLED                @"up_login_cancelled"

#define EVENT_UP_LOGOUT_STARTED                 @"up_logout_started"
#define EVENT_UP_LOGOUT_FINISHED                @"up_logout_finished"
#define EVENT_UP_LOGOUT_FAILED                  @"up_logout_failed"

#define EVENT_UP_SOCIAL_ACTION_STARTED          @"up_social_action_started"
#define EVENT_UP_SOCIAL_ACTION_FINISHED         @"up_social_action_finished"
#define EVENT_UP_SOCIAL_ACTION_CANCELLED        @"up_social_action_cancelled"
#define EVENT_UP_SOCIAL_ACTION_FAILED           @"up_social_action_failed"

#define EVENT_UP_GET_CONTACTS_STARTED           @"up_get_contacts_started"
#define EVENT_UP_GET_CONTACTS_FINISHED          @"up_get_contacts_finished"
#define EVENT_UP_GET_CONTACTS_FAILED            @"up_get_contacts_failed"

#define EVENT_UP_GET_FEED_STARTED           @"up_get_feed_started"
#define EVENT_UP_GET_FEED_FINISHED          @"up_get_feed_finished"
#define EVENT_UP_GET_FEED_FAILED            @"up_get_feed_failed"

// UserProfile Elements
#define DICT_ELEMENT_USER_PROFILE               @"userProfile"
#define DICT_ELEMENT_PROVIDER                   @"provider"
#define DICT_ELEMENT_PAYLOAD                    @"payload"
#define DICT_ELEMENT_SOCIAL_ACTION_TYPE         @"socialActiontype"
#define DICT_ELEMENT_MESSAGE                    @"message"
#define DICT_ELEMENT_CONTACTS                   @"contacts"
#define DICT_ELEMENT_FEEDS                      @"feeds"
#define DICT_ELEMENT_REWARD                     @"reward"
#define DICT_ELEMENT_IS_BADGE                   @"isBadge"

/**
 * This class is used to register and post all the supported profile events.
 * Use this class to invoke events on handlers when they occur.
 *
 * SOOMLA uses iOS's `NSNotificationCenter` to handle events across the SDK.
 */
@interface ProfileEventHandling : NSObject

/**
 Subscribes the provider observer to all the profile events at once,
 the supplied selector will be called when any of the events fired

 @param observer the subscriber to the events
 @param selector the selector to call on the observer when events are fired
 */
+ (void)observeAllEventsWithObserver:(id)observer withSelector:(SEL)selector;

/**
Called when the service has been initializedt.
*/
+ (void)postProfileInitialized;

/**
 Called when the app's rating page is opened
 */
+ (void)postUserRating;

/**
 Called when a user profile from a provider has been retrieved
 and updated in the device's local storage. Which fires the
 `EVENT_UP_USER_PROFILE_UPDATED` event.

 @param userProfile The user's profile which was updated
 */
+ (void)postUserProfileUpdated:(UserProfile *)userProfile;

/**
 Called when the login process to a provider has started. Which fires the
 `EVENT_UP_LOGIN_STARTED` event.

 @param provider The provider on where the login has started
 */
+ (void)postLoginStarted:(Provider)provider withPayload:(NSString *)payload;

/**
 Called when the login process finishes successfully. Which fires the
 `EVENT_UP_LOGIN_FINISHED` event.

 @param userProfile The user's profile from the logged in provider
 */
+ (void)postLoginFinished:(UserProfile *)userProfile withPayload:(NSString *)payload;

/**
 Called when the login process to a provider has failed. Which fires the
 `EVENT_UP_LOGIN_FAILED` event.

 @param provider The provider on which the login has failed
 @param message a Description of the reason for failure
 */
+ (void)postLoginFailed:(Provider)provider withMessage:(NSString *)message withPayload:(NSString *)payload;

/**
 Called the login process to a provider has been cancelled. Which fires the
 `EVENT_UP_LOGIN_CANCELLED` event.

 @param provider The provider on which the login has failed
 */
+ (void)postLoginCancelled:(Provider)provider withPayload:(NSString *)payload;

/**
 Called when the logout process from a provider has started. Which fires the
 `EVENT_UP_LOGOUT_STARTED` event.

 @param provider The provider on which the login has started.
 */
+ (void)postLogoutStarted:(Provider)provider;

/**
 Called when the logout process from a provider has finished. Which fires the
 `EVENT_UP_LOGOUT_FINISHED` event.

 @param provider The provider on which the logout has finished
 */
+ (void)postLogoutFinished:(Provider)provider;

/**
 Called when the logout process from a provider has failed. Which fires the
 `EVENT_UP_LOGOUT_FAILED` event.

 @param provider The provider on which the logout has failed
 @param message a Description of the reason for failure
 */
+ (void)postLogoutFailed:(Provider)provider withMessage:(NSString *)message;

/**
 Called when a generic social action on a provider has started. Which fires the
 `EVENT_UP_SOCIAL_ACTION_STARTED` event.

 @param provider The provider on which the social action has started
 @param socialActionType The social action which started
 */
+ (void)postSocialActionStarted:(Provider)provider withType:(SocialActionType)socialActionType withPayload:(NSString *)payload;

/**
 Called when a generic social action on a provider has finished. Which fires the
 `EVENT_UP_SOCIAL_ACTION_FINISHED` event.

 @param provider The provider on which the social action has finished
 @param socialActionType The social action which finished
 */
+ (void)postSocialActionFinished:(Provider)provider withType:(SocialActionType)socialActionType withPayload:(NSString *)payload;

/**
 Called when a generic social action on a provider has been cancelled. Which fires
 the `EVENT_UP_SOCIAL_ACTION_CANCELLED` event.

 @param provider The provider on which the social action has been cancelled
 @param socialActionType The social action which was cancelled
 */
+ (void)postSocialActionCancelled:(Provider)provider withType:(SocialActionType)socialActionType withPayload:(NSString *)payload;

/**
 Called when a generic social action on a provider has failed. Which fires the
 `EVENT_UP_SOCIAL_ACTION_FAILED` event.

 @param provider The provider on which the social action has failed
 @param socialActionType The social action which failed
 @param message a Description of the reason for failure
 */
+ (void)postSocialActionFailed:(Provider)provider withType:(SocialActionType)socialActionType withMessage:(NSString *)message withPayload:(NSString *)payload;

/**
 Called when the get contacts process from a provider has started. Which fires the
 `EVENT_UP_GET_CONTACTS_STARTED` event.

 @param provider The provider on which the get contacts process started
 @param socialActionType The social action which is preformed
 */
+ (void)postGetContactsStarted:(Provider)provider withType:(SocialActionType)socialActionType withPayload:(NSString *)payload;

/**
 Called when the get contacts process from a provider has finished. Which fires the
 `EVENT_UP_GET_CONTACTS_FINISHED` event.

 @param provider The provider on which the get contacts process finished
 @param socialActionType The social action which is preformed
 @param contacts an Array of contacts represented by `UserProfile`
 */
+ (void)postGetContactsFinished:(Provider)provider withType:(SocialActionType)socialActionType withContacts:(NSArray *)contacts withPayload:(NSString *)payload;

/**
 Called when the get contacts process from a provider has failed. Which fires the
 `EVENT_UP_GET_CONTACTS_FAILED` event.

 @param provider The provider on which the get contacts process has
 failed
 @param socialActionType The social action which is preformed
 @param message a Description of the reason for failure
 */
+ (void)postGetContactsFailed:(Provider)provider withType:(SocialActionType)socialActionType withMessage:(NSString *)message withPayload:(NSString *)payload;

/**
 Called when the get feed process from a provider has started. Which fires the
 `EVENT_UP_GET_FEED_STARTED` event.

 @param provider The provider on which the get feed process started
 @param socialActionType The social action which is preformed
 */
+ (void)postGetFeedStarted:(Provider)provider withType:(SocialActionType)socialActionType withPayload:(NSString *)payload;

/**
 Called when the get feed process from a provider has finished. Which fires the
 `EVENT_UP_GET_FEED_FINISHED` event.

 @param provider The provider on which the get feed process finished
 @param socialActionType The social action which is preformed
 @param feeds an Array of feed entries represented by `NSString`
 */
+ (void)postGetFeedFinished:(Provider)provider withType:(SocialActionType)socialActionType withContacts:(NSArray *)feeds withPayload:(NSString *)payload;

/**
 Called when the get feed process from a provider has failed. Which fires the
 `EVENT_UP_GET_FEED_FAILED` event.

 @param provider The provider on which the get feed process has
 failed
 @param socialActionType The social action which is preformed
 @param message a Description of the reason for failure
 */
+ (void)postGetFeedFailed:(Provider)provider withType:(SocialActionType)socialActionType withMessage:(NSString *)message withPayload:(NSString *)payload;

@end


text:
/* Notes
 *
 * You can omit the `_` prefix and the `.css` extension:
 *
 *         @import "./filename";
 *
 * It also support glob imports:
 *
 *         @import "./dir/<**>/<*>.css";
 *
 * Import from node modules:
 *
 *         @import "package-name";
 *         @import "package-name/dir/filename";
 *         @import "package-name/dir/<**>/<*>.css";
 */

/* Skin-in-Template */
@import "./skin-in-template/**/*.css";


text:
module ApplicationHelper

# Returns the full title on a per-page basis.
  def full_title(page_title)
    base_title = "Address Book App"
    if page_title.empty?
      base_title
    else
      "#{base_title} | #{page_title}"
    end
  end

	def flash_class(level)
  		case level
  			when :notice then 'info'
  			when :error then 'error'
  			when :alert then 'warning'
  		end
  	end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/bg_main_sample_item_ripple">
    <item>
        <selector android:exitFadeDuration="@android:integer/config_mediumAnimTime">
            <item
                android:drawable="@color/bg_main_sample_item_pressed"
                android:state_pressed="true" />
            <item
                android:drawable="@color/bg_main_sample_item_focused"
                android:state_focused="true" />
            <item android:drawable="@color/bg_main_sample_item_normal" />
        </selector>
    </item>
</ripple>


text:
package base

import "errors"

var (
	ErrExpectedByteSlice = errors.New("expected []byte as input")
)


text:
module.exports = function validCredentials(creds) {
	'use strict';
	const credsRegex = /^arn:aws[^:]*:(iam|sts):[^:]*:(\*|\d{12})?:/;
	return creds === true || ((typeof creds === 'string') && credsRegex.test(creds));
};


text:
var serverService = appRequire('services/server.js');
var resultCode = appRequire('constants/result.js');

module.exports.index = function(req, res) {
    var params = {};
    var message = req.flash('message');
    if (message.length > 0) {
        params.message = message[0];
    }
    params.servers = serverService.getServers();
    if (Object.keys(params.servers).length === 0) {
        params.servers = null;
    }
    res.render('servers.html', params);
}

module.exports.doAdd = function(req, res) {
    var result = serverService.addServer(req.body.name, req.body.url);
    var message = {
        success: false,
        content: ''
    }
    switch(result) {
        case resultCode.SUCCESS:
            message.content = 'New server has been added successfully';
            message.success = true;
            break;
        case resultCode.INVALID_VALUE:
            message.content = 'Could not add new server. Invalid input value';
            break;
        case resultCode.DUPLICATE:
            message.content = 'Could not add new server. URL already exists';
            break;
        default:
            message.content = 'Could not add new server.';
            break;
    }
    req.flash('message', message);
    res.redirect('/servers');
}

module.exports.doDelete = function(req, res) {
    var ids = req.body.id;
    if (ids.constructor !== Array) ids = [ids];
    var result = serverService.deleteServer(ids);
    var message = {
        success: false,
        content: ''
    }
    switch(result) {
        case resultCode.SUCCESS:
            message.content = 'Servers have been deleted successfully';
            message.success = true;
            break;
        case resultCode.INVALID_VALUE:
            message.content = 'Could not delete servers. Invalid input value';
            break;
        default:
            message.content = 'Could not delete servers.';
            break;
    }
    req.flash('message', message);
    res.redirect('/servers');
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/AWSDynamoDBUpdateTableInput.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/AWSDynamoDBUpdateTableInput</TokenIdentifier>
			<Abstract type="html">
Represents the input of an UpdateTable operation.

Required parameters: [TableName]</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<NodeRef refid="356"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSDynamoDBUpdateTableInput/setAttributeDefinitions:</TokenIdentifier>
			<Abstract type="html">
An array of attributes that describe the key schema for the table and indexes. If you are adding a new global secondary index to the table, AttributeDefinitions must include the key element(s) of the new index.
</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) NSArray<AWSDynamoDBAttributeDefinition*> *attributeDefinitions</Declaration>

			<Anchor>//api/name/attributeDefinitions</Anchor>
            <NodeRef refid="356"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSDynamoDBUpdateTableInput/attributeDefinitions</TokenIdentifier>
			<Abstract type="html">
An array of attributes that describe the key schema for the table and indexes. If you are adding a new global secondary index to the table, AttributeDefinitions must include the key element(s) of the new index.
</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) NSArray<AWSDynamoDBAttributeDefinition*> *attributeDefinitions</Declaration>

			<Anchor>//api/name/attributeDefinitions</Anchor>
            <NodeRef refid="356"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/AWSDynamoDBUpdateTableInput/attributeDefinitions</TokenIdentifier>
			<Abstract type="html">
An array of attributes that describe the key schema for the table and indexes. If you are adding a new global secondary index to the table, AttributeDefinitions must include the key element(s) of the new index.
</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) NSArray<AWSDynamoDBAttributeDefinition*> *attributeDefinitions</Declaration>

			<Anchor>//api/name/attributeDefinitions</Anchor>
            <NodeRef refid="356"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSDynamoDBUpdateTableInput/setGlobalSecondaryIndexUpdates:</TokenIdentifier>
			<Abstract type="html">
An array of one or more global secondary indexes for the table. For each index in the array, you can request one action:

Create - add a new global secondary index to the table.

Update - modify the provisioned throughput settings of an existing global secondary index.

Delete - remove a global secondary index from the table.

</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) NSArray<AWSDynamoDBGlobalSecondaryIndexUpdate*> *globalSecondaryIndexUpdates</Declaration>

			<Anchor>//api/name/globalSecondaryIndexUpdates</Anchor>
            <NodeRef refid="356"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSDynamoDBUpdateTableInput/globalSecondaryIndexUpdates</TokenIdentifier>
			<Abstract type="html">
An array of one or more global secondary indexes for the table. For each index in the array, you can request one action:

Create - add a new global secondary index to the table.

Update - modify the provisioned throughput settings of an existing global secondary index.

Delete - remove a global secondary index from the table.

</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) NSArray<AWSDynamoDBGlobalSecondaryIndexUpdate*> *globalSecondaryIndexUpdates</Declaration>

			<Anchor>//api/name/globalSecondaryIndexUpdates</Anchor>
            <NodeRef refid="356"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/AWSDynamoDBUpdateTableInput/globalSecondaryIndexUpdates</TokenIdentifier>
			<Abstract type="html">
An array of one or more global secondary indexes for the table. For each index in the array, you can request one action:

Create - add a new global secondary index to the table.

Update - modify the provisioned throughput settings of an existing global secondary index.

Delete - remove a global secondary index from the table.

</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) NSArray<AWSDynamoDBGlobalSecondaryIndexUpdate*> *globalSecondaryIndexUpdates</Declaration>

			<Anchor>//api/name/globalSecondaryIndexUpdates</Anchor>
            <NodeRef refid="356"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSDynamoDBUpdateTableInput/setProvisionedThroughput:</TokenIdentifier>
			<Abstract type="html">
Represents the provisioned throughput settings for a specified table or index. The settings can be modified using the UpdateTable operation.

For current minimum and maximum provisioned throughput values, see Limits in the Amazon DynamoDB Developer Guide.
</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) AWSDynamoDBProvisionedThroughput *provisionedThroughput</Declaration>

			<Anchor>//api/name/provisionedThroughput</Anchor>
            <NodeRef refid="356"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSDynamoDBUpdateTableInput/provisionedThroughput</TokenIdentifier>
			<Abstract type="html">
Represents the provisioned throughput settings for a specified table or index. The settings can be modified using the UpdateTable operation.

For current minimum and maximum provisioned throughput values, see Limits in the Amazon DynamoDB Developer Guide.
</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) AWSDynamoDBProvisionedThroughput *provisionedThroughput</Declaration>

			<Anchor>//api/name/provisionedThroughput</Anchor>
            <NodeRef refid="356"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/AWSDynamoDBUpdateTableInput/provisionedThroughput</TokenIdentifier>
			<Abstract type="html">
Represents the provisioned throughput settings for a specified table or index. The settings can be modified using the UpdateTable operation.

For current minimum and maximum provisioned throughput values, see Limits in the Amazon DynamoDB Developer Guide.
</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) AWSDynamoDBProvisionedThroughput *provisionedThroughput</Declaration>

			<Anchor>//api/name/provisionedThroughput</Anchor>
            <NodeRef refid="356"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSDynamoDBUpdateTableInput/setStreamSpecification:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) AWSDynamoDBStreamSpecification *streamSpecification</Declaration>

			<Anchor>//api/name/streamSpecification</Anchor>
            <NodeRef refid="356"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSDynamoDBUpdateTableInput/streamSpecification</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) AWSDynamoDBStreamSpecification *streamSpecification</Declaration>

			<Anchor>//api/name/streamSpecification</Anchor>
            <NodeRef refid="356"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/AWSDynamoDBUpdateTableInput/streamSpecification</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) AWSDynamoDBStreamSpecification *streamSpecification</Declaration>

			<Anchor>//api/name/streamSpecification</Anchor>
            <NodeRef refid="356"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSDynamoDBUpdateTableInput/setTableName:</TokenIdentifier>
			<Abstract type="html">
The name of the table to be updated.
</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) NSString *tableName</Declaration>

			<Anchor>//api/name/tableName</Anchor>
            <NodeRef refid="356"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSDynamoDBUpdateTableInput/tableName</TokenIdentifier>
			<Abstract type="html">
The name of the table to be updated.
</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) NSString *tableName</Declaration>

			<Anchor>//api/name/tableName</Anchor>
            <NodeRef refid="356"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/AWSDynamoDBUpdateTableInput/tableName</TokenIdentifier>
			<Abstract type="html">
The name of the table to be updated.
</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) NSString *tableName</Declaration>

			<Anchor>//api/name/tableName</Anchor>
            <NodeRef refid="356"/>
		</Token>

	</File>
</Tokens>


text:
title: PhoneGap/Cordova File System questions
date: 2014-06-23 20:12:00 Z
tags:
- PhoneGap Network
format: html
link: http://www.raymondcamden.com/2014/06/23/PhoneGapCordova-File-System-questions
type: post
author: Raymond Camden
status: publish
external: true
---

A large majority of the questions I get about PhoneGap and Cordova revolve around the file system API. It has had some pretty significant updates recently but still remains one of the most difficult ones to use. I've been putting off really digging deep into those questions because many times there are incredibly specific to a particular user's application. And - honestly - they typically don't lead themselves to the type of quick questions I can answer during the day.

So with that in mind, I thought it might be fruitful to ask my readers about the API and how I can help make things a bit clearer - for both you and me. What I'm thinking is - can we come up with a list of basic questions, a FAQ perhaps, for just this API. It can't be something too precise to one particular application, but something that can apply to multiple users.

As an example: How do I download an asset to my application? That's a simple question, but it brings up the question of where you would download the asset and how you would actually use it later.

Of course, the big issue is that this particular API is an evolving one. Anything I do today will be outdated next year. But as most of my blog posts on the API are already over a year old, this would at least be a bit more fresh. ;)

In order to organize this list, I'm going to start it in the blog entry. Use the comments to make suggestions, and as I see ones that I think make sense, I'll add them to the list. By the way, I know some of these are super trivial, but I figure it doesn't hurt to try to cover as much as possible.

File System FAQ

When does it make sense to use the file system (versus LocalStorage or WebSQL)?

How do I download an asset to my application?

How do I use a file stored in the file system (both binary and text-based files)?

How do I check to see if a file exists in a directory?

How do I check to see if a directory exists?

How do I make a subdirectory where the parent directory may not exist?


text:
title: Removing old linux kernels in Ubuntu.
date: 2013-12-09 00:00:00 Z
categories:
- Linux
tags:
- Ubuntu
layout: post
---

As I always forget how to remove the older kernel headers I am posting this here

{% highlight bash %}
sudo apt-get remove --purge $(dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d')
{% endhighlight %}

and a link back to the originating page


text:
package com.intel.analytics.bigdl.dllib.keras.layers

import com.intel.analytics.bigdl.dllib.nn.abstractnn.AbstractModule
import com.intel.analytics.bigdl.dllib.tensor.Tensor
import com.intel.analytics.bigdl.dllib.utils.Shape
import com.intel.analytics.bigdl.dllib.keras.Sequential
import com.intel.analytics.bigdl.dllib.keras.serializer.ModuleSerializationTest

class GlobalAveragePooling3DSpec extends KerasBaseSpec{

  "GlobalAveragePooling3D" should "be the same as Keras" in {
    val kerasCode =
      """
        |input_tensor = Input(shape=[3, 4, 5, 6])
        |input = np.random.random([2, 3, 4, 5, 6])
        |output_tensor = GlobalAveragePooling3D(dim_ordering="th")(input_tensor)
        |model = Model(input=input_tensor, output=output_tensor)
      """.stripMargin
    val seq = Sequential[Float]()
    val layer = GlobalAveragePooling3D[Float](inputShape = Shape(3, 4, 5, 6))
    seq.add(layer)
    seq.getOutputShape().toSingle().toArray should be (Array(-1, 3))
    checkOutputAndGrad(seq.asInstanceOf[AbstractModule[Tensor[Float], Tensor[Float], Float]],
      kerasCode)
  }

}

class GlobalAveragePooling3DSerialTest extends ModuleSerializationTest {
  override def test(): Unit = {
    val layer = GlobalAveragePooling3D[Float](inputShape = Shape(3, 4, 5, 6))
    layer.build(Shape(2, 3, 4, 5, 6))
    val input = Tensor[Float](2, 3, 4, 5, 6).rand()
    runSerializationTest(layer, input)
  }
}


text:
using System;
using System.Reflection;

[assembly: System.Reflection.AssemblyCompanyAttribute("Passanger.Tests.EndToEnd")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyDescriptionAttribute("Package Description")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("Passanger.Tests.EndToEnd")]
[assembly: System.Reflection.AssemblyTitleAttribute("Passanger.Tests.EndToEnd")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]

// Wygenerowane przez klasę WriteCodeFragment programu MSBuild.


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*
Source Code: mainWrapper.c

mainWrapper.c creates Composite Test Case Processes and waits for all processes to get over

Algorithm
o	Create PROCESS_COUNT processes.

Author: RameshG
*/

#include <palsuite.h>
#include "resulttime.h"

/* Test Input Variables */
unsigned int USE_PROCESS_COUNT = 0; //default
unsigned int WORKER_THREAD_MULTIPLIER_COUNT = 0; //default
unsigned int REPEAT_COUNT = 0; //default
unsigned int SLEEP_LENGTH = 0; //default
unsigned int RELATION_ID  = 0;//default
unsigned int THREAD_COUNT = 1; //There is only one suspender and resume thread for this test case

char *testCaseName;

struct applicationStatistics{
    DWORD        	operationTime;
    unsigned int 	relationId;
    unsigned int 	processCount;
    unsigned int 	threadCount;
    unsigned int 	repeatCount;
    char*        		buildNumber;

};

int GetParameters( int argc, char **argv)
{

	if( (argc != 5) || ((argc == 1) && !strcmp(argv[1],"/?"))
       || !strcmp(argv[1],"/h") || !strcmp(argv[1],"/H"))
    {
        printf("PAL -Composite Thread Suspension Test\n");
        printf("Usage:\n");
	 printf("\t[PROCESS_COUNT] Greater than or Equal to  1 \n");
	 printf("\t[WORKER_THREAD_MULTIPLIER_COUNT]  Greater than or Equal to 1 and Less than or Equal to %d \n", MAXIMUM_WAIT_OBJECTS);
        printf("\t[REPEAT_COUNT] Greater than or Equal to 1\n");
	 printf("\t[RELATION_ID  [greater than or Equal to 1]\n");
        return -1;
    }

 // Trace("Args 1 is [%s], Arg 2 is [%s], Arg 3 is [%s]\n", argv[1], argv[2], argv[3]);

    USE_PROCESS_COUNT = atoi(argv[1]);
    if( USE_PROCESS_COUNT < 0)
    {
        printf("\nPROCESS_COUNT to greater than or equal to 1\n");
        return -1;
    }

    WORKER_THREAD_MULTIPLIER_COUNT = atoi(argv[2]);
    if( WORKER_THREAD_MULTIPLIER_COUNT < 1 || WORKER_THREAD_MULTIPLIER_COUNT > 64)
    {
        printf("\nWORKER_THREAD_MULTIPLIER_COUNT to be greater than or equal to 1 or less than or equal to 64\n");
        return -1;
    }

    REPEAT_COUNT = atoi(argv[3]);
    if( REPEAT_COUNT < 1)
    {
        printf("\nREPEAT_COUNT to greater than or equal to 1\n");
        return -1;
    }

    RELATION_ID = atoi(argv[4]);
    if( RELATION_ID < 1)
    {
        printf("\nRELATION_ID to be greater than or equal to 1\n");
        return -1;
    }

    return 0;
}

 int __cdecl main(INT argc, CHAR **argv)
{
    unsigned int i = 0;
    HANDLE hProcess[MAXIMUM_WAIT_OBJECTS];
     DWORD processReturnCode = 0;
    int testReturnCode = PASS;
    STARTUPINFO si[MAXIMUM_WAIT_OBJECTS];
    PROCESS_INFORMATION pi[MAXIMUM_WAIT_OBJECTS];

    FILE *hFile;
    char fileName[MAX_PATH];
    struct applicationStatistics appStats;

    DWORD dwStart=0;

    char lpCommandLine[MAX_PATH] = "";

    char build[] ="0000.00";
    int returnCode = 0;

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return ( FAIL );
    }

   //Initialize Application Statistics Strucuture
   appStats.relationId=RELATION_ID;
   appStats.operationTime=0;
   appStats.buildNumber =  getBuildNumber();
   //appStats.buildNumber = build;
      appStats.processCount = 0;
   appStats.threadCount = 0;
   appStats.repeatCount = 0;

//Start Process Time Capture
dwStart = GetTickCount();

    if(GetParameters(argc, argv))
    {
        Fail("Error in obtaining the parameters\n");
    }

//Assign Correct Values to the Application Stats Structure
   appStats.relationId=RELATION_ID;
   appStats.processCount = USE_PROCESS_COUNT;
   appStats.threadCount = THREAD_COUNT ;
   appStats.repeatCount = REPEAT_COUNT;

   Trace("Relation ID: %d \n", RELATION_ID);
      Trace("USE_PROCESS_COUNT: %d \n", USE_PROCESS_COUNT);
   Trace("WORKER_THREAD_MULTIPLIER_COUNT: %d \n", WORKER_THREAD_MULTIPLIER_COUNT);
      Trace("REPEAT_COUNT: %d \n", REPEAT_COUNT);

_snprintf(fileName, MAX_PATH, "main_threadsuspension_%d_.txt",appStats.relationId);

 hFile = fopen(fileName, "w+");
if(hFile == NULL)
    {
        Fail("Error in opening file to write application results for Thread Suspension Test with error code %d \n", GetLastError() );
    }

    for( i = 0; i < USE_PROCESS_COUNT; i++ )
    {

        ZeroMemory( lpCommandLine, MAX_PATH );
        if ( _snprintf( lpCommandLine, MAX_PATH-1, "threadsuspension %d %d %d %d", i, WORKER_THREAD_MULTIPLIER_COUNT, REPEAT_COUNT, RELATION_ID) < 0 )
        {
            Trace ("Error: Insufficient commandline string length for for iteration [%d]\n",   i);
        }

        /* Zero the data structure space */
        ZeroMemory ( &pi[i], sizeof(pi[i]) );
        ZeroMemory ( &si[i], sizeof(si[i]) );

        /* Set the process flags and standard io handles */
        si[i].cb = sizeof(si[i]);

	//Printing the Command Line
	//Trace("Command Line \t %s \n", lpCommandLine);

        //Create Process
        if(!CreateProcess( NULL, /* lpApplicationName*/
                          lpCommandLine, /* lpCommandLine */
                          NULL, /* lpProcessAttributes  */
                          NULL, /* lpThreadAttributes */
                          TRUE, /* bInheritHandles */
                          0, /* dwCreationFlags, */
                          NULL, /* lpEnvironment  */
                          NULL, /* pCurrentDirectory  */
                          &si[i], /* lpStartupInfo  */
                          &pi[i] /* lpProcessInformation  */
                          ))
        {
            Fail("Process Not created for [%d] and GetLastError value is %d\n", i, GetLastError());

        }
        else
        {
            hProcess[i] = pi[i].hProcess;
            //Trace("Process created for [%d]\n", i);
        }

    }

    returnCode = WaitForMultipleObjects( USE_PROCESS_COUNT, hProcess, TRUE, INFINITE);
     if( WAIT_OBJECT_0 != returnCode )
    {
        Trace("Wait for Object(s) @ Main thread for %d processes returned %d, and GetLastError value is %d\n", USE_PROCESS_COUNT, returnCode, GetLastError());
        testReturnCode = FAIL;
    }

	for( i = 0; i < USE_PROCESS_COUNT; i++ )
    {
        /* check the exit code from the process */
        if( ! GetExitCodeProcess( pi[i].hProcess, &processReturnCode ) )
        {
            Trace( "GetExitCodeProcess call failed for iteration %d with error code %u\n",
                i, GetLastError() );

            testReturnCode = FAIL;
        }

        if(processReturnCode == FAIL)
        {
            Trace( "Process [%d] failed and returned FAIL\n", i);
            testReturnCode = FAIL;
        }

        if(!CloseHandle(pi[i].hThread))
        {
            Trace("Error:%d: CloseHandle failed for Process [%d] hThread\n", GetLastError(), i);
            testReturnCode = FAIL;
        }

        if(!CloseHandle(pi[i].hProcess) )
        {
            Trace("Error:%d: CloseHandle failed for Process [%d] hProcess\n", GetLastError(), i);
            testReturnCode = FAIL;
        }
    }

//Get the end time of the process
appStats.operationTime = GetTickCount() - dwStart;

if( testReturnCode == PASS)
    {
        Trace("Test Passed\n");
    }
    else
    {
        Trace("Test Failed\n");
    }

//Write Process Result Contents to File
if(hFile!= NULL)
    {
            fprintf(hFile, "%lu,%d,%d,%d,%d,%s\n", appStats.operationTime, appStats.relationId, appStats.processCount, appStats.threadCount, appStats.repeatCount, appStats.buildNumber);
    }

if (0!=fclose(hFile))
{
	Trace("Error:%d: fclose failed for file %s\n", GetLastError(), fileName);
}
    PAL_Terminate();

if( testReturnCode == PASS)
    {
        return PASS;
    }
    else
    {
        return FAIL;

    }

}


text:
Welcome to Dominoes on Exercism's Go Track.
If you need help running the tests or submitting your code, check out `HELP.md`.

## Instructions

Make a chain of dominoes.

Compute a way to order a given set of dominoes in such a way that they form a
correct domino chain (the dots on one half of a stone match the dots on the
neighboring half of an adjacent stone) and that dots on the halves of the
stones which don't have a neighbor (the first and last stone) match each other.

For example given the stones `[2|1]`, `[2|3]` and `[1|3]` you should compute something
like `[1|2] [2|3] [3|1]` or `[3|2] [2|1] [1|3]` or `[1|3] [3|2] [2|1]` etc, where the first and last numbers are the same.

For stones `[1|2]`, `[4|1]` and `[2|3]` the resulting chain is not valid: `[4|1] [1|2] [2|3]`'s first and last numbers are not the same. 4 != 3

Some test cases may use duplicate stones in a chain solution, assume that multiple Domino sets are being used.

Define a single Go func, MakeChain, which accepts a slice
of dominoes and attempts to construct a legal chain of dominoes.

MakeChain should have the following signature:

```
type Domino [2]int

func MakeChain(input []Domino) (chain []Domino, ok bool)
```

The 'ok' bool result indicates whether the given input domino list
could be arranged in a legal chain. An empty input list is considered legal,
and a single domino whose sides are the same is also considered legal.

The 'chain' result is a slice of zero or more dominoes
arranged in an order which shows the legal chain.
It is acceptable (and expected) that dominoes in 'input' may need
to be rotated so that each side matches their adjacent domino in the chain.
Dominoes at the beginning and the end of the chain must also match their outer side.

If the given input slice of dominoes cannot be arranged in a legal chain
MakeChain may return nil for the chain result, but must return false for the ok result.

Since there may be more than one legal chain arrangement for a given input list,
when ok is true, the test program will check the chain for validity only.

## Source

### Created by

- @leenipper

### Contributed to by

- @bitfield
- @ekingery
- @ferhatelmas
- @hilary
- @ilmanzo
- @sebito91
- @tleen
- @zeimusu


text:
package com.googlecode.kanbanik.builders

import org.bson.types.ObjectId
import com.googlecode.kanbanik.model.{User, Board, Workflowitem, Workflow}
import com.googlecode.kanbanik.dtos.{WorkflowitemDto, WorkflowDto}

class WorkflowitemBuilder extends BaseBuilder {

  def buildShallowEntity(dto: WorkflowitemDto, parentWorkflow: Option[Workflow], board: Option[Board]): Workflowitem = {
    new Workflowitem(
    {
      if (dto.id == null || !dto.id.isDefined) {
        Some(new ObjectId)
      } else {
        Some(new ObjectId(dto.id.get))
      }
    },
    dto.name,
    dto.wipLimit.getOrElse(0),
    dto.verticalSize.getOrElse(-1),
    dto.itemType,
    dto.version.getOrElse(0),
    // don't calculate it if not needed
    Workflow(),
    parentWorkflow
    )
  }

  def buildEntity(dto: WorkflowitemDto, parentWorkflow: Option[Workflow], board: Option[Board]): Workflowitem = {
    val shallow = buildShallowEntity(dto, parentWorkflow, board)
    if (dto.nestedWorkflow.isDefined) {
      shallow.copy(nestedWorkflow = workflowBuilder.buildEntity(dto.nestedWorkflow.get, board))
    } else {
      shallow
    }

  }

  def buildShallowDto(workflowitem: Workflowitem, parentWorkflow: Option[WorkflowDto], user: User): WorkflowitemDto =
    buildShallowDto(workflowitem, parentWorkflow, user, None)

  def buildShallowDto(workflowitem: Workflowitem, parentWorkflow: Option[WorkflowDto], user: User, boardId: Option[String]): WorkflowitemDto = {
    WorkflowitemDto(
      workflowitem.name,
      Some(workflowitem.id.get.toString),
      Some(workflowitem.wipLimit),
      workflowitem.itemType,
      Some(workflowitem.version),
      None,
      Some(parentWorkflow.getOrElse(workflowBuilder.buildShallowDto(workflowitem.parentWorkflow(user), parentBoard(parentWorkflow), user))),
      Some(workflowitem.verticalSize),
      boardId
    )
  }

  def buildDto(workflowitem: Workflowitem, parentWorkflow: Option[WorkflowDto], user: User): WorkflowitemDto =
    buildDto(workflowitem, parentWorkflow, user, None)

  def buildDto(workflowitem: Workflowitem, parentWorkflow: Option[WorkflowDto], user: User, boardId: Option[String]): WorkflowitemDto = {
    val dto = buildShallowDto(workflowitem, parentWorkflow, user, boardId)
    dto.copy(
      nestedWorkflow = Some(workflowBuilder.buildDto(workflowitem.nestedWorkflow, parentBoard(parentWorkflow), user)),
      parentWorkflow = Some(parentWorkflow.getOrElse(workflowBuilder.buildDto(workflowitem.parentWorkflow(user), parentBoard(parentWorkflow), user)))
    )
  }

  def parentBoard(parentWorkflow: Option[WorkflowDto]) = {
    if (!parentWorkflow.isDefined) {
      None
    } else {
      Some(parentWorkflow.get.board)
    }
  }

  def workflowBuilder = new WorkflowBuilder
}


text:
<?php

namespace Thruway\Authentication;

use Thruway\Event\MessageEvent;
use Thruway\Message\HelloMessage;
use Thruway\Message\WelcomeMessage;
use Thruway\Module\RealmModuleInterface;

/**
 * Class AnonymousAuthenticator
 * @package Thruway\Authentication
 */
class AnonymousAuthenticator implements RealmModuleInterface

{

    /**
     * Listen for Realm events
     * @return array
     */
    public function getSubscribedRealmEvents()
    {
        return ["HelloMessageEvent" => ["handleHelloMessageEvent", 0]];
    }

    /**
     * @param \Thruway\Event\MessageEvent $event
     */
    public function handleHelloMessageEvent(MessageEvent $event)
    {

        $session = $event->session;

        /** @var HelloMessage $msg */
        $msg = $event->message;

        if ($session->isAuthenticated()) {
            return;
        }

        $session->setAuthenticated(true);

        // still set admin on trusted transports
        $authDetails = AuthenticationDetails::createAnonymous();
        if ($session->getTransport() !== null && $session->getTransport()->isTrusted()) {
            $authDetails->addAuthRole('admin');
        }
        $session->setAuthenticationDetails($authDetails);

        $session->sendMessage(
          new WelcomeMessage($session->getSessionId(), $msg->getDetails())
        );

    }

}


text:
/**
 * Class used for determining the set of NSFetchRequest objects that
 * map to a given request URL.
 */
@protocol RKManagedObjectCache
@required

/**
 * Must return an array containing NSFetchRequests for use in retrieving locally
 * cached objects associated with a given request resourcePath.
 */
- (NSArray*)fetchRequestsForResourcePath:(NSString*)resourcePath;

@end


text:
require 'mathn' # also brings in matrix, rational and complex

# return a Hilbert matrix of given dimension
def hilbert(dimension)
  rows = Array.new
  (1..dimension).each do |i|
    row = Array.new
    (1..dimension).each do |j|
      row.push(1/(i + j - 1))
    end
    rows.push(row)
  end
  return(Matrix.rows(rows))
end


text:
CJacobianPseudoInverse::CJacobianPseudoInverse(
                                                    IN VectorXf & desired_position ,
                                                    IN CRobot   & robot
                                               ):
                                                    mtxinstance(CMatrixFactory::GetInstance()),
                                                    _desired_position(desired_position),
                                                    _robot(robot)

{
    current_position.resize(6);
}

OUT VectorXf CJacobianPseudoInverse::CalculateData()
{
    //Result vector
    VectorXf delta_theta(_robot.GiveMeMatrixHolder().size());
    //Vector for delta moving in space
    VectorXf delta_translation(6);

    VectorXf _temp = _desired_position;

    CJacobian * jac = CJacobian::GetInstance();
    //TODO
    //should be a parameter of function
    //Desired accuracy
    float epsilon = 0.1f;

    for (;;)
    {
        jac->CalculateJacobian(_robot.GiveMeMatrixHolder(),_robot.GiveMeJoints(),_robot.GiveMeFullHM());
        //calculation delta
        current_position << _robot.GiveMeFullHM()(0,3) ,    //X
                            _robot.GiveMeFullHM()(1,3) ,    //Y
                            _robot.GiveMeFullHM()(2,3) ,    //Z
                            0.0f,                           //Orientation
                            0.0f,                           //Orientation
                            0.0f;                           //Orientation

#ifdef JACOBIANDEBUGOUTPUT
        std::cout<<"Current position"<<std::endl<<current_position<<std::endl;
        std::cout<<"Desired position"<<std::endl<<_desired_position<<std::endl;
#endif

        delta_translation = _desired_position - current_position;

#ifdef JACOBIANDEBUGOUTPUT
        std::cout<<"Delta position"<<std::endl<<delta_translation<<std::endl;
#endif
        //compare delta with desired accuracy
        float n = delta_translation.norm();
        if (n < epsilon)
        {
            //Done
            break;
        }
        //Algo
        delta_theta = jac->PsevdoInverse() * delta_translation;

#ifdef JACOBIANDEBUGOUTPUT
        std::cout<<"Delta theta"<<std::endl<<delta_theta<<std::endl;
#endif
        UpdateJoints(delta_theta);
    }

    return _temp;
}

void CJacobianPseudoInverse::UpdateJoints( VectorXf & delta_theta )
{
    JointHandler & _j = _robot.GiveMeJoints();

    for (int i = 0 ; i < delta_theta.size() ; i++)
    {
        //TODO ADD CONSTRAINTS
        //new var = old var + delta var
        float res = delta_theta[i] + _j[i].GiveMeVariableParametr();
        _robot.SetJointVariable(i,res);
    }
}


text:
.. _array_serialization_wrap:

========================
array_serialization_wrap
========================

.. autofunction:: k3d.helpers.array_serialization_wrap

.. note::

  This function is used along with the `ipywidgets` package,
  which provides custom object serializations.

  See `ipywidgets documentation <https://ipywidgets.readthedocs.io/en/7.x/examples/Widget%20Low%20Level.html?highlight=to_json#Serialization-of-widget-attributes>`_ for more informations.

--------
Examples
--------

.. code-block:: python3

    # Example from objects.VoxelChunk

    coord = Array(dtype=np.uint32).tag(sync=True, **array_serialization_wrap("coord"))


text:
/**
 * Sample Servlet Package for Jenkins.
 */
package jp.gihyo.jenkinsbook;


text:
// Generated from /Users/samppa/Personal/javersion/javersion-path/src/main/antlr/PropertyPath.g4 by ANTLR 4.5.1
package org.javersion.path.parser;

import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.TerminalNode;

/**
 * This class provides an empty implementation of {@link PropertyPathListener},
 * which can be extended to create a listener which only needs to handle a subset
 * of the available methods.
 */
public class PropertyPathBaseListener implements PropertyPathListener {
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterParsePath(PropertyPathParser.ParsePathContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitParsePath(PropertyPathParser.ParsePathContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterParseProperty(PropertyPathParser.ParsePropertyContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitParseProperty(PropertyPathParser.ParsePropertyContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterIndexedOrAny(PropertyPathParser.IndexedOrAnyContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitIndexedOrAny(PropertyPathParser.IndexedOrAnyContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterProperty(PropertyPathParser.PropertyContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitProperty(PropertyPathParser.PropertyContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterIndex(PropertyPathParser.IndexContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitIndex(PropertyPathParser.IndexContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterKey(PropertyPathParser.KeyContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitKey(PropertyPathParser.KeyContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterAnyProperty(PropertyPathParser.AnyPropertyContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitAnyProperty(PropertyPathParser.AnyPropertyContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterAnyIndex(PropertyPathParser.AnyIndexContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitAnyIndex(PropertyPathParser.AnyIndexContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterAnyKey(PropertyPathParser.AnyKeyContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitAnyKey(PropertyPathParser.AnyKeyContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterAny(PropertyPathParser.AnyContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitAny(PropertyPathParser.AnyContext ctx) { }

	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void enterEveryRule(ParserRuleContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void exitEveryRule(ParserRuleContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void visitTerminal(TerminalNode node) { }
	/**
	 * {@inheritDoc}
	 *
	 *
The default implementation does nothing.

	 */
	@Override public void visitErrorNode(ErrorNode node) { }
}


text:
package tick

import (
	"sort"

	"github.com/influxdata/kapacitor/pipeline"
	"github.com/influxdata/kapacitor/tick/ast"
)

// SideloadNode converts the Sideload pipeline node into the TICKScript AST
type SideloadNode struct {
	Function
}

// NewSideload creates a Sideload function builder
func NewSideload(parents []ast.Node) *SideloadNode {
	return &SideloadNode{
		Function{
			Parents: parents,
		},
	}
}

// Build creates a Sideload ast.Node
func (n *SideloadNode) Build(d *pipeline.SideloadNode) (ast.Node, error) {
	n.Pipe("sideload")

	n.Dot("source", d.Source)
	order := make([]interface{}, len(d.OrderList))
	for i := range d.OrderList {
		order[i] = d.OrderList[i]
	}
	n.Dot("order", order...)

	var fieldKeys []string
	for k := range d.Fields {
		fieldKeys = append(fieldKeys, k)
	}
	sort.Strings(fieldKeys)
	for _, k := range fieldKeys {
		n.Dot("field", k, d.Fields[k])
	}

	var tagKeys []string
	for k := range d.Tags {
		tagKeys = append(tagKeys, k)
	}
	sort.Strings(tagKeys)
	for _, k := range tagKeys {
		n.Dot("tag", k, d.Tags[k])
	}
	return n.prev, n.err
}