text:
package rhttpc.akkapersistence.impl

import rhttpc.client.subscription.SubscriptionOnResponse

case class SubscriptionsStateStack private (stack: List[SubscriptionsState]) {
  import SubscriptionsStateStack._

  def withNextState(onAllRequestsPublishedForPrevState: Set[SubscriptionOnResponse] => Unit) = {
    val head :: tail = stack
    val newTail = head.withOnAllRequestsPublished(onAllRequestsPublishedForPrevState) match {
      case AllSubscriptionsConsumed =>
        tail
      case SomeSubscriptionsLeft(updated) =>
        updated :: tail
    }
    copy(stack = SubscriptionsState() :: newTail)
  }

  def withRegisteredPromise(sub: SubscriptionOnResponse): SubscriptionsStateStack = {
    val head :: tail = stack
    copy(stack = head.withRegisteredPromise(sub) :: tail)
  }

  def withPublishedRequestFor(sub: SubscriptionOnResponse): SubscriptionsStateStack =
    withCompletedSubscription(sub)(_.withPublishedRequestFor(sub))

  def withAbortedRequestFor(sub: SubscriptionOnResponse): SubscriptionsStateStack =
    withCompletedSubscription(sub)(_.withAbortedRequestFor(sub))

  def withConsumedSubscription(sub: SubscriptionOnResponse): SubscriptionsStateStack =
    copy(stack = consumeSubscriptionOnStack(stack)(sub, _.withConsumedSubscription(sub)))

  private def withCompletedSubscription(sub: SubscriptionOnResponse)
                                       (complete: SubscriptionsState => SubscriptionsState): SubscriptionsStateStack = {
    copy(stack = completeSubscriptionOnStack(stack)(sub, complete))
  }

}

object SubscriptionsStateStack {
  def apply(): SubscriptionsStateStack = SubscriptionsStateStack(List(SubscriptionsState()))

  private def completeSubscriptionOnStack(s: List[SubscriptionsState])
                                         (sub: SubscriptionOnResponse,
                                          complete: SubscriptionsState => SubscriptionsState): List[SubscriptionsState] = s match {
    case head :: tail if head.containsSubscription(sub) => complete(head) :: tail
    case head :: tail => head :: completeSubscriptionOnStack(tail)(sub, complete)
    case Nil => Nil
  }

  private def consumeSubscriptionOnStack(s: List[SubscriptionsState])
                                        (sub: SubscriptionOnResponse,
                                         consume: SubscriptionsState => SubscriptionConsumptionResult): List[SubscriptionsState] = s match {
    case head :: tail if head.containsSubscription(sub) =>
      consume(head) match {
        case AllSubscriptionsConsumed =>
          tail
        case SomeSubscriptionsLeft(updated) =>
          updated :: tail
      }
    case head :: tail => head :: consumeSubscriptionOnStack(tail)(sub, consume)
    case Nil => Nil
  }
}

case class SubscriptionsState private (private val subscriptions: Map[SubscriptionOnResponse, SubscriptionState], onAllRequestsPublished: Set[SubscriptionOnResponse] => Unit) {
  def containsSubscription(sub: SubscriptionOnResponse) = subscriptions.contains(sub)

  def withRegisteredPromise(sub: SubscriptionOnResponse): SubscriptionsState = copy(subscriptions = subscriptions + (sub -> SubscriptionPromisedState))

  def withOnAllRequestsPublished(newOnAllRequestsPublished: Set[SubscriptionOnResponse] => Unit): SubscriptionConsumptionResult = {
    if (subscriptions.isEmpty) {
      newOnAllRequestsPublished(Set.empty)
      AllSubscriptionsConsumed
    } else {
      copy(onAllRequestsPublished = newOnAllRequestsPublished).consumptionResult
    }
  }

  def withPublishedRequestFor(sub: SubscriptionOnResponse): SubscriptionsState =
    copy(subscriptions = subscriptions.updated(sub, RequestPublishedState)).completionResult

  def withAbortedRequestFor(sub: SubscriptionOnResponse): SubscriptionsState =
    copy(subscriptions = subscriptions - sub).completionResult

  private def completionResult: SubscriptionsState = {
    val published = subscriptions.filter {
      case (k, v) => v.isPublished
    }
    if (published.size == subscriptions.size) {
      onAllRequestsPublished(published.keys.toSet)
    }
    this
  }

  def withConsumedSubscription(sub: SubscriptionOnResponse): SubscriptionConsumptionResult =
    copy(subscriptions = subscriptions.updated(sub, SubscriptionConsumedState)).consumptionResult

  private def consumptionResult: SubscriptionConsumptionResult = {
    if (subscriptions.values.forall(_ == SubscriptionConsumedState)) {
      AllSubscriptionsConsumed
    } else {
      SomeSubscriptionsLeft(this)
    }
  }
}

sealed trait SubscriptionState {
  def isPublished: Boolean
}

case object SubscriptionPromisedState extends SubscriptionState {
  override def isPublished: Boolean = false
}
case object RequestPublishedState extends SubscriptionState {
  override def isPublished: Boolean = true
}
case object SubscriptionConsumedState extends SubscriptionState {
  override def isPublished: Boolean = true
}

sealed trait SubscriptionConsumptionResult

case object AllSubscriptionsConsumed extends SubscriptionConsumptionResult

case class SomeSubscriptionsLeft(updated: SubscriptionsState) extends SubscriptionConsumptionResult

object SubscriptionsState {
  def apply(): SubscriptionsState =
    new SubscriptionsState(Map.empty, _ => throw new IllegalStateException("Callback should be executed after withNextState"))

  def apply(onAllRequestsPublished: Set[SubscriptionOnResponse] => Unit): SubscriptionsState =
    new SubscriptionsState(Map.empty, onAllRequestsPublished)
}


text:
ACCEPTED

#### According to
World Register of Marine Species

#### Published in
Ukrainskii Bot. Zh. 40 (4): 82.

#### Original name
null

### Remarks
null

redpajama_set_name: RedPajamaGithub


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

import com.facebook.presto.Session;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.planner.DeterminismEvaluator;
import com.facebook.presto.sql.planner.ExpressionSymbolInliner;
import com.facebook.presto.sql.planner.PlanNodeIdAllocator;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.planner.SymbolAllocator;
import com.facebook.presto.sql.planner.plan.PlanNode;
import com.facebook.presto.sql.planner.plan.ProjectNode;
import com.facebook.presto.sql.planner.plan.SimplePlanRewriter;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.ExpressionTreeRewriter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import java.util.Map;

import static com.facebook.presto.sql.planner.plan.ChildReplacer.replaceChildren;
import static java.util.Objects.requireNonNull;

/**
 * Merges chains of consecutive projections
 */
public class MergeProjections
        extends PlanOptimizer
{
    @Override
    public PlanNode optimize(PlanNode plan, Session session, Map<Symbol, Type> types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator)
    {
        requireNonNull(plan, "plan is null");
        requireNonNull(session, "session is null");
        requireNonNull(types, "types is null");
        requireNonNull(symbolAllocator, "symbolAllocator is null");
        requireNonNull(idAllocator, "idAllocator is null");

        return SimplePlanRewriter.rewriteWith(new Rewriter(), plan);
    }

    private static class Rewriter
            extends SimplePlanRewriter<Void>
    {
        @Override
        public PlanNode visitProject(ProjectNode node, RewriteContext<Void> context)
        {
            PlanNode source = context.rewrite(node.getSource());

            // only merge if the source is completely deterministic
            // todo perform partial merge, pushing down expressions that have deterministic sources
            if (source instanceof ProjectNode && ((ProjectNode) source).getAssignments().values().stream().allMatch(DeterminismEvaluator::isDeterministic)) {
                ImmutableMap.Builder<Symbol, Expression> projections = ImmutableMap.builder();
                for (Map.Entry<Symbol, Expression> projection : node.getAssignments().entrySet()) {
                    Expression inlined = ExpressionTreeRewriter.rewriteWith(new ExpressionSymbolInliner(((ProjectNode) source).getAssignments()), projection.getValue());
                    projections.put(projection.getKey(), inlined);
                }

                return new ProjectNode(node.getId(), ((ProjectNode) source).getSource(), projections.build());
            }

            return replaceChildren(node, ImmutableList.of(source));
        }
    }
}


text:
modifier_teve_druid_shapeshifter_werewolf = class({})

function modifier_teve_druid_shapeshifter_werewolf:OnCreated(kv)
    if IsServer() then
        self:GetCaster():SetAttackCapability(DOTA_UNIT_CAP_MELEE_ATTACK)
    end
end

function modifier_teve_druid_shapeshifter_werewolf:OnDestroy(kv)
    if IsServer() then
        self:GetCaster():SetAttackCapability(DOTA_UNIT_CAP_RANGED_ATTACK)
    end
end

function modifier_teve_druid_shapeshifter_werewolf:DeclareFunctions()
    local funcs = {
        MODIFIER_PROPERTY_MODEL_CHANGE,
        MODIFIER_PROPERTY_MOVESPEED_BASE_OVERRIDE,
        MODIFIER_PROPERTY_STATS_STRENGTH_BONUS,
        MODIFIER_PROPERTY_STATS_AGILITY_BONUS,
        MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
        MODIFIER_PROPERTY_BASEATTACK_BONUSDAMAGE,
        MODIFIER_PROPERTY_ATTACK_RANGE_BONUS,
        MODIFIER_PROPERTY_BASE_ATTACK_TIME_CONSTANT,
        MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS
    }
    return funcs
end

function modifier_teve_druid_shapeshifter_werewolf:GetModifierModelChange()
    return "models/heroes/lycan/summon_wolves.vmdl"
end

function modifier_teve_druid_shapeshifter_werewolf:GetModifierMoveSpeedOverride(params)
    return 420
end

function modifier_teve_druid_shapeshifter_werewolf:GetModifierBonusStats_Strength(params)
    --Shapeshifter has 65, we want 80. therefore add 80-65
    return 80-65
end

function modifier_teve_druid_shapeshifter_werewolf:GetModifierBonusStats_Agility(params)
    --Shapeshifter has 65, we want 80. therefore add 80-65
    return 80-65
end

function modifier_teve_druid_shapeshifter_werewolf:GetModifierBonusStats_Intellect(params)
    --Shapeshifter has 80, we want 100. therefore add 100-80
    return 100-80
end

function modifier_teve_druid_shapeshifter_werewolf:GetModifierBaseAttack_BonusDamage(params)
    --Shapeshifter has 210 base damage, we want to end up with 950 "base" damage
    return 950-210
end

function modifier_teve_druid_shapeshifter_werewolf:GetModifierAttackRangeBonus(params)
    --Shapeshifter has 500 attack range, all our melee heroes have 100 range.
    return 100-500
