text:
/**
 * web-T::Framework Loader module
 * @author goshi
 */

webtFramework.inject({

    /**
     * loaders collection
     */
    __loaders : [],

    /**
     * universal UI  loader (strobber)
     * @param container
     * @param params
     * @returns {*}
     */
    loader : function(container, params){

        var id = this.__loaders.length;

        var self = this;

        var vids = [];

        $(container).each(function(){

            if ($(this).css('position') == 'static' || !$(this).css('position')){
                $(this).css('position', 'relative');
            }

            var vid = id+'-'+vids.length;
            vids.push(vid);

            var proto = '';
            $(this).append(proto);
            setTimeout(function(){$('#loader-'+vid).show(100);}, 100);

        });

        this.__loaders[id] = {

            __cid: id,
            __vids: vids,
            __cont: container,

            destroy: function(callback){

                var called = false;

                for (var i= 0,l=this.__vids.length; i<l; i++){
                    $('#loader-'+this.__vids[i]).hide(100, function(){
                        $(this).remove();
                        if (!called && typeof callback == 'function'){
                            callback();
                            called = true;
                        }
                    });
                }

                self.__loaders[this.__cid] = null;

            }

        };

        return this.__loaders[id];

    }

});


text:
<?php namespace Cviebrock\LaravelElasticsearch\Tests;

use Cviebrock\LaravelElasticsearch\Facade;
use Cviebrock\LaravelElasticsearch\ServiceProvider;
use Orchestra\Testbench\TestCase as Orchestra;

/**
 * Class TestCase
 *
 * @package Tests
 */
abstract class TestCase extends Orchestra
{

    /**
     * @inheritdoc
     */
    protected function getPackageProviders($app)
    {
        return [
            ServiceProvider::class,
        ];
    }

    /**
     * @inheritdoc
     */
    protected function getPackageAliases($app)
    {
        return [
            'Elasticsearch' => Facade::class,
        ];
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php namespace Braindump\Api\Controller;

require_once(__DIR__ . '/../lib/DatabaseFacade.php');

class BaseController {

    protected $ci;
    protected $renderer;

    // move to di container?
    protected $dbFacade;

    public function __construct(\Interop\Container\ContainerInterface $ci) {
        $this->ci = $ci;
        $this->renderer = $this->ci->get('renderer');

        $this->dbFacade = new \Braindump\Api\Lib\DatabaseFacade(
            \ORM::get_db(),
            (require( __DIR__ . '/../migrations/migration-config.php')));
    }

    function outputJson($data, $response) {
        // JSON_NUMERIC_CHECK is needed as PDO will return strings
        // as default (even if DB schema defines numeric types).
        // http://stackoverflow.com/questions/11128823/how-to-properly-format-pdo-results-numeric-results-returned-as-string
        return $response->withJson($data, null, JSON_PRETTY_PRINT | JSON_NUMERIC_CHECK);
    }

}


text:
from google.cloud import pubsublite_v1

async def sample_update_reservation():
    # Create a client
    client = pubsublite_v1.AdminServiceAsyncClient()

    # Initialize request argument(s)
    request = pubsublite_v1.UpdateReservationRequest(
    )

    # Make the request
    response = await client.update_reservation(request=request)

    # Handle the response
    print(response)

# [END pubsublite_v1_generated_AdminService_UpdateReservation_async]


text:
'use strict';

var adler32 = require('./adler32');

var TAG_END = /\/?>/;
var COMMENT_START = /^<\!\-\-/;

var ReactMarkupChecksum = {
  CHECKSUM_ATTR_NAME: 'data-react-checksum',

  /**
   * @param {string} markup Markup string
   * @return {string} Markup string with checksum attribute attached
   */
  addChecksumToMarkup: function (markup) {
    var checksum = adler32(markup);

    // Add checksum (handle both parent tags, comments and self-closing tags)
    if (COMMENT_START.test(markup)) {
      return markup;
    } else {
      return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&');
    }
  },

  /**
   * @param {string} markup to use
   * @param {DOMElement} element root React element
   * @returns {boolean} whether or not the markup is the same
   */
  canReuseMarkup: function (markup, element) {
    var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
    existingChecksum = existingChecksum && parseInt(existingChecksum, 10);
    var markupChecksum = adler32(markup);
    return markupChecksum === existingChecksum;
  }
};

module.exports = ReactMarkupChecksum;


text:
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

namespace AtcSimController.SiteReflection.SimConnector
{
    /// <summary>
    /// Utility class for working with the ATC-SIM User Interface
    /// </summary>
    [ExcludeFromCodeCoverage]
    sealed class UIHelper
    {
        /// <summary>
        /// Changes a DropDown selector by value
        /// </summary>
        /// <param name="driver">Current Web Driver</param>
        /// <param name="ddName">'name' value for the selector</param>
        /// <param name="ddValue">Target value</param>
        public static void ChangeDropDownByValue(ref IWebDriver driver, String ddName, String ddValue)
        {
            // Target element
            IWebElement targetElement = driver.FindElement(By.Name(ddName));
            // Create a select element
            SelectElement targetSelector = new SelectElement(targetElement);
            // Change to the value
            targetSelector.SelectByValue(ddValue);
        }

        /// <summary>
        /// Changes a Radio value
        /// </summary>
        /// <param name="driver">Current Web Driver</param>
        /// <param name="rdoName">'name' value for the radio selector</param>
        /// <param name="rdoValue">Target value</param>
        public static void ChangeRadioByValue(ref IWebDriver driver, String rdoName, String rdoValue)
        {
            // Get element for the option
            IList<IWebElement> radioOptions = driver.FindElements(By.Name(rdoName));

            foreach (IWebElement option in radioOptions)
            {
                // Click the option we want to select
                if (option.GetAttribute("value") == rdoValue)
                {
                    option.Click();
                    // Stop looping - we found our match
                    return;
                }
            }
        }

        /// <summary>
        /// Enters text into a textbox and submits its parent form
        /// </summary>
        /// <param name="driver">Current Web Driver</param>
        /// <param name="element">Name of TextBox element</param>
        /// <param name="text">Text to Enter</param>
        public static void EnterText(IWebDriver driver, String element, String text)
        {
            // Get the textbox element
            IWebElement textBox = driver.FindElement(By.Name(element));
            // To decrease input time, use JS as a workaround
            (driver as IJavaScriptExecutor).ExecuteScript(
                "document.getElementsByName('" + element + "')[0].setAttribute('value', '" + text + "')");
            textBox.Submit();
        }

        /// <summary>
        /// Submits a command to the simulator
        /// </summary>
        /// <param name="driver">Current web driver</param>
        /// <param name="command"></param>
        public static void SubmitCommand(IWebDriver driver, String command)
        {
            // To decrease input time, use JS as a workaround
            (driver as IJavaScriptExecutor).ExecuteScript(
                String.Format("document.frmClearance.txtClearance.value = '{0}'; return fnParseInput();", command));
        }

        /// <summary>
        /// Submits a web form
        /// </summary>
        /// <param name="driver">Current Web Driver</param>
        /// <param name="frmId">ID of the form to submit</param>
        public static void SubmitForm(ref IWebDriver driver, String frmId)
        {
            // Look for the form element and submit
            driver.FindElement(By.Id(frmId)).Submit();
        }
    }
}


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

namespace SE.DSP.Foundation.Infrastructure.Enumerations
{
    public enum DeploymentConfigKey
    {
        OTSEndPoint,
        OTSAccessId,
        OTSAccessKey,

        ProxyHost,
        ProxyPort,
        ProxyUserName,
        ProxyPassword,

        SpDbDatabase,
        SpDbServerIP,
        SpDbUser,
        SpDbPassword,
        SpDbMaxPoolSize,

        AppFabricServerHosts,

        LoginTrialSPs,
        LoginDemoTemplate,
        LoginPlatformDomain,
        LoginValidateDomain,

        CacheVersion,
        SmtpServerIP,

        DIKefDelimiter,
        DICollectorDir,
        DIExtractorDir,
        DIConvertorDir,
        DIImporterDir,

        FtpServer,
        FtpDownUser,
        FtpDownPwd,
        FtpDownPath,

        FtpUpDir,
        FtpDownDir,

        CODEREGEX,
        METERCODEREGEX,
        CUSTOMERCODEREGEX,

        WifAudienceUriDomains,
        WifAudienceUriTemplate,
        WifFederationIssuer,
        WifFederationRealm,
    }
}


text:
.proposal-link:hover {
  text-decoration: none;
}


text:
class AddOrderedFieldIdsToSavedQuery < ActiveRecord::Migration[5.2]
  def change
    add_column :saved_queries, :ordered_output_field_ids, :text
  end
end


text:
name=./ADEChallengeData2016

if [ ! -f ${name}.zip ]
then
	echo 'Downloading zip...'
	wget 'http://data.csail.mit.edu/places/ADEchallenge/ADEChallengeData2016.zip'
fi

if md5sum --status -c adechallenge.md5; then
	echo 'MD5 matches'
else
	echo 'MD5 does not match'
	exit 1
fi

rm -rf ${name}/

echo 'Unzipping...'
unzip -q ${name}.zip

echo 'Adjusting directories and file locations...'

mkdir -p ${name}/train/images/
mkdir -p ${name}/train/annotations/
mkdir -p ${name}/val/images/
mkdir -p ${name}/val/annotations/

mv ${name}/images/training/* ${name}/train/images/
mv ${name}/images/validation/* ${name}/val/images/

mv ${name}/annotations/training/* ${name}/train/annotations/
mv ${name}/annotations/validation/* ${name}/val/annotations/

rm -rf ${name}/images
rm -rf ${name}/annotations

echo 'Done.'


text:
Compiled example
----------------
![Example](topology-spiral.png)


text:
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <sys/types.h>
#include <unistd.h>
#include "libc_private.h"

__weak_reference(__sys_fork, __fork);

#pragma weak fork
pid_t
fork(void)
{

	return (((pid_t (*)(void))__libc_interposing[INTERPOS_fork])());
}


text:
ref class SoundEffect
{
internal:
    SoundEffect();

    void Initialize(
        _In_ IXAudio2*              masteringEngine,
        _In_ WAVEFORMATEX*          sourceFormat,
        _In_ Platform::Array<byte>^ soundData
        );

    void PlaySound(_In_ float volume);

protected private:
    bool                    m_audioAvailable;
    IXAudio2SourceVoice*    m_sourceVoice;
    Platform::Array<byte>^  m_soundData;
};


text:
"""Schedule for vision operators"""
from __future__ import absolute_import as _abs
import tvm
from .. import generic
from .. import cpp
from .. import tag

def _default_schedule(outs):
    """Default schedule for gpu."""
    target = tvm.target.current_target()
    outs = [outs] if isinstance(outs, tvm.tensor.Tensor) else outs
    s = tvm.create_schedule([x.op for x in outs])
    scheduled_ops = []

    def traverse(op):
        """inline all one-to-one-mapping operators except the last stage (output)"""
        if "nms" in op.tag:
            sort = op.input_tensors[1]
            score = s[sort].op.input_tensors[0]
            fused = s[score].fuse(*s[score].op.axis)
            num_thread = tvm.target.current_target(allow_none=False).max_num_threads
            bx, tx = s[score].split(fused, factor=num_thread)
            s[score].bind(bx, tvm.thread_axis("blockIdx.x"))
            s[score].bind(tx, tvm.thread_axis("threadIdx.x"))
        if tag.is_broadcast(op.tag):
            if op not in s.outputs:
                s[op].compute_inline()
            else:
                x = op.output(0)
                fused = s[x].fuse(*s[x].op.axis)
                num_thread = tvm.target.current_target(allow_none=False).max_num_threads
                bx, tx = s[x].split(fused, factor=num_thread)
                s[x].bind(bx, tvm.thread_axis("blockIdx.x"))
                s[x].bind(tx, tvm.thread_axis("threadIdx.x"))
            for tensor in op.input_tensors:
                if tensor.op.input_tensors and tensor.op not in scheduled_ops:
                    traverse(tensor.op)

        scheduled_ops.append(op)

    traverse(outs[0].op)
    return s

@generic.schedule_reorg.register(["cuda", "gpu"])
def schedule_reorg(outs):
    """Schedule for reorg operator.
    Parameters
    ----------
    outs: Array of Tensor
        The computation graph description of reorg
        in the format of an array of tensors.

    Returns
    -------
    s: Schedule
        The computation schedule for reorg.
    """
    target = tvm.target.current_target(allow_none=False)
    cpp_target = cpp.TEST_create_target(target.target_name)
    return cpp.cuda.schedule_injective(cpp_target, outs)

@generic.schedule_region.register(["cuda", "gpu"])
def schedule_region(outs):
    """Schedule for region operator.
    Parameters
    ----------
    outs: Array of Tensor
        The computation graph description of region
        in the format of an array of tensors.

    Returns
    -------
    s: Schedule
        The computation schedule for region.
    """
    target = tvm.target.current_target(allow_none=False)
    cpp_target = cpp.TEST_create_target(target.target_name)
    return cpp.cuda.schedule_region(cpp_target, outs)

@generic.schedule_nms.register(["cuda", "gpu"])
def schedule_nms(outs):
    """Schedule for non-maximum suppression

    Parameters
    ----------
    outs: Array of Tensor
      The computation graph description of nms
      in the format of an array of tensors.

    Returns
    -------
    s: Schedule
      The computation schedule for the op.
    """
    return _default_schedule(outs)

@generic.schedule_multibox_prior.register(["cuda", "gpu"])
def schedule_multibox_prior(outs):
    """Schedule for multibox_prior operator.

    Parameters
    ----------
    outs: Array of Tensor
        The computation graph description of multibox_prior
        in the format of an array of tensors.

    Returns
    -------
    s: Schedule
        The computation schedule for multibox_prior.
    """
    return _default_schedule(outs)

@generic.schedule_multibox_transform_loc.register(["cuda", "gpu"])
def schedule_multibox_transform_loc(outs):
    """Schedule for multibox_transform_loc

    Parameters
    ----------
    outs: Array of Tensor
      The computation graph description of
      multibox_transform_loc in the format
      of an array of tensors.

    Returns
    -------
    s: Schedule
      The computation schedule for the op.
    """
    return _default_schedule(outs)

@generic.schedule_multibox_detection.register(["cuda", "gpu"])
def schedule_multibox_detection(outs):
    """Schedule for multibox_detection operator.

    Parameters
    ----------
    outs: Array of Tensor
        The computation graph description of multibox_detection
        in the format of an array of tensors.

    Returns
    -------
    s: Schedule
        The computation schedule for multibox_detection.
    """
    return _default_schedule(outs)


text:
package org.apereo.portal.rendering.xslt;

import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Transformer;
import org.apereo.portal.utils.cache.CacheKey;

/**
 * Used by a {@link XSLTComponent} to configure the {@link Transformer}
 *
 * @author Eric Dalquist
 * @version $Revision$
 */
public interface TransformerConfigurationSource {
    /**
     * Passed on to {@link Transformer#setParameter(String, Object)}, ignored if null is returned
     */
    public Map<String, Object> getParameters(
            HttpServletRequest request, HttpServletResponse response);

    /**
     * Passed on to {@link Transformer#setOutputProperties(Properties)}, ignored if null is returned
     */
    public Properties getOutputProperties(HttpServletRequest request, HttpServletResponse response);

    /**
     * A key representing the state of the parameters and properties for the request, ignored if
     * null is returned
     */
    public CacheKey getCacheKey(HttpServletRequest request, HttpServletResponse response);
}


text:
package org.atomify.model.jaxrs;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.xml.transform.stream.StreamResult;

import org.atomify.model.AtomDocument;
import org.atomify.model.AtomDocumentParser;
import org.atomify.model.AtomDocumentSerializer;
import org.xml.sax.SAXException;

public class AtomDocumentProvider implements MessageBodyReader<AtomDocument>, MessageBodyWriter<AtomDocument> {

	// Reader Area

	public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
		return AtomDocument.class.isAssignableFrom(type);
	}

	public AtomDocument readFrom(Class<AtomDocument> type, Type genericType, Annotation[] annotations, MediaType mediaType,
			MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
		try {
			return new AtomDocumentParser().parse(entityStream);
		} catch (SAXException e) {
			throw new RuntimeException("Could not parse AtomDocument: "+e.getMessage(), e);
		}
	}

	// Writer Area

	public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
		return AtomDocument.class.isAssignableFrom(type);
	}