end

function modifier_teve_druid_shapeshifter_werewolf:GetModifierBaseAttackTimeConstant(params)
    return 1.3
end

function modifier_teve_druid_shapeshifter_werewolf:GetModifierPhysicalArmorBonus(params)
    --Shapeshifter already has 3 armor, we want 25
    return 25-3
end


text:
using namespace std;
using namespace GPULogger;

static const std::string s_PART_NAME = HSA_PART_NAME;
static const std::string s_HSA_TRACE_OUTPUT = HSA_PART_NAME ATP_API_TRACE_OUTPUT;
static const std::string s_HSA_TIMESTAMP_OUTPUT = HSA_PART_NAME ATP_TIMESSTAMP_OUTPUT;
static const std::string s_HSA_KERNEL_TIMESTAMP_OUTPUT = HSA_PART_NAME ATP_KERNEL_TIMESTAMP_OUTPUT;

#define MAX_LINE_SIZE 2048

HSAAtpFilePart::HSAAtpFilePart(const Config& config, bool shouldReleaseMemory)
    : IAtpFilePart(config, shouldReleaseMemory), m_dispatchIndex(0)
{
    m_strPartName = s_PART_NAME;
    m_sections.push_back(s_HSA_TRACE_OUTPUT);
    m_sections.push_back(s_HSA_TIMESTAMP_OUTPUT);
    m_sections.push_back(s_HSA_KERNEL_TIMESTAMP_OUTPUT);

    // Add for before CodeXL 2.3
    m_sections.push_back(CODEXL_STR HSA_PART_NAME ATP_API_TRACE_OUTPUT);
    m_sections.push_back(CODEXL_STR HSA_PART_NAME ATP_TIMESSTAMP_OUTPUT);
    m_sections.push_back(CODEXL_STR HSA_PART_NAME ATP_KERNEL_TIMESTAMP_OUTPUT);
}

HSAAtpFilePart::~HSAAtpFilePart(void)
{
}

void HSAAtpFilePart::WriteHeaderSection(SP_fileStream& sout)
{
    std::set<std::string> excludedAPIs;
    ReadExcludedAPIs(m_config.strAPIFilterFile, excludedAPIs);
    WriteExcludedAPIs(sout, "HSA", excludedAPIs);
}

bool HSAAtpFilePart::WriteContentSection(SP_fileStream& sout, const std::string& strTmpFilePath, const std::string& strPID)
{
    bool ret = false;
    SpAssertRet(!m_sections.empty()) ret;

    if (m_config.bTimeOut || m_config.bMergeMode)
    {
        UpdateTmpTimestampFiles(strTmpFilePath, strPID);

        stringstream ss;
        ss << "." << m_strPartName << TMP_TRACE_EXT;
        ret = FileUtils::MergeTmpTraceFiles(sout, strTmpFilePath, strPID, ss.str().c_str(), GetSectionHeader(m_sections[0]).c_str());

        ss.str("");
        ss << "." << m_strPartName << TMP_TIME_STAMP_EXT;
        ret |= FileUtils::MergeTmpTraceFiles(sout, strTmpFilePath, strPID, ss.str().c_str(), GetSectionHeader(m_sections[1]).c_str());

        ss.str("");
        ss << "." << m_strPartName << TMP_KERNEL_TIME_STAMP_EXT;
        ret |= FileUtils::MergeTmpTraceFiles(sout, strTmpFilePath, strPID, ss.str().c_str(), GetSectionHeader(m_sections[2]).c_str(), FileUtils::MergeSummaryType_CumulativeNumEntries);
    }
    else
    {
        // read .$(ModName).atp and write to sout
        stringstream ss;

        std::string strExtension = FileUtils::GetFileExtension(m_config.strOutputFile);

        if (strExtension == TRACE_EXT || strExtension == OCCUPANCY_EXT || strExtension == PERF_COUNTER_EXT)
        {
            // strip .atp, .csv or .occupancy and append .$ModName.atp
            string strBaseFileName = FileUtils::GetBaseFileName(m_config.strOutputFile);
            ss << strBaseFileName << "." << m_strPartName << "." << TRACE_EXT;
        }
        else
        {
            // append $ModName.atp
            ss << m_config.strOutputFile << "." << m_strPartName << "." << TRACE_EXT;
        }

        string fileContent;
        ret = FileUtils::ReadFile(ss.str(), fileContent, false);
        sout << fileContent.c_str();
        remove(ss.str().c_str());
    }

    return ret;
}

HSAAPIInfo* HSAAtpFilePart::CreateAPIInfo(const std::string& strAPIName)
{
    HSAAPIInfo* retObj = nullptr;

    HSA_API_Type apiType = HSAFunctionDefsUtils::Instance()->ToHSAAPIType(strAPIName);

    if (apiType == HSA_API_Type_hsa_amd_memory_async_copy)
    {
        retObj = new(nothrow) HSAMemoryTransferAPIInfo();
    }
    else if (apiType == HSA_API_Type_hsa_amd_memory_async_copy_rect)
    {
        retObj = new(nothrow) HSAMemoryTransferRectAPIInfo();
    }
    else if (apiType == HSA_API_Type_hsa_memory_allocate || apiType == HSA_API_Type_hsa_memory_copy ||
             apiType == HSA_API_Type_hsa_memory_register || apiType == HSA_API_Type_hsa_memory_deregister ||
             apiType == HSA_API_Type_hsa_amd_memory_pool_allocate || apiType == HSA_API_Type_hsa_amd_memory_lock ||
             apiType == HSA_API_Type_hsa_amd_memory_fill || apiType == HSA_API_Type_hsa_amd_interop_map_buffer)
    {
        retObj = new(nothrow)HSAMemoryAPIInfo();
    }
    else
    {
        retObj = new(nothrow)HSAAPIInfo();
    }

    if (retObj)
    {
        retObj->m_strName = strAPIName;
    }

    return retObj;
}

// TODO:Should this live in HSAStringUtils or HSAAtpFileParser?
bool ParseWorkgroup(istream& str, string& raw, size_t& dim, size_t& x, size_t& y, size_t& z)
{
    string tmp;
    str >> tmp;
    raw = tmp;

    if (tmp.size() < 3)
    {
        // smallest workgroup string: {1}
        return false;
    }

    // remove tailing and leading bracket
    tmp = tmp.substr(1);
    tmp = tmp.substr(0, tmp.size() - 1);

    // extract numbers;
    vector<string> nums;
    StringUtils::Split(nums, tmp, string(","));
    SpAssertRet(nums.size() > 0) false;

    dim = nums.size();

    switch (dim)
    {
        case 3:
            SpAssertRet(StringUtils::Parse(nums[2], z)) false;

        // fall through is intentional
        case 2:
            SpAssertRet(StringUtils::Parse(nums[1], y)) false;

        // fall through is intentional
        case 1:
            SpAssertRet(StringUtils::Parse(nums[0], x)) false;
            break;

        default:
            return false;
    }

    return true;
}

bool HSAAtpFilePart::ParseHostTimestamp(const char* buf, HSAAPIInfo* pAPIInfo, bool bTimeoutMode)
{
    SP_UNREFERENCED_PARAMETER(bTimeoutMode);

    stringstream ss(buf);
    int apiTypeID;
    string apiName;
    ULONGLONG ullStart;
    ULONGLONG ullEnd;

    ss >> apiTypeID;
    CHECK_SS_ERROR(ss)
    ss >> apiName;
    CHECK_SS_ERROR(ss)

    if (!pAPIInfo)
    {
        return false;
    }

    pAPIInfo->m_apiID = static_cast<HSA_API_Type>(apiTypeID);

    if (apiName != pAPIInfo->m_strName)
    {
        // unmatched num of API trace items and num of timestamp items
        // in this case, number of api could greater than number of timestamp item,
        // it's harder to recover from this problem.
        Log(logWARNING, "Unexpected data in input file. Inconsistent API trace item and timestamp item.\n");
        //m_strWarningMsg = "[Warning]Unexpected data in input file. Incomplete summary pages may be generated.";
        return false;
    }

    ss >> ullStart;
    CHECK_SS_ERROR(ss)
    ss >> ullEnd;
    CHECK_SS_ERROR(ss)

    pAPIInfo->m_ullStart = ullStart;
    pAPIInfo->m_ullEnd = ullEnd;

    if ((HSA_API_Type_hsa_amd_memory_async_copy == pAPIInfo->m_apiID ||
        HSA_API_Type_hsa_amd_memory_async_copy_rect == pAPIInfo->m_apiID) &&
        !ss.eof())
    {
        ULONGLONG ullAsyncCopyStart;
        ULONGLONG ullAsyncCopyEnd;

        ss >> ullAsyncCopyStart;
        CHECK_SS_ERROR(ss)
        ss >> ullAsyncCopyEnd;
        CHECK_SS_ERROR(ss)

        HSAMemoryTransferAPIInfo* pAsyncCopyApi = dynamic_cast<HSAMemoryTransferAPIInfo*>(pAPIInfo);

        pAsyncCopyApi->m_transferStartTime = ullAsyncCopyStart;
        pAsyncCopyApi->m_transferEndTime = ullAsyncCopyEnd;
    }

    return true;
}

bool HSAAtpFilePart::ParseDeviceTimestamp(const char* buf, HSADispatchInfo* pDispatchInfo)
{
    unsigned int curDispatchIndex = m_dispatchIndex;
    m_dispatchIndex++;

    SpAssertRet(NULL != pDispatchInfo) false;
    stringstream ss(buf);
    string strKernelName;
    ULONGLONG uiKernelHandle;
    string strDeviceName;
    string strDeviceHandle;
    unsigned int queueIndex = 0;
    string strQueueHandle;
    ULONGLONG ullStart;
    ULONGLONG ullEnd;

    ss >> strKernelName;
    strKernelName = StringUtils::Replace(strKernelName, std::string(SPACE), " ");
    strKernelName = StringUtils::Replace(strKernelName, std::string(COMMA), ",");
    CHECK_SS_ERROR(ss)
    ss >> std::hex >> uiKernelHandle >> std::dec;
    CHECK_SS_ERROR(ss)

    ss >> ullStart;
    CHECK_SS_ERROR(ss)
    ss >> ullEnd;
    CHECK_SS_ERROR(ss)

    ss >> strDeviceName;
    CHECK_SS_ERROR(ss)

    ss >> strDeviceHandle;
    CHECK_SS_ERROR(ss)

    // ATP files prior to 3.2 did not contain the queueIndex
    if (m_atpMajorVer > 3 || (m_atpMajorVer == 3 && m_atpMinorVer >= 2))
    {
        ss >> queueIndex;
        CHECK_SS_ERROR(ss)
    }

    ss >> strQueueHandle;
    CHECK_SS_ERROR(ss)

    pDispatchInfo->m_strKernelName = strKernelName;
    pDispatchInfo->m_uiKernelHandle = uiKernelHandle;
    pDispatchInfo->m_ullStart = ullStart;
    pDispatchInfo->m_ullEnd = ullEnd;
    pDispatchInfo->m_strDeviceName = strDeviceName;
    pDispatchInfo->m_strDeviceHandle = strDeviceHandle;
    pDispatchInfo->m_queueIndex = queueIndex;
    pDispatchInfo->m_strQueueHandle = strQueueHandle;
    pDispatchInfo->m_uiSeqID = curDispatchIndex;

    return true;
}