	public long getSize(AtomDocument t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
		return -1;
	}

	public void writeTo(AtomDocument t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
			MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
		Charset outputCharset = getCharset(mediaType);
		new AtomDocumentSerializer(outputCharset.name()).serialize(t, new StreamResult(entityStream));
	}

	private final Charset getCharset(MediaType m) {
		String name = (m == null) ? null : m.getParameters().get("charset");
		return (name == null) ? DEFAULT_CHARSET : Charset.forName(name);
	}

	private final static Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

}


text:
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/autofill_assistant/browser/actions/js_flow_action.h"
#include "base/json/json_reader.h"
#include "base/strings/strcat.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/mock_callback.h"
#include "components/autofill_assistant/browser/actions/mock_action_delegate.h"
#include "components/autofill_assistant/browser/js_flow_executor.h"
#include "components/autofill_assistant/browser/service.pb.h"
#include "components/autofill_assistant/browser/test_util.h"
#include "testing/gmock/include/gmock/gmock.h"

namespace autofill_assistant {
namespace {

using ::base::test::RunOnceCallback;
using ::testing::_;
using ::testing::AllOf;
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::Property;
using ::testing::SaveArgPointee;
using ::testing::WithArg;

// Parses |json| as a base::Value. No error handling - this will crash for
// invalid json inputs.
std::unique_ptr<base::Value> UniqueValueFromJson(const std::string& json) {
  return std::make_unique<base::Value>(
      std::move(*base::JSONReader::Read(json)));
}

class MockJsFlowExecutor : public JsFlowExecutor {
 public:
  MockJsFlowExecutor() = default;
  ~MockJsFlowExecutor() override = default;

  MOCK_METHOD(
      void,
      Start,
      (const std::string& js_flow,
       base::OnceCallback<void(const ClientStatus&,
                               std::unique_ptr<base::Value>)> result_callback),
      (override));
};

class JsFlowActionTest : public testing::Test {
 protected:
  std::unique_ptr<JsFlowAction> CreateAction(
      std::unique_ptr<JsFlowExecutor> js_flow_executor) {
    ActionProto action_proto;
    *action_proto.mutable_js_flow() = proto_;
    std::unique_ptr<JsFlowAction> action = std::make_unique<JsFlowAction>(
        &mock_action_delegate_, action_proto, std::move(js_flow_executor));
    return action;
  }

  MockActionDelegate mock_action_delegate_;
  base::MockCallback<Action::ProcessActionCallback> callback_;
  base::MockCallback<base::OnceCallback<
      void(const ClientStatus&, std::unique_ptr<base::Value> result_value)>>
      native_action_callback_;
  JsFlowProto proto_;
};

TEST_F(JsFlowActionTest, SmokeTest) {
  auto mock_js_flow_executor = std::make_unique<MockJsFlowExecutor>();

  EXPECT_CALL(*mock_js_flow_executor, Start("", _))
      .WillOnce(RunOnceCallback<1>(ClientStatus(ACTION_APPLIED),
                                   /* return_value = */ nullptr));
  EXPECT_CALL(
      callback_,
      Run(Pointee(Property(&ProcessedActionProto::status, ACTION_APPLIED))));
  CreateAction(std::move(mock_js_flow_executor))
      ->ProcessAction(callback_.Get());
}

TEST_F(JsFlowActionTest, FailsIfNativeActionIsInvalid) {
  auto mock_js_flow_executor = std::make_unique<MockJsFlowExecutor>();
  auto* mock_js_flow_executor_ptr = mock_js_flow_executor.get();
  auto action = CreateAction(std::move(mock_js_flow_executor));

  EXPECT_CALL(*mock_js_flow_executor_ptr, Start).WillOnce([&]() {
    // invalid action_id
    EXPECT_CALL(
        native_action_callback_,
        Run(Property(&ClientStatus::proto_status, UNSUPPORTED_ACTION), _));
    action->RunNativeAction(
        /* action_id = */ -1,
        /* action = */ std::string(), native_action_callback_.Get());
  });
  action->ProcessAction(callback_.Get());
}

TEST_F(JsFlowActionTest, FailsForInvalidNativeActionProto) {
  auto mock_js_flow_executor = std::make_unique<MockJsFlowExecutor>();
  auto* mock_js_flow_executor_ptr = mock_js_flow_executor.get();
  auto action = CreateAction(std::move(mock_js_flow_executor));

  EXPECT_CALL(*mock_js_flow_executor_ptr, Start).WillOnce([&]() {
    // invalid proto.
    EXPECT_CALL(native_action_callback_,
                Run(Property(&ClientStatus::proto_status, INVALID_ACTION), _));
    action->RunNativeAction(
        /* action_id = */ 11,
        /* action = */ "\xff\xff\xff", native_action_callback_.Get());
  });
  action->ProcessAction(callback_.Get());
}

TEST_F(JsFlowActionTest, NestedFlowActionsAreDisallowed) {
  auto mock_js_flow_executor = std::make_unique<MockJsFlowExecutor>();
  auto* mock_js_flow_executor_ptr = mock_js_flow_executor.get();
  auto action = CreateAction(std::move(mock_js_flow_executor));

  EXPECT_CALL(*mock_js_flow_executor_ptr, Start).WillOnce([&]() {
    // nested flows are disallowed. 92 == js_flow action.
    EXPECT_CALL(native_action_callback_,
                Run(Property(&ClientStatus::proto_status, INVALID_ACTION), _));
    action->RunNativeAction(
        /* action_id = */ 92,
        /* action = */ "", native_action_callback_.Get());
  });
  action->ProcessAction(callback_.Get());
}

TEST_F(JsFlowActionTest, NativeActionSucceeds) {
  auto mock_js_flow_executor = std::make_unique<MockJsFlowExecutor>();
  auto* mock_js_flow_executor_ptr = mock_js_flow_executor.get();
  auto action = CreateAction(std::move(mock_js_flow_executor));

  ActionProto native_action;
  native_action.mutable_tell()->set_message("Hello World!");
  EXPECT_CALL(*mock_js_flow_executor_ptr, Start)
      .WillOnce(WithArg<1>([&](auto finished_callback) {
        std::string serialized_native_action;
        native_action.tell().SerializeToString(&serialized_native_action);

        EXPECT_CALL(mock_action_delegate_, SetStatusMessage("Hello World!"));
        EXPECT_CALL(
            native_action_callback_,
            Run(Property(&ClientStatus::proto_status, ACTION_APPLIED), _));
        action->RunNativeAction(
            /* action_id = */ static_cast<int>(
                native_action.action_info_case()),
            /* action = */
            serialized_native_action, native_action_callback_.Get());
        std::move(finished_callback).Run(ClientStatus(ACTION_APPLIED), nullptr);
      }));
  ProcessedActionProto processed_action_capture;
  EXPECT_CALL(callback_, Run)
      .WillOnce(SaveArgPointee<0>(&processed_action_capture));
  action->ProcessAction(callback_.Get());

  EXPECT_THAT(processed_action_capture.status(), Eq(ACTION_APPLIED));
}

TEST_F(JsFlowActionTest, NativeActionFails) {
  auto mock_js_flow_executor = std::make_unique<MockJsFlowExecutor>();
  auto* mock_js_flow_executor_ptr = mock_js_flow_executor.get();
  auto action = CreateAction(std::move(mock_js_flow_executor));

  ActionProto native_action;
  // ShowCast without a selector is invalid.
  native_action.mutable_show_cast();
  EXPECT_CALL(*mock_js_flow_executor_ptr, Start)
      .WillOnce(WithArg<1>([&](auto finished_callback) {
        std::string serialized_native_action;
        native_action.show_cast().SerializeToString(&serialized_native_action);

        EXPECT_CALL(
            native_action_callback_,
            Run(Property(&ClientStatus::proto_status, INVALID_SELECTOR), _));
        action->RunNativeAction(
            /* action_id = */ static_cast<int>(
                native_action.action_info_case()),
            /* action = */
            serialized_native_action, native_action_callback_.Get());

        // Note: it is possible for the flow to succeed even if a native action
        // fails.
        std::move(finished_callback).Run(ClientStatus(ACTION_APPLIED), nullptr);
      }));
  ProcessedActionProto processed_action_capture;
  EXPECT_CALL(callback_, Run)
      .WillOnce(SaveArgPointee<0>(&processed_action_capture));
  action->ProcessAction(callback_.Get());
  EXPECT_THAT(processed_action_capture.status(), Eq(ACTION_APPLIED));
}

TEST_F(JsFlowActionTest, WritesFlowResultAsJsonDictToActionResult) {
  auto mock_js_flow_executor = std::make_unique<MockJsFlowExecutor>();

  EXPECT_CALL(*mock_js_flow_executor, Start("", _))
      .WillOnce(RunOnceCallback<1>(ClientStatus(ACTION_APPLIED),
                                   /* return_value = */ UniqueValueFromJson(R"(
        {
          "status": 3,
          "result": [[1, 2], null, {"enum": 5}]
        }
  )")));

  ProcessedActionProto processed_action_capture;
  EXPECT_CALL(callback_, Run)
      .WillOnce(SaveArgPointee<0>(&processed_action_capture));
  CreateAction(std::move(mock_js_flow_executor))
      ->ProcessAction(callback_.Get());

  // OTHER_ACTION_STATUS == 3
  EXPECT_THAT(processed_action_capture.status(), Eq(OTHER_ACTION_STATUS));
  EXPECT_EQ(base::JSONReader::Read(
                processed_action_capture.js_flow_result().result_json()),
            base::JSONReader::Read(R"([[1, 2], null, {"enum": 5}])"));
}

TEST_F(JsFlowActionTest, AllowsFlowsWithoutReturnValue) {
  auto mock_js_flow_executor = std::make_unique<MockJsFlowExecutor>();

  EXPECT_CALL(*mock_js_flow_executor, Start("", _))
      .WillOnce(RunOnceCallback<1>(ClientStatus(ACTION_APPLIED),
                                   /* return_value = */ nullptr));

  ProcessedActionProto processed_action_capture;
  EXPECT_CALL(callback_, Run)
      .WillOnce(SaveArgPointee<0>(&processed_action_capture));
  CreateAction(std::move(mock_js_flow_executor))
      ->ProcessAction(callback_.Get());

  EXPECT_THAT(processed_action_capture.status(), Eq(ACTION_APPLIED));
  EXPECT_FALSE(processed_action_capture.js_flow_result().has_result_json());
}

TEST_F(JsFlowActionTest, AllowsFlowsReturningStatusWithoutResult) {
  auto mock_js_flow_executor = std::make_unique<MockJsFlowExecutor>();

  EXPECT_CALL(*mock_js_flow_executor, Start("", _))
      .WillOnce(RunOnceCallback<1>(ClientStatus(ACTION_APPLIED),
                                   /* return_value = */ UniqueValueFromJson(R"(
        {
          "status": 3
        }
  )")));

  ProcessedActionProto processed_action_capture;
  EXPECT_CALL(callback_, Run)
      .WillOnce(SaveArgPointee<0>(&processed_action_capture));
  CreateAction(std::move(mock_js_flow_executor))
      ->ProcessAction(callback_.Get());

  EXPECT_THAT(processed_action_capture.status(), Eq(OTHER_ACTION_STATUS));
  EXPECT_FALSE(processed_action_capture.js_flow_result().has_result_json());
}

TEST_F(JsFlowActionTest, RemovesOriginalProtoFromTheProcessedAction) {
  auto mock_js_flow_executor = std::make_unique<MockJsFlowExecutor>();

  EXPECT_CALL(*mock_js_flow_executor, Start)
      .WillOnce(RunOnceCallback<1>(ClientStatus(ACTION_APPLIED),
                                   /* return_value = */ nullptr));

  ProcessedActionProto processed_action_capture;
  EXPECT_CALL(callback_, Run)
      .WillOnce(SaveArgPointee<0>(&processed_action_capture));
  proto_.set_js_flow(
      "console.log('Large blob that should not be sent back to the backend');");
  CreateAction(std::move(mock_js_flow_executor))
      ->ProcessAction(callback_.Get());

  EXPECT_THAT(processed_action_capture.status(), Eq(ACTION_APPLIED));
  EXPECT_FALSE(processed_action_capture.action().js_flow().has_js_flow());
}

}  // namespace
}  // namespace autofill_assistant


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin {
  function __construct(){
    $this->ci =& get_instance();
  }

  public function usuario_logado($condicao = TRUE, $redirecionar = NULL, $sessao_nome = 'admin_logado'){
    $checa_login = $this->ci->session->userdata($sessao_nome);
    $usuario_logado = $checa_login ? TRUE : FALSE;

    if($usuario_logado == $condicao){
      if($redirecionar){
        if($redirecionar === TRUE){
          $redirecionar = "admin/login";
        }
        $this->ci->session->set_tempdata('redirect', base_url($this->ci->uri->uri_string()), 180);
        redirect(base_url($redirecionar), 'location');
      }
      return TRUE;
    }
    return FALSE;
  }

  public function userinfo($slug){
    if($this->usuario_logado()){
      $usuario = $this->ci->session->userdata('admin_logado');
      if(isset($usuario[$slug])){
        return $usuario[$slug];
      }
    }
  }

  public function get_redirect($local = null) {
    $redirect = base_url($local ? $local : '');
    if($this->ci->input->post("redirect")) {
      $redirect = $this->ci->input->post("redirect");
    }else{
      if($this->ci->session->tempdata('redirect')) {
        $redirect = $this->ci->session->tempdata('redirect');
        $this->ci->session->unset_tempdata('redirect');
      }
    }
    return $redirect;
  }

  public function form_error($erros){
    $return = array();
    $erro_item = '';
    if($erros){
      foreach($erros as $key => $value){
        $erro_item .= '• ' . $value . '
';
        $return['erros'][$key] = $value;
      }
    }

    $return['alerta'] = array(
      'type' => 'danger',
      'message' => $erro_item,
      'status' => 'visible'
    );

    return $return;
  }

  public function alerta_redirect($alertaClass = 'danger', $mensagem = 'Ocorreu um erro inesperado.', $redirect = null, $status = 'visible', $extraClass = array()){
    $alerta = array(
      'alerta' => array(
        'type' => $alertaClass,
        'message' => $mensagem,
        'status' => $status,
        'class' => $extraClass
      )
    );

    if($redirect){
      $this->ci->session->set_flashdata('alerta', $alerta);
      $redirect = (strpos($redirect, '//') === false) ? base_url($redirect) : $redirect;
      redirect($redirect, 'location');
      exit;
    }

    return $alerta;
  }

  // public function enviar_email($destinatario, $assunto, $template_slug, $parametros = array(), $header = false){
  //   // Inicia helper de acesso ao template do e-mail
  //   $this->ci->load->helper('file');
  //   $template_path = "assets/site/emails/" . $template_slug;
  //   $template = read_file($template_path . '/template.html');

  //   if($parametros){
  //     foreach($parametros as $chave => $valor){
  //       $template = str_replace('{{'. $chave .'}}', $valor, $template);
  //     }
  //   }
  //   $template = str_replace("{{site_nome}}", $this->ci->config->item('site_nome'), $template);
  //   $template = str_replace("{{site_email}}", $this->ci->config->item('site_email'), $template);
  //   $template = str_replace("{{site_sigla}}", $this->ci->config->item('site_sigla'), $template);
  //   $template = str_replace("{{data_hora}}", date("d/m/Y H:i", time()), $template);
  //   $template = str_replace("{{template_url}}", base_url($template_path), $template);
  //   $template = str_replace("{{base_url}}", base_url(), $template);

  //   // Inicia class de envio de e-mail
  //   $this->ci->load->library('email');
  //   $this->ci->email->initialize(array('mailtype'=>'html'));

  //   $this->ci->email->from($this->ci->config->item('site_email_envio'), $this->ci->config->item('site_nome'), $this->ci->config->item('site_email_envio'));
  //   $this->ci->email->to($destinatario);
  //   //$this->ci->email->reply_to($post["email"], $post["nome"]);
  //   //$this->ci->email->bcc('desenvolvedor@digitalaction.com.br', 'Digital Action - Desenvolvedor');

  //   $this->ci->email->subject($assunto);
  //   $this->ci->email->message($template);

  //  //return $this->ci->email->send();
  // }

  // public function enviar_email_admin($assunto, $mensagem, $local = null){
  //   $this->ci->load->library('email');
  //   $this->ci->email->initialize(array('mailtype'=>'html'));

  //   $this->ci->email->from($this->ci->config->item('site_email_envio'), $this->ci->config->item('site_nome'), $this->ci->config->item('site_email_envio'));
  //   $this->ci->email->to($this->ci->config->item('site_email'));

  //   $mensagem_body = '
Mensagem:
' . nl2br($mensagem) . '
';
  //   if($local){
  //     $mensagem_body .= '
Local:
' . $local . '
';
  //   }
  //   $mensagem_body .= '
Data:
' . date("d/m/Y H:i", time()) . '
';

  //   $this->ci->email->subject($assunto);
  //   $this->ci->email->message($mensagem_body);

  //   //return $this->ci->email->send();
  // }
}


text:
//  RCInterruptMessage.h
//  Created by xugang on 15/1/12.

#import <Foundation/Foundation.h>
#import "RCMessageContent.h"

#define RCInterruptMessageTypeIdentifier @"RC:SpMsg"
/**
 *  客服挂断消息
 */
@interface RCSuspendMessage : RCMessageContent <RCMessageCoding, RCMessagePersistentCompatible>

/**
 *  init
 *
 *  @return return instance
 */
- (instancetype)init;

@end


text:
package org.apache.calcite.sql;

import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.util.ImmutableNullableList;

import java.util.List;
import java.util.Objects;

/**
 * Parse tree for {@code CREATE JOIN INDEX} statement.
 */
public class SqlCreateJoinIndex extends SqlCreate {
  private static final SqlOperator OPERATOR =
      new SqlSpecialOperator("CREATE JOIN INDEX",
          SqlKind.CREATE_JOIN_INDEX);

  public final SqlIdentifier name;
  public final List<SqlTableAttribute> tableAttributes;
  public final SqlNode select;
  public final List<SqlIndex> indices;

  /** Creates a {@code SqlCreateJoinIndex}. */
  public SqlCreateJoinIndex(SqlParserPos pos, SqlIdentifier name,
      List<SqlTableAttribute> tableAttributes, SqlNode select,
      List<SqlIndex> indices) {
    super(OPERATOR, pos, SqlCreateSpecifier.CREATE, false);
    this.name = Objects.requireNonNull(name);
    this.tableAttributes = Objects.requireNonNull(tableAttributes);
    this.select = Objects.requireNonNull(select);
    this.indices = Objects.requireNonNull(indices);
  }

  @Override public List<SqlNode> getOperandList() {
    return ImmutableNullableList.of(name, select);
  }

  @Override public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
    writer.keyword("CREATE JOIN INDEX");
    name.unparse(writer, 0, 0);
    if (!tableAttributes.isEmpty()) {
      SqlWriter.Frame frame = writer.startList("", "");
      for (SqlTableAttribute a : tableAttributes) {
        writer.sep(",", true);
        a.unparse(writer, 0, 0);
      }
      writer.endList(frame);
    }
    writer.keyword("AS");
    select.unparse(writer, 0, 0);
    if (!indices.isEmpty()) {
      SqlWriter.Frame frame = writer.startList("", "");
      for (SqlIndex index : indices) {
        writer.sep(",");
        index.unparse(writer, 0, 0);
      }
      writer.endList(frame);
    }
  }
}


text:
package fc.xml.xmlr;

import java.util.Iterator;

/**
 * Miscellaneous XMLR utilities.
 */
public class XmlrUtil {

    public static int countNodes(RefTree t) {
        return countNodes(t.getRoot(), 0);
    }

    private static int countNodes(RefTreeNode root, int i) {
        i++;
        for (Iterator<RefTreeNode> it = root.getChildIterator(); it.hasNext();)
            i = countNodes(it.next(), i);
        return i;
    }

    /*
     * public static class KeyIterator implements Iterator {
     *
     * Iterator i;
     *
     * KeyIterator(Iterator nodes) {
     *
     * }
     *
     * public boolean hasNext() { return i.hasNext(); }
     *
     * public Object next() { return ((RefTreeNode) i.next()).getId(); }
     *
     * public void remove() { throw new UnsupportedOperationException(); }
     *
     * }
     */

    /**
     * LRU cache for small quantities. Small = quantities for which a linear array search is fast
     * enough, e.g. 32 items. LRU swap-to-front happens both on put and get. All operations are
     * O(1), but 1 is larger for large caches :).
     */
    // IMPL NOTE: if asserts are enabled, the cache keeps stats of hits/misses;
    // as well as logs these on finalization
    /*
     * public static final class SmallLRUCache { private int hits=0; // NOTE: Needed for profiling
     * only private int calls=0; // NOTE: Needed for profiling only private int capacity; private
     * int mask; private int nextPos=0; private Object[] keyvals=null; // Array of keys and values.
     * keys in range // 0...capacity-1, and the corresponding value to // a key at index i is at
     * capacity+i
     *
     *
     * public SmallLRUCache(int bits) { capacity=1<<bits; mask=capacity-1; keyvals=new
     * Object[2capacity]; Object senitel = new Object(); for( int i=0;i<capacity;i++)
     * keyvals[i]=senitel; // Init to key array to unreachable key }
     *
     * public final void put(Object key, Object value) { //Log.debug("Put "+key+","+value); assert
     * ++calls > 0; int where = locate(key); if( where != -1) { // It's already here int
     * prevpos=(nextPos -1)&mask; if( where != prevpos ) { // Needs move to front
     * keyvals[where]=keyvals[prevpos]; keyvals[capacity+where]=keyvals[capacity+prevpos];
     * keyvals[prevpos]=key; keyvals[capacity+prevpos]=value; } return; }
     * keyvals[nextPos+capacity]=value; keyvals[nextPos++]=key; nextPos&=mask; // Wrap nextPos }
     *
     * public final Object get(Object key) { //Log.debug("Get "+key); assert ++calls > 0; int where
     * = locate(key); if( where != -1) { int prevpos=(nextPos -1)&mask; // It's here Object value =
     * keyvals[capacity+where]; if( where != prevpos ) { // Needs move to front
     * keyvals[where]=keyvals[prevpos]; keyvals[capacity+where]=keyvals[capacity+prevpos];
     * keyvals[prevpos]=key; keyvals[capacity+prevpos]=value; } return value; } return null; }
     *
     * private final int locate(Object key) { int low = nextPos; int high = nextPos+capacity;
     * for(int i = low; i< high; i++) { if( keyvals[i&mask] == key ) { assert ++hits > 0; return
     * i&mask; } } return -1; }
     *
     * protected void finalize() { assert stats()>0; }
     *
     * private int stats() { Log.info("Cache stats for cache "+hashCode()+" (hits/all): "
     * +hits+"/"+calls); return 1; }
     *
     * / // Test code: public static void main(String[] args) { SmallLRUCache c = new
     * SmallLRUCache(4); Object[] keys={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; Object[]
     * vals={100+0,100+1,100+2,100+3,100+4,100+5,100+6,100+7,100+8,
     * 100+9,100+10,100+11,100+12,100+13,100+14,100+15}; for( int i = 0; i<keys.length;i++ )
     * c.put(keys[i], vals[i]); for( int i = 0; i<keys.length;i++ ) assert c.get(keys[i]) ==
     * vals[i]; c = new SmallLRUCache(3); c.put(keys[8], vals[8]); for( int i = 0; i<keys.length;i++
     * ) { c.get(keys[8]); // Keep keys[8] warm c.put(keys[i], vals[i]); } assert c.get(keys[0]) ==
     * null; // Verify cold key was lost assert c.get(keys[8]) == vals[8]; // Verify warm key was
     * kept }
     *//*
        *
        *
        * }
        */
}

// arch-tag: c1689962-aedf-4fd5-b820-8f40fa544aaa