bool HSAAtpFilePart::Parse(std::istream& in, std::string& outErrorMsg)
{
    // Assumption: 1) HSA API trace section first then HSA timestamp + HSA kernel timestamp OR 2) just HSA kernel timestamp
    bool bError = false;
    bool bTSStart = false;
    bool bKTSStart = false;
    std::string strProgressMessage = "Parsing HSA Trace Data...";
    ErrorMessageUpdater errorMessageUpdater(outErrorMsg, this);

    if (s_HSA_KERNEL_TIMESTAMP_OUTPUT == m_strCurrentSectionName)
    {
        // if the .atp file has only the kernel timestamp section, then we will start on the s_HSA_KERNEL_TIMESTAMP_OUTPUT section
        bTSStart = true;
        bKTSStart = true;
    }

    do
    {
        string line;

        if (m_shouldStopParsing)
        {
            // proceed to the next section and continue parsing there
            line.clear();

            while (line[0] != '=')
            {
                READLINE(line)
            }

            if (line.length() == 0)
            {
                continue;
            }

            if (line[0] == '=')
            {
                m_shouldStopParsing = false;
                RewindToPreviousPos(in);
            }
        }

        READLINE(line)

        if (line.length() == 0)
        {
            continue;
        }

        if (line[0] == '=')
        {
            if (!bTSStart)
            {
                bTSStart = true;
                strProgressMessage = "Parsing HSA Timeline Data...";
                // read thread id
                ReadLine(in, line);
            }
            else
            {
                size_t sectionNameStart = line.find_first_not_of('=');
                std::string atpSectionHeaderStartEndString = ATP_SECTION_HEADER_START_END;
                string sectionName = line.substr(sectionNameStart, line.size() - (2 * atpSectionHeaderStartEndString.size()));

                if (!bKTSStart && std::find(m_sections.begin(), m_sections.end(), sectionName) != m_sections.end())
                {
                    bKTSStart = true;
                    strProgressMessage = "Parsing HSA Kernel Timestamp Data...";
                    // read api count
                    ReadLine(in, line);

                    if (line[0] == '=') // encountered a new section (meaning there were no kernel timestamps)
                    {
                        // rewind to previous position so the other parsers have a crack at this section
                        RewindToPreviousPos(in);
                        return true;
                    }
                }
                else
                {
                    // finished reading HSA trace sections
                    RewindToPreviousPos(in);
                    return true;
                }
            }
        }

        //else it's thread id
        osThreadId tid = 0;
        bool ret = false;

        if (!bKTSStart)
        {
            ret = StringUtils::Parse(line, tid);

            if (!ret)
            {
                Log(logERROR, "Failed to parse thread ID, Unexpected data in input file.\n");
                return false;
            }

            READLINE(line)
        }

        unsigned int apiNum = 0;

        if (!line.empty())
        {
            ret = StringUtils::Parse(line, apiNum);

            if (!ret)
            {
                Log(logERROR, "Failed to parse thread number, Unexpected data in input file.\n");
                return false;
            }
        }

        int apiIndex = -1;

        if (!bKTSStart)
        {
            for (std::vector<IParserListener<HSAAPIInfo>*>::iterator it = m_listenerList.begin(); it != m_listenerList.end(); ++it)
            {
                if (nullptr != (*it))
                {
                    (*it)->SetAPINum(tid, apiNum);
                }
            }
        }

        // read all apis for this thread
        for (unsigned int i = 0; i < apiNum && !m_shouldStopParsing; i++)
        {
            apiIndex++;
            READLINE(line)

            ReportProgress(strProgressMessage, i, apiNum);

            if (!bTSStart)
            {
                // api trace
                string apiTraceStr = line;

                if (apiTraceStr.empty())
                {
                    continue;
                }

                // First find the API name (required for the API info object allocation)
                size_t equalSignPos = apiTraceStr.find_first_of("=");
                size_t openParenPos = apiTraceStr.find_first_of("(");

                if (openParenPos != string::npos)
                {
                    size_t nameStartIndex = 0;

                    // In HSA, not all APIs have a return value -- those with no return value do not have an equal sign before the API name
                    if (equalSignPos == string::npos || equalSignPos > openParenPos)
                    {
                        equalSignPos = 0;
                    }
                    else
                    {
                        // If there is an equal sign, increment the start index (we expect a space before the name starts)
                        nameStartIndex = equalSignPos + 2;
                    }

                    // Back up from the opening parentheses, this is where the name actually ends
                    size_t nameEndIndex = openParenPos - 1;

                    // Get the name
                    size_t nameLength = nameEndIndex - nameStartIndex;

                    if ((nameStartIndex < apiTraceStr.size()) && (nameStartIndex + nameLength <= apiTraceStr.size()))
                    {
                        string name = apiTraceStr.substr(nameStartIndex, nameEndIndex - nameStartIndex);

                        // Create the HSA API info object
                        HSAAPIInfo* pAPIInfo = CreateAPIInfo(name);

                        // Parse the return value
                        if (0 != equalSignPos)
                        {
                            pAPIInfo->m_strRet = apiTraceStr.substr(0, equalSignPos - 1);
                        }
                        else
                        {
                            pAPIInfo->m_strRet.clear();
                        }

                        // Parse the arg list
                        size_t argListEndIndex = apiTraceStr.find_last_of(")");

                        if (argListEndIndex != string::npos)
                        {
                            size_t argListLength = argListEndIndex - openParenPos;

                            if (nameEndIndex + argListLength < apiTraceStr.size())
                            {
                                pAPIInfo->m_argList = StringUtils::Trim(apiTraceStr.substr(nameEndIndex + 2, argListLength - 2));
                                pAPIInfo->ParseArgList();
                            }
                        }
                        else
                        {
                            Log(logERROR, "Failed to parse API trace (%s), Unexpected data in input file.\n", line.c_str());
                            return false;
                        }

                        pAPIInfo->m_tid = tid;
                        pAPIInfo->m_uiSeqID = i;
                        pAPIInfo->m_bHasDisplayableSeqId = true;
                        pAPIInfo->m_uiDisplaySeqID = i;

                        m_HSAAPIInfoMap[tid].push_back(pAPIInfo);
                    }

                }
                else
                {
                    Log(logERROR, "Failed to parse API trace (%s), Unexpected data in input file.\n", line.c_str());
                    return false;
                }
            }
            else if (!bKTSStart)
            {
                // timestamp
                // find APIInfo object from InfoMap
                HSAAPIInfo* pAPIInfo = nullptr;
                std::vector<HSAAPIInfo*>& apiList = m_HSAAPIInfoMap[ tid ];

                if (apiList.size() <= i)
                {
                    // unmatched num of API trace items and num of timestamp items
                    // skip this timestamp
                    // This could happen in timeout mode
                    Log(logWARNING, "Unexpected data in input file. Inconsistent number of API trace items and timestamp items. Number of timestamp item is greater than number of api trace item.\n");
                    m_bWarning = true;
                    m_strWarningMsg = "[Warning]Unexpected data in input file. Incomplete summary pages may be generated.";
                    continue;
                }
                else
                {
                    pAPIInfo = apiList[i];

                    if (!ParseHostTimestamp(line.c_str(), pAPIInfo))
                    {
                        Log(logERROR, "Unexpected data in input file. Failed to parse timestamp entry.\n");
                        return false;
                    }
                }

                for (std::vector<IParserListener<HSAAPIInfo>*>::iterator it = m_listenerList.begin(); it != m_listenerList.end() && !m_shouldStopParsing; it++)
                {
                    if ((nullptr != (*it)) && (nullptr != pAPIInfo))
                    {
                        (*it)->OnParse(pAPIInfo, m_shouldStopParsing);
                    }
                    else
                    {
                        SpBreak("pAPIInfo == NULL");
                    }
                }
            }
            else
            {
                if (std::string::npos != line.find("HSA_PACKET_TYPE_"))
                {
                    if (std::string::npos == line.find("HSA_PACKET_TYPE_KERNEL_DISPATCH"))
                    {
                        // skip packet trace entry for non-dispatch packets
                        continue;
                    }

                }

                HSADispatchInfo* dispatchInfo = new(std::nothrow) HSADispatchInfo();

                if (nullptr == dispatchInfo)
                {
                    Log(logERROR, "Error: out of memory\n");
                    return false;
                }

                if (!ParseDeviceTimestamp(line.c_str(), dispatchInfo))
                {
                    Log(logERROR, "Error parsing device timestamp entry\n");
                    return false;
                }

                m_HSADispatchInfoList.push_back(dispatchInfo);

                for (std::vector<IParserListener<HSAAPIInfo>*>::iterator it = m_listenerList.begin(); it != m_listenerList.end() && !m_shouldStopParsing; it++)
                {
                    if (nullptr != (*it))
                    {
                        (*it)->OnParse(dispatchInfo, m_shouldStopParsing);
                    }
                }
            }
        }
    }
    while (!in.eof());

    return true;
}

bool HSAAtpFilePart::ParseHeader(const std::string& strKey, const std::string& strVal)
{
    if (0 == strKey.compare(FILE_HEADER_TRACE_FILE_VERSION))
    {
        StringUtils::ParseMajorMinorVersion(strVal, m_atpMajorVer, m_atpMinorVer);
    }

    return true;
}

bool HSAAtpFilePart::UpdateTmpTimestampFiles(const std::string& strTmpFilePath, const std::string& strFilePrefix)
{
    std::vector<std::string> files;

    if (!FileUtils::GetFilesUnderDir(strTmpFilePath, files, strFilePrefix))
    {
        return false;
    }
    else
    {
        std::string strAsyncCopyTSFile;
        std::stringstream ss;
        ss << '.' << m_strPartName;
        std::string strPartName = ss.str();
        ThreadCopyItemMap threadCopyTimestamps;

        // first locate the async copy timestamp file
        for (vector<string>::iterator it = files.begin(); it != files.end(); ++it)
        {
            size_t part_found = it->find(strPartName);

            if (part_found == string::npos)
            {
                Log(logMESSAGE, "Skipping file: %s. It does not contain: %s.\n", it->c_str(), strPartName.c_str());
                continue;
            }

            size_t found = it->find_last_of(".");

            if (found != string::npos)
            {
                std::string strExt = it->substr(found);

                if (strExt == TMP_ASYNC_COPY_TIME_STAMP_EXT)
                {
                    strAsyncCopyTSFile = strTmpFilePath + '/' + *it;

                    // once we find the async copy timestamp file, load the data into threadCopyTimestamps
                    if (!LoadAsyncCopyTimestamps(strAsyncCopyTSFile, threadCopyTimestamps))
                    {
                        continue;
                    }
                }
            }
            else
            {
                // wrong file name -- ignore this one
                Log(logMESSAGE, "Incorrect file name : %s.\n", it->c_str());
                continue;
            }
        }

        // now update the timestamp data for the has_amd_memory_async_copy to include the data transfer timing
        for (vector<string>::iterator it = files.begin(); it != files.end(); ++it)
        {
            size_t part_found = it->find(strPartName);

            if (part_found == string::npos)
            {
                Log(logMESSAGE, "Skipping file: %s. It does not contain: %s.\n", it->c_str(), strPartName.c_str());
                continue;
            }

            size_t found = it->find_last_of(".");

            if (found != string::npos)
            {
                std::string strExt = it->substr(found);

                if (strExt == TMP_TIME_STAMP_EXT)
                {
                    string strFullName = strTmpFilePath + '/' + *it;
                    if (!UpdateAsyncCopyTimestamps(strFullName, threadCopyTimestamps))
                    {
                        continue;
                    }
                }
            }
        }

        if (!strAsyncCopyTSFile.empty())
        {
            // delete async copy timestamp file.
            remove(strAsyncCopyTSFile.c_str());
        }

        return true;
    }
}

bool HSAAtpFilePart::LoadAsyncCopyTimestamps(const std::string& strFile, ThreadCopyItemMap& threadCopyItemMap)
{
    char buf[MAX_LINE_SIZE];
    ifstream fin(strFile.c_str());

    if (!fin.is_open())
    {
        return false;
    }

    threadCopyItemMap.clear();

    while (!fin.eof())
    {
        memset(buf, 0, MAX_LINE_SIZE * sizeof(char));
        fin.getline(buf, MAX_LINE_SIZE);
        std::istringstream ss(buf);

        // check empty line.
        if (ss.str().empty())
        {
            continue;
        }

        int threadId = 0;
        AsyncCopyItem asyncCopyItem;

        ss >> threadId;
        ss >> asyncCopyItem.m_strSignalHandle;
        ss >> asyncCopyItem.m_start;
        ss >> asyncCopyItem.m_end;
        ss >> asyncCopyItem.m_asyncCopyIdentifier;

        asyncCopyItem.m_apiIndex = 0;

        if (!ss.fail())
        {
            if (0 < threadCopyItemMap.count(threadId))
            {
                threadCopyItemMap[threadId].push_back(asyncCopyItem);
            }
            else
            {
                AsyncCopyItemList itemList;
                itemList.push_back(asyncCopyItem);
                threadCopyItemMap[threadId] = itemList;
            }
        }
        else
        {
            Log(logERROR, "Unable to parse async copy timestamp data\n");
        }
    }

    fin.close();

    return true;
}

bool HSAAtpFilePart::UpdateAsyncCopyTimestamps(const std::string strFile, ThreadCopyItemMap threadCopyInfoMap)
{
    osThreadId tid;
    bool correctTidFile = IsCorrectTidFile(strFile, threadCopyInfoMap, tid);

    if (!correctTidFile)
    {
        return false;
    }

    AsyncCopyItemList itemList = threadCopyInfoMap[tid];

    std::vector<std::string> fileLines;
    bool fileUpdated = false;

    if (FileUtils::ReadFile(strFile, fileLines, false))
    {
        std::unordered_map<uint64_t, uint32_t> asyncCopyIdentifierToIndexMap;

        for (uint32_t i = 0; i < fileLines.size(); ++i)
        {
            if (std::string::npos != fileLines[i].find("hsa_amd_memory_async_copy") ||
                std::string::npos != fileLines[i].find("hsa_amd_memory_async_copy_rect"))
            {
                std::stringstream ss;
                int apiType;
                std::string apiName;
                uint64_t ullStart;
                uint64_t ullEnd;
                uint64_t asyncCopyIdentifier;

                ss << fileLines[i];

                ss >> apiType;
                ss >> apiName;
                ss >> ullStart;
                ss >> ullEnd;
                ss >> asyncCopyIdentifier;

                asyncCopyIdentifierToIndexMap[asyncCopyIdentifier] = i;

                ss.str("");

                ss << std::left << std::setw(5) << apiType;
                ss << std::left << std::setw(45) << apiName;
                ss << std::left << std::setw(21) << ullStart;
                ss << std::left << std::setw(21) << ullEnd;

                fileLines[i] = ss.str();
            }
        }

        for (auto it = itemList.begin(); it != itemList.end(); ++it)
        {
            uint32_t apiIndex = 0;

            if (asyncCopyIdentifierToIndexMap.count(it->m_asyncCopyIdentifier) > 0)
            {
                apiIndex = asyncCopyIdentifierToIndexMap[it->m_asyncCopyIdentifier];
            }

            std::stringstream ss;
            ss << fileLines[apiIndex];
            ss << std::left << std::setw(21) << it->m_start;
            ss << std::left << std::setw(21) << it->m_end;

            fileLines[apiIndex] = ss.str();
            fileUpdated = true;
        }
    }

    if (fileUpdated)
    {
        remove(strFile.c_str());
        FileUtils::WriteFile(strFile, fileLines);
    }

    return true;
}

bool HSAAtpFilePart::IsCorrectTidFile(const std::string strFile, ThreadCopyItemMap threadCopyInfoMap, osThreadId& threadId)
{
    size_t tidStartPos = strFile.find_first_of("_");
    size_t tidEndPos = strFile.find_first_of(".");

    bool correctTidFile = false;

    if (string::npos != tidStartPos && string::npos != tidEndPos)
    {
        std::string tidString = strFile.substr(tidStartPos + 1, tidEndPos - 1);
        std::stringstream ss(tidString);
        ss >> threadId;

        if (!ss.fail())
        {
            correctTidFile = threadCopyInfoMap.count(threadId) > 0;
        }
    }

    if (!correctTidFile)
    {
        return false;
    }

    return true;
}


text:
<?php
namespace Anavel\Test;

use Anavel\Foundation\Support\ModuleProvider;
use Request;
use Schema;

class TestModuleProvider extends ModuleProvider
{

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    public function boot()
    {
        $this->loadViewsFrom(__DIR__.'/../views', 'anavel-test');
        $this->publishes([
            __DIR__.'/../config/anavel-test.php' => config_path('anavel-test.php'),
        ], 'config');

    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../config/anavel-test.php', 'anavel-test');
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [];
    }

    public function name()
    {
        return config('anavel-test.name');
    }

    public function routes()
    {
        return __DIR__.'/Http/routes.php';
    }

    public function mainRoute()
    {
        return route('anavel-test.home');
    }

    public function hasSidebar()
    {
        return false;
    }

    public function sidebarMenu()
    {
        return null;
    }

    public function isActive()
    {
        $uri = Request::route()->uri();

        if (strpos($uri, 'test') !== false) {
            return true;
        }

        return false;
    }

}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.http.filter.security.misc;

import com.yahoo.container.jdisc.RequestHandlerTestDriver;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
import com.yahoo.jdisc.http.filter.util.FilterTestUtils;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;

/**
 * @author mpolden
 * @author bjorncs
 */
public class LocalhostFilterTest {

    @Test
    void filter() {
        // Reject from non-loopback
        assertUnauthorized(createRequest("1.2.3.4", null));

        // Allow requests from loopback addresses
        assertSuccess(createRequest("127.0.0.1", null));
        assertSuccess(createRequest("127.127.0.1", null));
        assertSuccess(createRequest("0:0:0:0:0:0:0:1", null));

        // Allow requests originating from self
        assertSuccess(createRequest("1.3.3.7", "1.3.3.7"));
    }

    private static DiscFilterRequest createRequest(String remoteAddr, String localAddr) {
        return FilterTestUtils.newRequestBuilder()
                .withUri("http://%s:8080/".formatted(localAddr))
                .withRemoteAddress(remoteAddr, 12345)
                .build();
    }

    private static void assertUnauthorized(DiscFilterRequest request) {
        LocalhostFilter filter = new LocalhostFilter();
        RequestHandlerTestDriver.MockResponseHandler handler = new RequestHandlerTestDriver.MockResponseHandler();
        filter.filter(request, handler);
        assertEquals(Response.Status.UNAUTHORIZED, handler.getStatus());
    }

    private static void assertSuccess(DiscFilterRequest request) {
        LocalhostFilter filter = new LocalhostFilter();
        RequestHandlerTestDriver.MockResponseHandler handler = new RequestHandlerTestDriver.MockResponseHandler();
        filter.filter(request, handler);
        assertNull(handler.getResponse());
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="es.shyri.randomusers.MainActivity"
    android:orientation="vertical">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/editTextContactsAmount"
        android:layout_gravity="center_horizontal" />

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/button_insert_contacts"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="insert"
        android:layout_gravity="center_horizontal" />
</LinearLayout>


text:
{% extends "D4DAppBundle::backend.layout.twig.html" %}

{% block editor%}

{% endblock %}

{% block content %}

      {{ topTitle }}

      {{ topTitle }}

 /

{{ action }} {{ topTitle|replace({'es':'e'}) }}

                        {{ action }} {{ topTitle|replace({'es':'e'}) }}

                {{ form_start(form, {'attr': {'id': 'pages_form'}}) }}

                {{ form_errors(form.pagename) }}

                    {{ form_label(form.pagename) }}

                        {{ form_widget(form.pagename) }}

                {{ form_errors(form.pagetitle) }}

                    {{ form_label(form.pagetitle) }}

                        {{ form_widget(form.pagetitle) }}

                {{ form_errors(form.pagebody) }}

                    {{ form_label(form.pagebody) }}

                        {{ form_widget(form.pagebody) }}
                        {% if constants %}

                        {% endif %}

                {% if constants %}

Template Parameters:

                                {% for constant,description in constants %}

                                            {{ constant }}

{{ description|raw }}

                                {% endfor %}

                {% endif %}

{{ button }}

                <input style="display: none;" id="news_submit" type="submit" name="page({{ action }})" value="{{ action }}"/>
                {{ form_end(form) }}

{% endblock%}


text:
set -euo pipefail

# Load the test setup defined in the parent directory
CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${CURRENT_DIR}/../integration_test_setup.sh" \
  || { echo "integration_test_setup.sh not found!" >&2; exit 1; }
source "${CURRENT_DIR}/../sandboxing_test_utils.sh" \
  || { echo "sandboxing_test_utils.sh not found!" >&2; exit 1; }
source "${CURRENT_DIR}/execution_statistics_utils.sh" \
  || { echo "execution_statistics_utils.sh not found!" >&2; exit 1; }

enable_errexit

readonly OUT_DIR="${TEST_TMPDIR}/out"
readonly OUT="${OUT_DIR}/outfile"
readonly ERR="${OUT_DIR}/errfile"
readonly SANDBOX_DIR="${OUT_DIR}/sandbox"
readonly MOUNT_TARGET_ROOT="${TEST_TMPDIR}/targets"

readonly CPU_TIME_SPENDER="${CURRENT_DIR}/../../../test/shell/integration/spend_cpu_time"

SANDBOX_DEFAULT_OPTS="-W $SANDBOX_DIR"

function set_up {
  rm -rf $OUT_DIR
  mkdir -p $SANDBOX_DIR
}

function test_basic_functionality() {
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -- /bin/echo hi there &> $TEST_log || fail
  expect_log "hi there"
}

function test_execvp_error_message_contains_path() {
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -- /does/not/exist --hello world &> $TEST_log || code=$?
  expect_log "\"execvp(/does/not/exist, 0x[[:alnum:]]*)\": No such file or directory"
}

function test_default_user_is_current_user() {
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -- /usr/bin/id &> $TEST_log || fail
  local current_uid_number="$(id -u)"
  # Expecting something like: uid=485038(ruperts) ...
  expect_log "uid=${current_uid_number}("
}

function test_user_switched_to_root() {
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -R -- /usr/bin/id &> $TEST_log || fail
  expect_log "uid=0(root) gid=0(root) groups=0(root)"
}

function test_user_switched_to_nobody() {
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -U -- /usr/bin/id &> $TEST_log || fail
  expect_log "uid=[0-9]\+(nobody) gid=[0-9]\+(\(nobody\|nogroup\)) groups=[0-9]\+(\(nobody\|nogroup\))"
}

function test_exit_code() {
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -- /bin/bash -c "exit 71" &> $TEST_log || code=$?
  assert_equals 71 "$code"
}

function test_signal_death() {
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -- /bin/bash -c 'kill -ABRT $$' &> $TEST_log || code=$?
  assert_equals 134 "$code" # SIGNAL_BASE + SIGABRT = 128 + 6
}

# Tests that even when the child catches SIGTERM and exits with code 0, that the sandbox exits with
# code 142 (telling us about the expired timeout).
function test_signal_catcher() {
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -T 2 -t 3 -- /bin/bash -c \
    'trap "echo later; exit 0" SIGINT SIGTERM SIGALRM; sleep 1000' &> $TEST_log || code=$?
  assert_equals 142 "$code" # SIGNAL_BASE + SIGALRM = 128 + 14
  expect_log "^later$"
}

function test_basic_timeout() {
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -T 3 -t 3 -- /bin/bash -c "echo before; sleep 1000; echo after" &> $TEST_log && fail
  expect_log "^before$" ""
}

function test_timeout_grace() {
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -T 2 -t 3 -- /bin/bash -c \
    'trap "echo -n before; sleep 1; echo -n after; exit 0" SIGINT SIGTERM SIGALRM; sleep 1000' &> $TEST_log || code=$?
  assert_equals 142 "$code" # SIGNAL_BASE + SIGALRM = 128 + 14
  expect_log "^beforeafter$"
}

function test_timeout_kill() {
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -T 2 -t 3 -- /bin/bash -c \
    'trap "echo before; sleep 1000; echo after; exit 0" SIGINT SIGTERM SIGALRM; sleep 1000' &> $TEST_log || code=$?
  assert_equals 142 "$code" # SIGNAL_BASE + SIGALRM = 128 + 14
  expect_log "^before$"
}

function test_debug_logging() {
  touch ${TEST_TMPDIR}/testfile
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -D -- /bin/true &> $TEST_log || code=$?
  expect_log "child exited normally with exitcode 0"
}

function test_mount_additional_paths_success() {
  mkdir -p ${TEST_TMPDIR}/foo
  mkdir -p ${TEST_TMPDIR}/bar
  touch ${TEST_TMPDIR}/testfile
  mkdir -p ${MOUNT_TARGET_ROOT}/foo
  touch ${MOUNT_TARGET_ROOT}/sandboxed_testfile

  touch /tmp/sandboxed_testfile
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -D \
    -M ${TEST_TMPDIR}/foo -m ${MOUNT_TARGET_ROOT}/foo \
    -M ${TEST_TMPDIR}/bar \
    -M ${TEST_TMPDIR}/testfile -m ${MOUNT_TARGET_ROOT}/sandboxed_testfile \
    -- /bin/true &> $TEST_log || code=$?
  # mount a directory to a customized path inside the sandbox
  expect_log "bind mount: ${TEST_TMPDIR}/foo -> ${MOUNT_TARGET_ROOT}/foo\$"
  # mount a directory to the same path inside the sanxbox
  expect_log "bind mount: ${TEST_TMPDIR}/bar -> ${TEST_TMPDIR}/bar\$"
  # mount a file to a customized path inside the sandbox
  expect_log "bind mount: ${TEST_TMPDIR}/testfile -> ${MOUNT_TARGET_ROOT}/sandboxed_testfile\$"
  expect_log "child exited normally with exitcode 0"
  rm -rf ${MOUNT_TARGET_ROOT}/foo
  rm -rf ${MOUNT_TARGET_ROOT}/sandboxed_testfile
}

function test_mount_additional_paths_relative_path() {
  touch ${TEST_TMPDIR}/testfile
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -D \
    -M ${TEST_TMPDIR}/testfile -m tmp/sandboxed_testfile \
    -- /bin/true &> $TEST_log || code=$?
  # mount a directory to a customized path inside the sandbox
  expect_log "The -m option must be used with absolute paths only.\$"
}

function test_mount_additional_paths_leading_m() {
  mkdir -p ${TEST_TMPDIR}/foo
  touch ${TEST_TMPDIR}/testfile
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -D \
    -m /tmp/foo \
    -M ${TEST_TMPDIR}/testfile -m /tmp/sandboxed_testfile \
    -- /bin/true &> $TEST_log || code=$?
  # mount a directory to a customized path inside the sandbox
  expect_log "The -m option must be strictly preceded by an -M option.\$"
}

function test_mount_additional_paths_m_not_preceeded_by_M() {
  mkdir -p ${TEST_TMPDIR}/foo
  mkdir -p ${TEST_TMPDIR}/bar
  touch ${TEST_TMPDIR}/testfile
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -D \
    -M ${TEST_TMPDIR}/testfile -m /tmp/sandboxed_testfile \
    -m /tmp/foo \
    -M ${TEST_TMPDIR}/bar \
    -- /bin/true &> $TEST_log || code=$?
  # mount a directory to a customized path inside the sandbox
  expect_log "The -m option must be strictly preceded by an -M option.\$"
}

function test_mount_additional_paths_other_flag_between_M_m_pair() {
  mkdir -p ${TEST_TMPDIR}/bar
  touch ${TEST_TMPDIR}/testfile
  $linux_sandbox $SANDBOX_DEFAULT_OPTS \
    -M ${TEST_TMPDIR}/testfile -D -m /tmp/sandboxed_testfile \
    -M ${TEST_TMPDIR}/bar \
    -- /bin/true &> $TEST_log || code=$?
  # mount a directory to a customized path inside the sandbox
  expect_log "The -m option must be strictly preceded by an -M option.\$"
}

function test_mount_additional_paths_multiple_sources_mount_to_one_target() {
  mkdir -p ${TEST_TMPDIR}/foo
  mkdir -p ${TEST_TMPDIR}/bar
  mkdir -p ${MOUNT_TARGET_ROOT}/foo
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -D \
    -M ${TEST_TMPDIR}/foo -m ${MOUNT_TARGET_ROOT}/foo \
    -M ${TEST_TMPDIR}/bar -m ${MOUNT_TARGET_ROOT}/foo \
    -- /bin/true &> $TEST_log || code=$?
  # mount a directory to a customized path inside the sandbox
  expect_log "bind mount: ${TEST_TMPDIR}/foo -> ${MOUNT_TARGET_ROOT}/foo\$"
  # mount a new source directory to the same target, which will overwrite the previous source path
  expect_log "bind mount: ${TEST_TMPDIR}/bar -> ${MOUNT_TARGET_ROOT}/foo\$"
  expect_log "child exited normally with exitcode 0"
  rm -rf ${MOUNT_TARGET_ROOT}/foo
}

function test_redirect_output() {
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -l $OUT -L $ERR -- /bin/bash -c "echo out; echo err >&2" &> $TEST_log || code=$?
  assert_equals "out" "$(cat $OUT)"
  assert_equals "err" "$(cat $ERR)"
}

function test_tmp_is_writable() {
  # If /tmp is not writable on the host, it won't be inside the sandbox.
  test -w /tmp || return 0

  $linux_sandbox $SANDBOX_DEFAULT_OPTS -w /tmp -- /bin/bash -c "rm -f $(mktemp --tmpdir=/tmp)" \
    &> $TEST_log || fail
}

function test_dev_shm_is_writable() {
  # If /dev/shm is not writable on the host, it won't be inside the sandbox.
  test -w /dev/shm || return 0

  # /dev/shm is often a symlink to /run/shm, thus we use readlink to get the canonical path.
  $linux_sandbox $SANDBOX_DEFAULT_OPTS -w "$(readlink -f /dev/shm)" -- /bin/bash -c "rm -f $(mktemp --tmpdir=/dev/shm)" \
    &> $TEST_log || fail
}

function assert_linux_sandbox_exec_time() {
  local user_time_low="$1"; shift
  local user_time_high="$1"; shift
  local sys_time_low="$1"; shift
  local sys_time_high="$1"; shift

  local local_tmp="$(mktemp -d "${OUT_DIR}/assert_linux_sandbox_exec_timeXXXX")"
  local stdout_path="${local_tmp}/stdout"
  local stderr_path="${local_tmp}/stderr"
  local stats_out_path="${local_tmp}/statsfile"
  local stats_out_decoded_path="${local_tmp}/statsfile.decoded"

  cp "${CPU_TIME_SPENDER}" "${SANDBOX_DIR}"
  local cpu_time_spender_sandbox_path="${SANDBOX_DIR}/spend_cpu_time"

  # Sandboxed process will be terminated after 100 seconds if not already dead.
  local code=0
  "${linux_sandbox}" \
      -W "${SANDBOX_DIR}" \
      -T 100 \
      -t 2 \
      -l "${stdout_path}" \
      -L "${stderr_path}" \
      -S "${stats_out_path}" \
      -- \
      "${cpu_time_spender_sandbox_path}" "${user_time_low}" "${sys_time_low}" \
      &> "${TEST_log}" || code="$?"
  sed -e 's,^subprocess stdout: ,,' "${stdout_path}" >>"${TEST_log}"
  sed -e 's,^subprocess stderr: ,,' "${stderr_path}" >>"${TEST_log}"
  assert_equals 0 "${code}"

  assert_execution_time_in_range \
      "${user_time_low}" \
      "${user_time_high}" \
      "${sys_time_low}" \
      "${sys_time_high}" \
      "${stats_out_path}"
}

function test_stats_high_user_time() {
  assert_linux_sandbox_exec_time 10 19 0 9
}

function test_stats_high_system_time() {
  assert_linux_sandbox_exec_time 0 9 10 19
}

function test_stats_high_user_time_and_high_system_time() {
  assert_linux_sandbox_exec_time 10 19 10 19
}

# The test shouldn't fail if the environment doesn't support running it.
check_supported_platform || exit 0
check_sandbox_allowed || exit 0

run_suite "linux-sandbox"


text:
#pragma once

#include "CoreMinimal.h"
#include "InputCoreTypes.h"
#include "Templates/SubclassOf.h"
#include "Framework/Commands/InputChord.h"
#include "VoxelGraphShortcuts.generated.h"

class UVoxelNode;

USTRUCT()
struct FVoxelGraphEditorKeyBinding
{
	GENERATED_BODY()

	UPROPERTY(EditAnywhere, Category = "Voxel")
	bool bCtrlDown = false;

	UPROPERTY(EditAnywhere, Category = "Voxel")
	bool bAltDown = false;

	UPROPERTY(EditAnywhere, Category = "Voxel")
	bool bShiftDown = false;

	UPROPERTY(EditAnywhere, Category = "Voxel")
	FKey Key;

	UPROPERTY(EditAnywhere, Category = "Voxel")
	TSubclassOf<UVoxelNode> Class;

	FVoxelGraphEditorKeyBinding() = default;

	FVoxelGraphEditorKeyBinding(FKey Key, TSubclassOf<UVoxelNode> Class)
		: Key(Key)
		, Class(Class)
	{
	}

	inline bool IsSameAs(const FInputChord& Chord)
	{
		return bCtrlDown == Chord.bCtrl && bAltDown == Chord.bAlt && bShiftDown == Chord.bShift && Key == Chord.Key;
	}
};

UCLASS(Config = EditorKeyBindings)
class UVoxelGraphShortcuts : public UObject
{
	GENERATED_BODY()

public:
	UVoxelGraphShortcuts();

	UPROPERTY(Config, EditAnywhere, Category = "Voxel")
	TArray<FVoxelGraphEditorKeyBinding> Shortcuts;

	//~ Begin UObject Interface
#if WITH_EDITOR
	virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override;
#endif
};


text:
from django.http import JsonResponse
import math
import json

from ..models import Comment, Movie
from movies.utils import get_token_data

# @csrf_exempt # temporary decorator to remove csrf, just to test with postman
def comment(request):
    if request.method == 'POST':
        post_data = json.loads(request.body)
        movie_id = post_data['id']
        body = post_data['body']

        try:
            username = post_data['username']
        except KeyError:
            token = get_token_data(request)
            username = token['username']

        # get movie object
        m, created = Movie.objects.get_or_create(source_id = movie_id, defaults={'title': ''})
        # comment
        c = Comment(movie = m, username = username, body = body)
        try:
            c.save()
        except:
            return JsonResponse({
                'status': 'fail',
                'data': {
                    'message': 'Error while saving comment'
                }
            }, status=500)

        return JsonResponse({
            'status': 'success',
            'data': {
                'id': c.id
            }
        })
    elif request.method == 'DELETE':
        id = request.GET.get('id', '')
        username = request.GET.get('u', '')

        try:
            c = Comment.objects.get(id=id, username=username)
        except Comment.DoesNotExist:
            return JsonResponse({
                'status': 'fail',
                'data': {
                    'message': 'This comment does not exist'
                }
            }, status=500)

        try:
            c.delete()
        except:
            return JsonResponse({
                'status': 'fail',
                'data': {
                    'message': 'Error while deleting comment'
                }
            }, status=500)

        return JsonResponse({
            'status': 'success'
        })

def get_comments(request, movie_id):
    if request.method != 'GET':
        pass

    items_per_page = 7
    page = int(request.GET.get('p', 1))

    c = Comment.objects.filter(movie_id=movie_id).order_by('-date')
    total_pages = math.ceil(c.count() / items_per_page)

    page = page-1 if page <=total_pages or total_pages==0 else total_pages-1
    limits = {
        'from': items_per_page * page,
        'to': (items_per_page * page) + items_per_page
    }

    comments = c[limits['from']: limits['to']].values()

    return JsonResponse({
        'status': 'success',
        'data': {
            'comments': list(comments),
            'total_pages': total_pages,
            'current_page': page+1,
            'items_per_page': items_per_page
        }
    })

# not currently used
def update_comment(request, id):
    if request.method != 'POST':
        pass

    username = request.POST.get('username', '')
    body = request.POST.get('body', '')

    try:
        c = Comment.objects.get(id=id, username=username)
    except Comment.DoesNotExist:
        return JsonResponse({
            'status': 'fail',
            'data': {
                'message': 'This comment does not exist'
            }
        }, status=500)

    c.body = body
    try:
        c.save()
    except:
        return JsonResponse({
            'status': 'fail',
            'data': {
                'message': 'Error while updating comment'
            }
        })

    return JsonResponse({
        'status': 'success'
    })


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta name="application-name" content="Essential YouTube">
    <meta name="description" content="An experimental UI for YouTube.">
    <meta name="url" content="http://essentialyoutube.com/">

    <meta property="og:site_name" content="Essential YouTube">
    <meta property="og:description" content="">
    <meta property="og:url" content="http://essentialyoutube.com">
    <meta property="og:locale" content="en_US">

    <meta name="twitter:title" content="Essential YouTube">
    <meta name="twitter:description" content="An experimental UI for YouTube.">
    <meta name="twitter:url" content="http://essentialyoutube.com">
    <meta name="twitter:creator" content="@boramalper">

    <title>Essential YouTube</title>

    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.red-indigo.min.css">

    <link href="index.css" rel="stylesheet">

          Essential YouTube

            About

              <input class="mdl-textfield__input" type="text" id="search" oninput="search_onInput(this)" onkeydown="search_onKeydown(event)" onclick="search_onClick(this)">
              Search...

<input id="slider" class="mdl-slider mdl-js-slider" type="range" min="0" max="100" value="0" tabindex="0" onchange="slider_onChange(this)" onmouseup="slider_onMouseup(this)" onmousedown="slider_onMousedown(this)">

                <button id="play-pause" class="mdl-button mdl-js-button" onclick="playPause_onClick(this)">pause</button>
                <button class="mdl-button mdl-js-button" onclick="next_onClick()">skip_next</button>
                <button class="mdl-button mdl-js-button" onclick="volume_onClick(this)">volume_up</button>

              <button class="mdl-button mdl-js-button videoControl" onclick="close_onClick()" title="Exit the search">close</button>

Title

 remove_red_eye

                    Description...

repeat_one Repeat the video

                      <input type="checkbox" id="loopSwitch" class="mdl-switch__input">


text:
package com.mkl.websuites.itests.cmd;

import static org.assertj.core.api.Assertions.fail;

import com.mkl.websuites.command.BaseCommand;
import com.mkl.websuites.command.CommandDescriptor;

@CommandDescriptor(name = "failingCommand")
public class FailingCommand extends BaseCommand {

    @Override
    protected void runStandardCommand() {

        fail("I'm failing");
    }

}


text:
import {
    concept_nodesAttribute,
    concept_linksAttribute,
    concept_suggested_linksAttribute,
    modulesAttribute,
    definition_valuesAttribute,
} from '../../../models/db'

export interface extendedConceptNodeAttribute extends concept_nodesAttribute {
    key: string,
    depth: number,
    connexComponent: number,
    suggested: boolean,
}

export interface conceptLinksAttribute {
    key: number,
    target: any,
    source: any,
    connexComponent: number,
}

export interface conceptGraphNodeData extends concept_nodesAttribute {
    connexComponent: number,
    suggested: boolean,
}

export interface conceptGraphNode extends d3.HierarchyNode<extendedConceptNodeAttribute> {}

export interface conceptGraph {
    [index: number]: conceptGraphNode,
}

export interface appState {
    containers?: {
        [id: string]: containerState
    },
    conceptGraph: {
        nodes: extendedConceptNodeAttribute[],
        graph?: any,
        graphNodes: any,
        selectedRoot: any,
        selectedNode: any,
        displayedNode: any,
        displayedSlugs: string[],
    }
    dispatch?: any,
    toggled: boolean,
}

export interface containerState {
    loading: number,
    dispatch?: any,
    containerId: string,

    // The following props depend on the container.
    concepts?: concept[],
    testData?: any,
}

export interface concept {
    attributes: conceptAttributes,
    loadedTime: number,
}

interface conceptAttributes extends concept_nodesAttribute {
    modules?: module[],
}

export interface module extends modulesAttribute {
    data?: any,
}

export interface action {
    type: string,
    promise?: (dispatch: any, getState: any) => any,
    value?: any,
    container?: string,
}

export type columnSize = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
'1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '10' | '11' | '12' | '13' | '14' | '15' | '16'


text:
Mamute QA [![Build Status](https://secure.travis-ci.org/caelum/mamute.png)](http://travis-ci.org/caelum/mamute)
======

## Requirements

This project makes use of the following technologies to simplify setup:

* [Node.js](https://nodejs.org)
* [npm](https://www.npmjs.com)
* [Docker CE](https://docs.docker.com/install/)
* [Docker Compose](https://docs.docker.com/compose/install/)

## How to set up an instance of Mamute

First of all, you need to setup an MySQL database. The default database name is
`mamute_development`, the username is `root` and the password must be blank.

You may also use Docker Compose to run your MySQL database:

```
docker-compose -f docker-compose-it.yml up -d
```

This is useful for running the tests.

## To use Mamute

### Using docker-compose:

To start an instance of the latest Mamute release and its dependencies:

```
cd docker
docker-compose up --build
```

Then you can access Mamute on [http://localhost:80](http://localhost:80).

### Using a compiled war file:

1. Download the war of the latest version at http://www.mamute.org
2. Unpack it to a folder named `yourproject/mamute`
3. Run it by executing the bash script `mamute/run.sh`
4. If everything worked, you are free to customize `mamute` folder as you want to!

### Using git + maven:

1. Clone the repository from [github](https://github.com/caelum/mamute)
2. Install node and npm
3. Run `npm install`
5. Run `npm install -g grunt-cli`
6. Run `./scripts/mvn-package.sh`
7. Make a copy of `mamute/target/mamute-1.0.0-SNAPSHOT` to `yourproject/mamute`
8. Run it by executing the bash script `mamute/run.sh`
9. If everything worked, you are free to customize `mamute` folder as you want to!

## To contribute with mamute:

1. Fork the repository from [github](https://github.com/caelum/mamute)
2. Clone the fork
3. Install node and npm
4. Run `npm install`
5. Run `npm install -g grunt-cli`
6. Run `Main.java` to start mamute
7. Develop and do your pull request

## FAQ

* [How to setup an instance](http://meta.mamute.org/221-how-to-set-up-an-instance-of-mamute)

* [How can I boot Mamute in a production environment?](http://meta.mamute.org/231-how-can-i-boot-mamute-in-a-production-environment)

* [How can I configure ad banners in my site?](http://meta.mamute.org/241-how-can-i-configure-ad-banners-in-my-site)

* [How can I configure the system to activate/deactivate some feature?](http://meta.mamute.org/292-how-can-i-configure-the-system-to-activatedeactivate-some-feature)

* [How can I configure the system to allow/disallow the creation of tags by common users?](http://meta.mamute.org/251-how-can-i-configure-the-system-to-allowdisallow-the-creation-of-tags-by-common-users)

* [Is it possible to delete inappropriate questions?](http://meta.mamute.org/261-is-it-possible-to-delete-inappropriate-questions)

* [How can I update mamute in my project?](http://meta.mamute.org/271-how-can-i-update-mamute-in-my-project)

* [What are the basic CSS classes to customize Mamute?](http://meta.mamute.org/281-what-are-the-basic-css-classes-to-customize-mamute)

## Questions?

Send your questions to [mamute meta](http://meta.mamute.org).

Or to our mail-list: mamute-qa-dev@googlegroups.com

Mamute was developed by www.caelum.com.br and www.alura.com.br developers


text:
<?php

namespace LBSS\MyAngularApiBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use LBSS\MyAngularApiBundle\Entity\User;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

use FOS\RestBundle\Controller\Annotations as Rest;
/*use FOS\RestBundle\View\ViewHandler;
use FOS\RestBundle\View\View;
*/
use LBSS\MyAngularApiBundle\Form\UserType;

use Nelmio\ApiDocBundle\Annotation\ApiDoc;

class UserController extends Controller
{
    /**
     * @ApiDoc(
     *    description="Récupère la liste des Users",
     *    input={"class"=PlaceType::class, "name"=""},
     *    statusCodes = {
     *        201 = "Création avec succès",
     *        400 = "Formulaire invalide"
     *    },
     *    responseMap={
     *         201 = {"class"=Place::class},
     *         400 = { "class"=PlaceType::class, "fos_rest_form_errors"=true, "name" = ""}
     *    }

     * )
     *
     * @Rest\View()
     * @Rest\Get("/users")
     */
    public function getUsersAction(Request $request)
    {
    	$users = $this->getDoctrine()->getRepository('LBSSMyAngularApiBundle:User')->findAll();

        return $users;

    }

    /**
     * @ApiDoc(
     *    description="Récupère un User"
     * )
     *
     * @Rest\View()
     * @Rest\Get("/user/{id}")
     */
    public function getUserAction(User $user)
    {
    	$user = $this->getDoctrine()->getRepository('LBSSMyAngularApiBundle:User')->find($user);

         return $user;

    }

    /**
     * @Rest\View(statusCode=Response::HTTP_CREATED)
     * @Rest\Post("/users")
     */
    public function postUsersAction(Request $request)
    {
        $user = new User();
        $form = $this->createForm(UserType::class, $user);

        $form->submit($request->request->all());
        /*$user->setUsername($request->get('username'))
            ->setEmail($request->get('email'));*/
       /* $user->setUsername($userName)
            ->setEmail($email);*/

         if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();
            return $user;
        } else {
            return $form;
        }

    }

    /**
     * @Rest\View(statusCode=Response::HTTP_NO_CONTENT)
     * @Rest\Delete("/users/{id}")
     */
    public function removeUserAction(User $user)
    {
        $user = $this->getDoctrine()->getRepository('LBSSMyAngularApiBundle:User')->find($user);
        $em = $this->getDoctrine()->getManager();

        if ($place) {
            $em->remove($user);
            $em->flush();
        }

    }

    /**
     * @Rest\View()
     * @Rest\Put("/user/{id}")
     */
    public function putUserAction(Request $request)
    {
        $user = $this->getDoctrine()->getRepository('LBSSMyAngularApiBundle:User')
                ->find($request->get('id'));

        if (empty($user)) {
            return \FOS\RestBundle\View\View::create(['message' => 'User not found'], Response::HTTP_NOT_FOUND);
        }

        $form = $this->createForm(UserType::class, $user);

        $form->submit($request->request->all());

        if ($form->isValid()) {
            $em = $this->get('doctrine.orm.entity_manager');

            $em->flush();
            return $user;
        } else {
            return $form;
        }
    }

    /**
     * @Rest\View()
     * @Rest\Patch("/user/{id}")
     */
    public function patchPlaceAction(Request $request)
    {
        $user = $this->getDoctrine()->getRepository('LBSSMyAngularApiBundle:User')
                ->find($request->get('id'));

        if (empty($user)) {
            return \FOS\RestBundle\View\View::create(['message' => 'user not found !!!'], Response::HTTP_NOT_FOUND);
        }

        $form = $this->createForm(UserType::class, $user);

         // Le paramètre false dit à Symfony de garder les valeurs dans notre
         // entité si l'utilisateur n'en fournit pas une dans sa requête
        $form->submit($request->request->all(), false);

        if ($form->isValid()) {
            $em = $this->get('doctrine.orm.entity_manager');
            $em->flush();
            return $user;
        } else {
            return $form;
        }
    }

}


text:
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;

namespace Internal.Cryptography.Pal.AnyOS
{
    internal sealed partial class ManagedPkcsPal : PkcsPal
    {
        public override void AddCertsFromStoreForDecryption(X509Certificate2Collection certs)
        {
            certs.AddRange(PkcsHelpers.GetStoreCertificates(StoreName.My, StoreLocation.CurrentUser, openExistingOnly: false));

            try
            {
                // This store exists on macOS, but not Linux
                certs.AddRange(
                    PkcsHelpers.GetStoreCertificates(StoreName.My, StoreLocation.LocalMachine, openExistingOnly: false));
            }
            catch (CryptographicException)
            {
            }
        }

        public override byte[] GetSubjectKeyIdentifier(X509Certificate2 certificate)
        {
            Debug.Assert(certificate != null);

            X509Extension extension = certificate.Extensions[Oids.SubjectKeyIdentifier];

            if (extension == null)
            {
                // Construct the value from the public key info.
                extension = new X509SubjectKeyIdentifierExtension(
                    certificate.PublicKey,
                    X509SubjectKeyIdentifierHashAlgorithm.CapiSha1,
                    false);
            }

            // Certificates are DER encoded.
            AsnReader reader = new AsnReader(extension.RawData, AsnEncodingRules.DER);

            if (reader.TryReadPrimitiveOctetStringBytes(out ReadOnlyMemory<byte> contents))
            {
                reader.ThrowIfNotEmpty();
                return contents.ToArray();
            }

            // TryGetPrimitiveOctetStringBytes will have thrown if the next tag wasn't
            // Universal (primitive) OCTET STRING, since we're in DER mode.
            // So there's really no way we can get here.
            Debug.Fail($"TryGetPrimitiveOctetStringBytes returned false in DER mode");
            throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
        }

        public override T GetPrivateKeyForSigning<T>(X509Certificate2 certificate, bool silent)
        {
            return GetPrivateKey<T>(certificate);
        }

        public override T GetPrivateKeyForDecryption<T>(X509Certificate2 certificate, bool silent)
        {
            return GetPrivateKey<T>(certificate);
        }

        private T GetPrivateKey<T>(X509Certificate2 certificate) where T : AsymmetricAlgorithm
        {
            if (typeof(T) == typeof(RSA))
                return (T)(object)certificate.GetRSAPrivateKey();
            if (typeof(T) == typeof(ECDsa))
                return (T)(object)certificate.GetECDsaPrivateKey();
#if netcoreapp || netcoreapp30 || netstandard21
            if (typeof(T) == typeof(DSA))
                return (T)(object)certificate.GetDSAPrivateKey();
#endif

            Debug.Fail($"Unknown key type requested: {typeof(T).FullName}");
            return null;
        }

        private static SymmetricAlgorithm OpenAlgorithm(AlgorithmIdentifierAsn contentEncryptionAlgorithm)
        {
            SymmetricAlgorithm alg = OpenAlgorithm(contentEncryptionAlgorithm.Algorithm);

            if (alg is RC2)
            {
                if (contentEncryptionAlgorithm.Parameters == null)
                {
                    // Windows issues CRYPT_E_BAD_DECODE
                    throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
                }

                Rc2CbcParameters rc2Params = Rc2CbcParameters.Decode(
                    contentEncryptionAlgorithm.Parameters.Value,
                    AsnEncodingRules.BER);

                alg.KeySize = rc2Params.GetEffectiveKeyBits();
                alg.IV = rc2Params.Iv.ToArray();
            }
            else
            {
                if (contentEncryptionAlgorithm.Parameters == null)
                {
                    // Windows issues CRYPT_E_BAD_DECODE
                    throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
                }

                AsnReader reader = new AsnReader(contentEncryptionAlgorithm.Parameters.Value, AsnEncodingRules.BER);

                if (reader.TryReadPrimitiveOctetStringBytes(out ReadOnlyMemory<byte> primitiveBytes))
                {
                    alg.IV = primitiveBytes.ToArray();
                }
                else
                {
                    byte[] iv = new byte[alg.BlockSize / 8];

                    if (!reader.TryCopyOctetStringBytes(iv, out int bytesWritten) ||
                        bytesWritten != iv.Length)
                    {
                        throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
                    }

                    alg.IV = iv;
                }
            }

            return alg;
        }

        private static SymmetricAlgorithm OpenAlgorithm(AlgorithmIdentifier algorithmIdentifier)
        {
            SymmetricAlgorithm alg = OpenAlgorithm(algorithmIdentifier.Oid);

            if (alg is RC2)
            {
                if (algorithmIdentifier.KeyLength != 0)
                {
                    alg.KeySize = algorithmIdentifier.KeyLength;
                }
                else
                {
                    alg.KeySize = KeyLengths.Rc2_128Bit;
                }
            }

            return alg;
        }

        private static SymmetricAlgorithm OpenAlgorithm(Oid algorithmIdentifier)
        {
            Debug.Assert(algorithmIdentifier != null);

            SymmetricAlgorithm alg;

            switch (algorithmIdentifier.Value)
            {
                case Oids.Rc2Cbc:
#pragma warning disable CA5351
                    alg = RC2.Create();
#pragma warning restore CA5351
                    break;
                case Oids.DesCbc:
#pragma warning disable CA5351
                    alg = DES.Create();
#pragma warning restore CA5351
                    break;
                case Oids.TripleDesCbc:
#pragma warning disable CA5350
                    alg = TripleDES.Create();
#pragma warning restore CA5350
                    break;
                case Oids.Aes128Cbc:
                    alg = Aes.Create();
                    alg.KeySize = 128;
                    break;
                case Oids.Aes192Cbc:
                    alg = Aes.Create();
                    alg.KeySize = 192;
                    break;
                case Oids.Aes256Cbc:
                    alg = Aes.Create();
                    alg.KeySize = 256;
                    break;
                default:
                    throw new CryptographicException(SR.Cryptography_Cms_UnknownAlgorithm, algorithmIdentifier.Value);
            }

            // These are the defaults, but they're restated here for clarity.
            alg.Padding = PaddingMode.PKCS7;
            alg.Mode = CipherMode.CBC;
            return alg;
        }
    }
}


text:
//
//  ExampleApplicationAppDelegate.m
//  ExampleApplication
//
//  Created by Reid Simonton on 1/9/13.
//  Copyright 2013 __MyCompanyName__. All rights reserved.
//

#import "ExampleApplicationAppDelegate.h"
#import "NYTimesReviewSearchVC.h"
#import "YouTubeSearchTableVC.h"

@implementation ExampleApplicationAppDelegate

@synthesize window;
@synthesize tabBarController;

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Set the tab bar controller as the window's root view controller and display.
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
}

#pragma mark -
#pragma mark UITabBarControllerDelegate methods

/*
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
}
*/

/*
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed {
}
*/

- (void)applicationDidFinishLaunching:(UIApplication *)application {
	[window addSubview:[tabBarController view]];
	[window makeKeyAndVisible];
}

#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}

- (void)dealloc {
    [tabBarController release];
    [window release];
    [super dealloc];
}

@end


text:
import type { MessageParam } from '../../Message';
import { Message } from '../../Message';
import { MessageParamDefinition, MessageType } from '../../MessageDefinition';

@MessageType('WALLOPS')
export class WallopsMessage extends Message<WallopsMessage> {
	@MessageParamDefinition({
		trailing: true
	})
	content!: MessageParam;
}


text:
<?php

class HomeController extends BaseController
{

    /**
      |--------------------------------------------------------------------------
      | Default Home Controller
      |--------------------------------------------------------------------------
      |
      | You may wish to use controllers instead of, or in addition to, Closure
      | based routes. That's great! Here is an example controller method to
      | get you started. To route to this controller, just add the route:
      |
      |	Route::get('/', 'HomeController@showWelcome');
      |
     */
    public function showWelcome()
    {
        $in = Input::all();
        if ($in) {
            echo "<pre>";
            echo print_r($in);
            echo "</pre>";
            exit();
        } else
            return View::make('hello');
    }

    public function add()
    {
       $in = Input::all();
        if ($in) {
             return View::make('hello',['data'=>$in['Home']]);
        } else
            return View::make('hello');
    }

}


text:
import copy

from fabric.api import env
from fabric.api import run
from fabric.api import settings

from cloudferrylib.base.action import action
from cloudferrylib.os.actions import task_transfer
from cloudferrylib.utils import forward_agent
from cloudferrylib.utils import utils as utl

CLOUD = 'cloud'
BACKEND = 'backend'
CEPH = 'ceph'
ISCSI = 'iscsi'
COMPUTE = 'compute'
INSTANCES = 'instances'
INSTANCE_BODY = 'instance'
INSTANCE = 'instance'
DIFF = 'diff'
EPHEMERAL = 'ephemeral'
DIFF_OLD = 'diff_old'
EPHEMERAL_OLD = 'ephemeral_old'

PATH_DST = 'path_dst'
HOST_DST = 'host_dst'
PATH_SRC = 'path_src'
HOST_SRC = 'host_src'
BACKING_FILE_DST = 'backing_file_dst'

TEMP = 'temp'
FLAVORS = 'flavors'

SSH_CHUNKS = 'CopyFilesBetweenComputeHosts'

TRANSPORTER_MAP = {CEPH: {CEPH: 'SSHCephToCeph',
                          ISCSI: 'SSHCephToFile'},
                   ISCSI: {CEPH: 'SSHFileToCeph',
                           ISCSI: 'SSHFileToFile'}}

class TransportEphemeral(action.Action):
    # TODO constants

    def run(self, info=None, **kwargs):
        info = copy.deepcopy(info)
        # Init before run
        new_info = {
            utl.INSTANCES_TYPE: {
            }
        }

        # Get next one instance
        for instance_id, instance in info[utl.INSTANCES_TYPE].iteritems():
            is_ephemeral = instance[utl.INSTANCE_BODY]['is_ephemeral']
            one_instance = {
                utl.INSTANCES_TYPE: {
                    instance_id: instance
                }
            }
            if is_ephemeral:
                self.copy_ephemeral(self.src_cloud,
                                    self.dst_cloud,
                                    one_instance)
            new_info[utl.INSTANCES_TYPE].update(
                one_instance[utl.INSTANCES_TYPE])

        return {
            'info': new_info
        }

    @staticmethod
    def delete_remote_file_on_compute(path_file, host_cloud,
                                      host_instance):
        with settings(host_string=host_cloud,
                      connection_attempts=env.connection_attempts):
            with forward_agent(env.key_filename):
                run("ssh -oStrictHostKeyChecking=no %s  'rm -rf %s'" %
                    (host_instance, path_file))

    def copy_data_via_ssh(self, src_cloud, dst_cloud, info, body, resources,
                          types):
        dst_storage = dst_cloud.resources[resources]
        src_compute = src_cloud.resources[resources]
        src_backend = src_compute.config.compute.backend
        dst_backend = dst_storage.config.compute.backend
        ssh_driver = (SSH_CHUNKS
                      if self.cfg.migrate.direct_compute_transfer
                      else TRANSPORTER_MAP[src_backend][dst_backend])
        transporter = task_transfer.TaskTransfer(
            self.init,
            ssh_driver,
            resource_name=types,
            resource_root_name=body)
        transporter.run(info=info)

    def copy_ephemeral(self, src_cloud, dst_cloud, info):
        dst_storage = dst_cloud.resources[utl.COMPUTE_RESOURCE]
        src_compute = src_cloud.resources[utl.COMPUTE_RESOURCE]
        src_backend = src_compute.config.compute.backend
        dst_backend = dst_storage.config.compute.backend
        if (src_backend == CEPH) and (dst_backend == ISCSI):
            self.copy_ephemeral_ceph_to_iscsi(src_cloud, dst_cloud, info)
        elif (src_backend == ISCSI) and (dst_backend == CEPH):
            self.copy_ephemeral_iscsi_to_ceph(src_cloud, info)
        else:
            self.copy_data_via_ssh(src_cloud,
                                   dst_cloud,
                                   info,
                                   utl.EPHEMERAL_BODY,
                                   utl.COMPUTE_RESOURCE,
                                   utl.INSTANCES_TYPE)

    def copy_ephemeral_ceph_to_iscsi(self, src_cloud, dst_cloud, info):
        transporter = task_transfer.TaskTransfer(
            self.init,
            TRANSPORTER_MAP[ISCSI][ISCSI],
            resource_name=utl.INSTANCES_TYPE,
            resource_root_name=utl.EPHEMERAL_BODY)

        instances = info[utl.INSTANCES_TYPE]
        temp_src = src_cloud.cloud_config.cloud.temp
        host_dst = dst_cloud.getIpSsh()
        qemu_img_dst = dst_cloud.qemu_img
        qemu_img_src = src_cloud.qemu_img

        temp_path_src = temp_src + "/%s" + utl.DISK_EPHEM
        for inst_id, inst in instances.iteritems():

            path_src_id_temp = temp_path_src % inst_id
            host_compute_dst = inst[EPHEMERAL][HOST_DST]
            inst[EPHEMERAL][
                BACKING_FILE_DST] = qemu_img_dst.detect_backing_file(
                inst[EPHEMERAL][PATH_DST], host_compute_dst)
            self.delete_remote_file_on_compute(inst[EPHEMERAL][PATH_DST],
                                               host_dst,
                                               host_compute_dst)
            qemu_img_src.convert(
                utl.QCOW2,
                'rbd:%s' % inst[EPHEMERAL][PATH_SRC], path_src_id_temp)
            inst[EPHEMERAL][PATH_SRC] = path_src_id_temp

        transporter.run(info=info)

        for inst_id, inst in instances.iteritems():
            host_compute_dst = inst[EPHEMERAL][HOST_DST]
            qemu_img_dst.diff_rebase(inst[EPHEMERAL][BACKING_FILE_DST],
                                     inst[EPHEMERAL][PATH_DST],
                                     host_compute_dst)

    def copy_ephemeral_iscsi_to_ceph(self, src_cloud, info):
        instances = info[utl.INSTANCES_TYPE]
        qemu_img_src = src_cloud.qemu_img
        transporter = task_transfer.TaskTransfer(
            self.init,
            TRANSPORTER_MAP[ISCSI][CEPH],
            resource_name=utl.INSTANCES_TYPE,
            resource_root_name=utl.EPHEMERAL_BODY)

        for inst_id, inst in instances.iteritems():
            path_src = inst[EPHEMERAL][PATH_SRC]
            path_src_temp_raw = path_src + "." + utl.RAW

            host_src = inst[EPHEMERAL][HOST_SRC]
            qemu_img_src.convert(utl.RAW,
                                 path_src,
                                 path_src_temp_raw,
                                 host_src)
            inst[EPHEMERAL][PATH_SRC] = path_src_temp_raw

        transporter.run(info=info)