text:
using ppapi::ArrayBufferVar;
using ppapi::PpapiGlobals;
using ppapi::ScopedPPVar;
using ppapi::StringVar;
using blink::WebElement;
using blink::WebDOMEvent;
using blink::WebDOMMessageEvent;
using blink::WebPluginContainer;
using blink::WebSerializedScriptValue;

namespace content {

namespace {

const char kPostMessage[] = "postMessage";
const char kPostMessageAndAwaitResponse[] = "postMessageAndAwaitResponse";
const char kV8ToVarConversionError[] =
    "Failed to convert a PostMessage "
    "argument from a JavaScript value to a PP_Var. It may have cycles or be of "
    "an unsupported type.";
const char kVarToV8ConversionError[] =
    "Failed to convert a PostMessage "
    "argument from a PP_Var to a Javascript value. It may have cycles or be of "
    "an unsupported type.";

}  // namespace

// MessageChannel --------------------------------------------------------------
struct MessageChannel::VarConversionResult {
  VarConversionResult() : success_(false), conversion_completed_(false) {}
  void ConversionCompleted(const ScopedPPVar& var,
                           bool success) {
    conversion_completed_ = true;
    var_ = var;
    success_ = success;
  }
  const ScopedPPVar& var() const { return var_; }
  bool success() const { return success_; }
  bool conversion_completed() const { return conversion_completed_; }

 private:
  ScopedPPVar var_;
  bool success_;
  bool conversion_completed_;
};

// static
gin::WrapperInfo MessageChannel::kWrapperInfo = {gin::kEmbedderNativeGin};

// static
MessageChannel* MessageChannel::Create(PepperPluginInstanceImpl* instance,
                                       v8::Persistent<v8::Object>* result) {
  MessageChannel* message_channel = new MessageChannel(instance);
  v8::HandleScope handle_scope(instance->GetIsolate());
  v8::Context::Scope context_scope(instance->GetMainWorldContext());
  gin::Handle<MessageChannel> handle =
      gin::CreateHandle(instance->GetIsolate(), message_channel);
  result->Reset(instance->GetIsolate(),
                handle.ToV8()->ToObject(instance->GetIsolate()));
  return message_channel;
}

MessageChannel::~MessageChannel() {
  UnregisterSyncMessageStatusObserver();

  passthrough_object_.Reset();
  if (instance_)
    instance_->MessageChannelDestroyed();
}

void MessageChannel::InstanceDeleted() {
  UnregisterSyncMessageStatusObserver();
  instance_ = NULL;
}

void MessageChannel::PostMessageToJavaScript(PP_Var message_data) {
  v8::HandleScope scope(v8::Isolate::GetCurrent());

  // Because V8 is probably not on the stack for Native->JS calls, we need to
  // enter the appropriate context for the plugin.
  v8::Local<v8::Context> context = instance_->GetMainWorldContext();
  if (context.IsEmpty())
    return;

  v8::Context::Scope context_scope(context);

  v8::Local<v8::Value> v8_val;
  if (!var_converter_.ToV8Value(message_data, context, &v8_val)) {
    PpapiGlobals::Get()->LogWithSource(instance_->pp_instance(),
                                       PP_LOGLEVEL_ERROR,
                                       std::string(),
                                       kVarToV8ConversionError);
    return;
  }

  WebSerializedScriptValue serialized_val =
      WebSerializedScriptValue::serialize(v8_val);

  if (js_message_queue_state_ != SEND_DIRECTLY) {
    // We can't just PostTask here; the messages would arrive out of
    // order. Instead, we queue them up until we're ready to post
    // them.
    js_message_queue_.push_back(serialized_val);
  } else {
    // The proxy sent an asynchronous message, so the plugin is already
    // unblocked. Therefore, there's no need to PostTask.
    DCHECK(js_message_queue_.empty());
    PostMessageToJavaScriptImpl(serialized_val);
  }
}

void MessageChannel::Start() {
  DCHECK_EQ(WAITING_TO_START, js_message_queue_state_);
  DCHECK_EQ(WAITING_TO_START, plugin_message_queue_state_);

  ppapi::proxy::HostDispatcher* dispatcher =
      ppapi::proxy::HostDispatcher::GetForInstance(instance_->pp_instance());
  // The dispatcher is NULL for in-process.
  if (dispatcher) {
    unregister_observer_callback_ =
        dispatcher->AddSyncMessageStatusObserver(this);
  }

  // We can't drain the JS message queue directly since we haven't finished
  // initializing the PepperWebPluginImpl yet, so the plugin isn't available in
  // the DOM.
  DrainJSMessageQueueSoon();

  plugin_message_queue_state_ = SEND_DIRECTLY;
  DrainCompletedPluginMessages();
}

void MessageChannel::SetPassthroughObject(v8::Local<v8::Object> passthrough) {
  passthrough_object_.Reset(instance_->GetIsolate(), passthrough);
}

void MessageChannel::SetReadOnlyProperty(PP_Var key, PP_Var value) {
  StringVar* key_string = StringVar::FromPPVar(key);
  if (key_string) {
    internal_named_properties_[key_string->value()] = ScopedPPVar(value);
  } else {
    NOTREACHED();
  }
}

MessageChannel::MessageChannel(PepperPluginInstanceImpl* instance)
    : gin::NamedPropertyInterceptor(instance->GetIsolate(), this),
      instance_(instance),
      js_message_queue_state_(WAITING_TO_START),
      drain_js_message_queue_scheduled_(false),
      blocking_message_depth_(0),
      plugin_message_queue_state_(WAITING_TO_START),
      var_converter_(instance->pp_instance(),
                     V8VarConverter::kDisallowObjectVars),
      template_cache_(instance->GetIsolate()),
      weak_ptr_factory_(this) {
}

gin::ObjectTemplateBuilder MessageChannel::GetObjectTemplateBuilder(
    v8::Isolate* isolate) {
  return Wrappable<MessageChannel>::GetObjectTemplateBuilder(isolate)
      .AddNamedPropertyInterceptor();
}

void MessageChannel::BeginBlockOnSyncMessage() {
  js_message_queue_state_ = QUEUE_MESSAGES;
  ++blocking_message_depth_;
}

void MessageChannel::EndBlockOnSyncMessage() {
  DCHECK_GT(blocking_message_depth_, 0);
  --blocking_message_depth_;
  if (!blocking_message_depth_)
    DrainJSMessageQueueSoon();
}

v8::Local<v8::Value> MessageChannel::GetNamedProperty(
    v8::Isolate* isolate,
    const std::string& identifier) {
  if (!instance_)
    return v8::Local<v8::Value>();

  PepperTryCatchV8 try_catch(instance_, &var_converter_, isolate);
  if (identifier == kPostMessage) {
    return GetFunctionTemplate(isolate, identifier,
                               &MessageChannel::PostMessageToNative)
        ->GetFunction();
  } else if (identifier == kPostMessageAndAwaitResponse) {
    return GetFunctionTemplate(isolate, identifier,
                               &MessageChannel::PostBlockingMessageToNative)
        ->GetFunction();
  }

  std::map<std::string, ScopedPPVar>::const_iterator it =
      internal_named_properties_.find(identifier);
  if (it != internal_named_properties_.end()) {
    v8::Local<v8::Value> result = try_catch.ToV8(it->second.get());
    if (try_catch.ThrowException())
      return v8::Local<v8::Value>();
    return result;
  }

  PluginObject* plugin_object = GetPluginObject(isolate);
  if (plugin_object)
    return plugin_object->GetNamedProperty(isolate, identifier);
  return v8::Local<v8::Value>();
}

bool MessageChannel::SetNamedProperty(v8::Isolate* isolate,
                                      const std::string& identifier,
                                      v8::Local<v8::Value> value) {
  if (!instance_)
    return false;
  PepperTryCatchV8 try_catch(instance_, &var_converter_, isolate);
  if (identifier == kPostMessage ||
      identifier == kPostMessageAndAwaitResponse) {
    try_catch.ThrowException("Cannot set properties with the name postMessage"
                             "or postMessageAndAwaitResponse");
    return true;
  }

  // TODO(raymes): This is only used by the gTalk plugin which is deprecated.
  // Remove passthrough of SetProperty calls as soon as it is removed.
  PluginObject* plugin_object = GetPluginObject(isolate);
  if (plugin_object)
    return plugin_object->SetNamedProperty(isolate, identifier, value);

  return false;
}

std::vector<std::string> MessageChannel::EnumerateNamedProperties(
    v8::Isolate* isolate) {
  std::vector<std::string> result;
  PluginObject* plugin_object = GetPluginObject(isolate);
  if (plugin_object)
    result = plugin_object->EnumerateNamedProperties(isolate);
  result.push_back(kPostMessage);
  result.push_back(kPostMessageAndAwaitResponse);
  return result;
}

void MessageChannel::PostMessageToNative(gin::Arguments* args) {
  if (!instance_)
    return;
  if (args->Length() != 1) {
    // TODO(raymes): Consider throwing an exception here. We don't now for
    // backward compatibility.
    return;
  }

  v8::Local<v8::Value> message_data;
  if (!args->GetNext(&message_data)) {
    NOTREACHED();
  }

  EnqueuePluginMessage(message_data);
  DrainCompletedPluginMessages();
}

void MessageChannel::PostBlockingMessageToNative(gin::Arguments* args) {
  if (!instance_)
    return;
  PepperTryCatchV8 try_catch(instance_, &var_converter_, args->isolate());
  if (args->Length() != 1) {
    try_catch.ThrowException(
        "postMessageAndAwaitResponse requires one argument");
    return;
  }

  v8::Local<v8::Value> message_data;
  if (!args->GetNext(&message_data)) {
    NOTREACHED();
  }

  if (plugin_message_queue_state_ == WAITING_TO_START) {
    try_catch.ThrowException(
        "Attempted to call a synchronous method on a plugin that was not "
        "yet loaded.");
    return;
  }

  // If the queue of messages to the plugin is non-empty, we're still waiting on
  // pending Var conversions. This means at some point in the past, JavaScript
  // called postMessage (the async one) and passed us something with a browser-
  // side host (e.g., FileSystem) and we haven't gotten a response from the
  // browser yet. We can't currently support sending a sync message if the
  // plugin does this, because it will break the ordering of the messages
  // arriving at the plugin.
  // TODO(dmichael): Fix this.
  // See https://code.google.com/p/chromium/issues/detail?id=367896#c4
  if (!plugin_message_queue_.empty()) {
    try_catch.ThrowException(
        "Failed to convert parameter synchronously, because a prior "
        "call to postMessage contained a type which required asynchronous "
        "transfer which has not completed. Not all types are supported yet by "
        "postMessageAndAwaitResponse. See crbug.com/367896.");
    return;
  }
  ScopedPPVar param = try_catch.FromV8(message_data);
  if (try_catch.ThrowException())
    return;

  ScopedPPVar pp_result;
  bool was_handled = instance_->HandleBlockingMessage(param, &pp_result);
  if (!was_handled) {
    try_catch.ThrowException(
        "The plugin has not registered a handler for synchronous messages. "
        "See the documentation for PPB_Messaging::RegisterMessageHandler "
        "and PPP_MessageHandler.");
    return;
  }
  v8::Local<v8::Value> v8_result = try_catch.ToV8(pp_result.get());
  if (try_catch.ThrowException())
    return;

  args->Return(v8_result);
}

void MessageChannel::PostMessageToJavaScriptImpl(
    const WebSerializedScriptValue& message_data) {
  DCHECK(instance_);

  WebPluginContainer* container = instance_->container();
  // It's possible that container() is NULL if the plugin has been removed from
  // the DOM (but the PluginInstance is not destroyed yet).
  if (!container)
    return;

  // [*] Note that the |origin| is only specified for cross-document and server-
  //     sent messages, while |source| is only specified for cross-document
  //     messages:
  //      http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html
  //     This currently behaves like Web Workers. On Firefox, Chrome, and Safari
  //     at least, postMessage on Workers does not provide the origin or source.
  //     TODO(dmichael):  Add origin if we change to a more iframe-like origin
  //                      policy (see crbug.com/81537)
  WebDOMMessageEvent msg_event(message_data);
  container->element().dispatchEvent(msg_event);
}

PluginObject* MessageChannel::GetPluginObject(v8::Isolate* isolate) {
  return PluginObject::FromV8Object(isolate,
      v8::Local<v8::Object>::New(isolate, passthrough_object_));
}

void MessageChannel::EnqueuePluginMessage(v8::Local<v8::Value> v8_value) {
  plugin_message_queue_.push_back(VarConversionResult());
  // Convert the v8 value in to an appropriate PP_Var like Dictionary,
  // Array, etc. (We explicitly don't want an "Object" PP_Var, which we don't
  // support for Messaging.)
  // TODO(raymes): Possibly change this to use TryCatch to do the conversion and
  // throw an exception if necessary.
  V8VarConverter::VarResult conversion_result =
      var_converter_.FromV8Value(
          v8_value,
          v8::Isolate::GetCurrent()->GetCurrentContext(),
          base::Bind(&MessageChannel::FromV8ValueComplete,
                     weak_ptr_factory_.GetWeakPtr(),
                     &plugin_message_queue_.back()));
  if (conversion_result.completed_synchronously) {
    plugin_message_queue_.back().ConversionCompleted(
        conversion_result.var,
        conversion_result.success);
  }
}

void MessageChannel::FromV8ValueComplete(VarConversionResult* result_holder,
                                         const ScopedPPVar& result,
                                         bool success) {
  if (!instance_)
    return;
  result_holder->ConversionCompleted(result, success);
  DrainCompletedPluginMessages();
}

void MessageChannel::DrainCompletedPluginMessages() {
  DCHECK(instance_);
  if (plugin_message_queue_state_ == WAITING_TO_START)
    return;

  while (!plugin_message_queue_.empty() &&
         plugin_message_queue_.front().conversion_completed()) {
    const VarConversionResult& front = plugin_message_queue_.front();
    if (front.success()) {
      instance_->HandleMessage(front.var());
    } else {
      PpapiGlobals::Get()->LogWithSource(instance()->pp_instance(),
                                         PP_LOGLEVEL_ERROR,
                                         std::string(),
                                         kV8ToVarConversionError);
    }
    plugin_message_queue_.pop_front();
  }
}

void MessageChannel::DrainJSMessageQueue() {
  DCHECK(drain_js_message_queue_scheduled_);
  drain_js_message_queue_scheduled_ = false;

  if (!instance_)
    return;
  if (js_message_queue_state_ == SEND_DIRECTLY)
    return;

  // Take a reference on the PluginInstance. This is because JavaScript code
  // may delete the plugin, which would destroy the PluginInstance and its
  // corresponding MessageChannel.
  scoped_refptr<PepperPluginInstanceImpl> instance_ref(instance_);
  while (!js_message_queue_.empty()) {
    PostMessageToJavaScriptImpl(js_message_queue_.front());
    js_message_queue_.pop_front();
  }
  js_message_queue_state_ = SEND_DIRECTLY;
}

void MessageChannel::DrainJSMessageQueueSoon() {
  if (drain_js_message_queue_scheduled_)
    return;

  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE, base::Bind(&MessageChannel::DrainJSMessageQueue,
                            weak_ptr_factory_.GetWeakPtr()));
  drain_js_message_queue_scheduled_ = true;
}

void MessageChannel::UnregisterSyncMessageStatusObserver() {
  if (!unregister_observer_callback_.is_null()) {
    unregister_observer_callback_.Run();
    unregister_observer_callback_.Reset();
  }
}

v8::Local<v8::FunctionTemplate> MessageChannel::GetFunctionTemplate(
    v8::Isolate* isolate,
    const std::string& name,
    void (MessageChannel::*memberFuncPtr)(gin::Arguments* args)) {
  v8::Local<v8::FunctionTemplate> function_template = template_cache_.Get(name);
  if (!function_template.IsEmpty())
    return function_template;
  function_template = gin::CreateFunctionTemplate(
      isolate, base::Bind(memberFuncPtr, weak_ptr_factory_.GetWeakPtr()));
  template_cache_.Set(name, function_template);
  return function_template;
}

}  // namespace content


text:
'use strict';

const Rule = require('./base');

module.exports = class NoUnnecessaryConcat extends Rule {
  visitor() {
    return {
      ConcatStatement(node) {
        if (node.parts.length === 1) {
          let source = this.sourceForNode(node);
          let innerSource = this.sourceForNode(node.parts[0]);
          let message = `Unnecessary string concatenation. Use ${innerSource} instead of ${source}.`;

          this.log({
            message,
            line: node.loc && node.loc.start.line,
            column: node.loc && node.loc.start.column,
            source,
          });
        }
      },
    };
  }
};

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace OpenClassrooms\Bundle\OneSkyBundle\Tests\Gateways\Impl;

use OpenClassrooms\Bundle\OneSkyBundle\Gateways\FileGateway;
use OpenClassrooms\Bundle\OneSkyBundle\Gateways\Impl\FileGatewayImpl;
use OpenClassrooms\Bundle\OneSkyBundle\Model\ExportFile;
use OpenClassrooms\Bundle\OneSkyBundle\Model\UploadFile;
use OpenClassrooms\Bundle\OneSkyBundle\Tests\Doubles\Model\ExportFileStub1;
use OpenClassrooms\Bundle\OneSkyBundle\Tests\Doubles\Model\ExportFileStub2;
use OpenClassrooms\Bundle\OneSkyBundle\Tests\Doubles\Model\UploadFileStub1;
use OpenClassrooms\Bundle\OneSkyBundle\Tests\Doubles\Model\UploadFileStub2;
use OpenClassrooms\Bundle\OneSkyBundle\Tests\Doubles\OneSky\Api\ClientMock;
use Symfony\Component\EventDispatcher\EventDispatcher;

/**
 * @author Romain Kuzniak <romain.kuzniak@openclassrooms.com>
 */
class FileGatewayImplTest extends \PHPUnit_Framework_TestCase
{
    const EXPECTED_DOWNLOADED_FILE_1 = __DIR__.'/../../Fixtures/Resources/translations/messages.fr.yml';

    const EXPECTED_DOWNLOADED_FILE_2 = __DIR__.'/../../Fixtures/Resources/translations/subDirectory/messages.fr.yml';

    /**
     * @var FileGateway
     */
    private $gateway;

    /**
     * @test
     */
    public function WithoutFiles_upload_DoNothing()
    {
        $uploadedTranslations = $this->gateway->uploadTranslations([]);
        $this->assertNull(ClientMock::$action);
        $this->assertEmpty($uploadedTranslations);
    }

    /**
     * @test
     */
    public function OneFile_upload()
    {
        $uploadFileStub1 = new UploadFileStub1();
        $uploadedTranslations = $this->gateway->uploadTranslations([$uploadFileStub1]);
        $this->assertEquals(ClientMock::$action, FileGateway::UPLOAD_METHOD);
        $this->assertEquals(
            [
                [
                    UploadFile::PROJECT_ID             => UploadFileStub1::PROJECT_ID,
                    UploadFile::SOURCE_FILE_PATH       => $uploadFileStub1->getFormattedFilePath(),
                    UploadFile::FILE_FORMAT            => UploadFileStub1::FILE_FORMAT,
                    UploadFile::SOURCE_LOCALE          => UploadFileStub1::SOURCE_LOCALE,
                    UploadFile::IS_KEEPING_ALL_STRINGS => UploadFileStub1::IS_KEEPING_ALL_STRINGS,
                ],
            ],
            ClientMock::$parameters
        );
        $this->assertEquals([new UploadFileStub1()], $uploadedTranslations);
    }

    /**
     * @test
     */
    public function ManyFiles_upload_Upload()
    {
        $uploadFileStub1 = new UploadFileStub1();
        $uploadFileStub2 = new UploadFileStub2();
        $uploadedTranslations = $this->gateway->uploadTranslations([$uploadFileStub1, $uploadFileStub2]);
        $this->assertEquals(ClientMock::$action, FileGateway::UPLOAD_METHOD);
        $this->assertEquals(
            [
                [
                    UploadFile::PROJECT_ID             => UploadFileStub1::PROJECT_ID,
                    UploadFile::SOURCE_FILE_PATH       => $uploadFileStub1->getFormattedFilePath(),
                    UploadFile::FILE_FORMAT            => UploadFileStub1::FILE_FORMAT,
                    UploadFile::SOURCE_LOCALE          => UploadFileStub1::SOURCE_LOCALE,
                    UploadFile::IS_KEEPING_ALL_STRINGS => UploadFileStub1::IS_KEEPING_ALL_STRINGS,
                ],
                [
                    UploadFile::PROJECT_ID             => UploadFileStub2::PROJECT_ID,
                    UploadFile::SOURCE_FILE_PATH       => $uploadFileStub2->getFormattedFilePath(),
                    UploadFile::FILE_FORMAT            => UploadFileStub2::FILE_FORMAT,
                    UploadFile::SOURCE_LOCALE          => UploadFileStub2::SOURCE_LOCALE,
                    UploadFile::IS_KEEPING_ALL_STRINGS => UploadFileStub2::IS_KEEPING_ALL_STRINGS
                ],
            ],
            ClientMock::$parameters
        );
        $this->assertEquals([new UploadFileStub1(), new UploadFileStub2()], $uploadedTranslations);
    }

    /**
     * @test
     * @expectedException \OpenClassrooms\Bundle\OneSkyBundle\Gateways\InvalidContentException
     */
    public function WithApiException_download_ThrowException()
    {
        ClientMock::$downloadedContent = '{exception}';
        $this->gateway->downloadTranslations([new ExportFileStub1()]);
    }

    /**
     * @test
     */
    public function WithFileNotOnApiException_download_DoNothing()
    {
        ClientMock::$downloadedContent = '{"meta":{"status":400,"message":"Invalid source file"},"data":{}}';
        $this->gateway->downloadTranslations([new ExportFileStub1()]);
    }

    /**
     * @test
     * @expectedException \Guzzle\Http\Exception\ServerErrorResponseException
     */
    public function ApiServerError_download_ThrowException()
    {
        ClientMock::$downloadedContent = '{"meta":{"status":500,"message":"Something went wrong. Please try again or contact us at support@oneskyapp.com"},"data":{}}';
        $this->gateway->downloadTranslations([new ExportFileStub1()]);
    }

    /**
     * @test
     */
    public function WithoutFile_download_DoNothing()
    {
        $downloadedTranslations = $this->gateway->downloadTranslations([]);
        $this->assertNull(ClientMock::$action);
        $this->assertEmpty($downloadedTranslations);
    }

    /**
     * @test
     */
    public function WithOneFile_download_Download()
    {
        $exportFileStub1 = new ExportFileStub1();
        $downloadedTranslations = $this->gateway->downloadTranslations([$exportFileStub1]);
        $this->assertEquals(ClientMock::$action, FileGateway::DOWNLOAD_METHOD);
        $this->assertEquals(
            ClientMock::$parameters,
            [
                [
                    ExportFile::PROJECT_ID                 => ExportFileStub1::PROJECT_ID,
                    ExportFile::REQUESTED_LOCALE           => ExportFileStub1::REQUESTED_LOCALE,
                    ExportFile::REQUESTED_SOURCE_FILE_NAME => $exportFileStub1->getEncodedSourceFileName(),
                ],
            ]
        );
        $this->assertStringEqualsFile(self::EXPECTED_DOWNLOADED_FILE_1, 'Download : 1');
        $this->assertEquals([new ExportFileStub1()], $downloadedTranslations);
    }

    /**
     * @test
     */
    public function WithManyFiles_upload_Upload()
    {
        $exportFileStub1 = new ExportFileStub1();
        $exportFileStub2 = new ExportFileStub2();
        $downloadedTranslations = $this->gateway->downloadTranslations([$exportFileStub1, $exportFileStub2]);
        $this->assertEquals(ClientMock::$action, FileGateway::DOWNLOAD_METHOD);
        $this->assertEquals(
            ClientMock::$parameters,
            [
                [
                    ExportFile::PROJECT_ID                 => ExportFileStub1::PROJECT_ID,
                    ExportFile::REQUESTED_LOCALE           => ExportFileStub1::REQUESTED_LOCALE,
                    ExportFile::REQUESTED_SOURCE_FILE_NAME => $exportFileStub1->getEncodedSourceFileName(),
                ],
                [
                    ExportFile::PROJECT_ID                 => ExportFileStub2::PROJECT_ID,
                    ExportFile::REQUESTED_LOCALE           => ExportFileStub2::REQUESTED_LOCALE,
                    ExportFile::REQUESTED_SOURCE_FILE_NAME => $exportFileStub2->getEncodedSourceFileName(),
                ],
            ]
        );
        $this->assertStringEqualsFile(self::EXPECTED_DOWNLOADED_FILE_1, 'Download : 1');
        $this->assertStringEqualsFile(self::EXPECTED_DOWNLOADED_FILE_2, 'Download : 2');
        $this->assertEquals([new ExportFileStub1(), new ExportFileStub2()], $downloadedTranslations);
    }

    protected function setUp()
    {
        $this->gateway = new FileGatewayImpl();
        $this->gateway->setClient(new ClientMock());
        $this->gateway->setEventDispatcher(new EventDispatcher());
    }

    /**
     * {@inheritdoc}
     */
    protected function tearDown()
    {
        file_exists(self::EXPECTED_DOWNLOADED_FILE_1) ? unlink(self::EXPECTED_DOWNLOADED_FILE_1) : null;
        file_exists(self::EXPECTED_DOWNLOADED_FILE_2) ? unlink(self::EXPECTED_DOWNLOADED_FILE_2) : null;
    }
}


text:
/**
 */
package org.afplib.afplib.impl;

import org.afplib.afplib.AfplibPackage;
import org.afplib.afplib.ExtendedResourceLocalIdentifier;

import org.afplib.base.impl.TripletImpl;

import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.ecore.EClass;

import org.eclipse.emf.ecore.impl.ENotificationImpl;

/**
 *
 * An implementation of the model object 'Extended Resource Local Identifier'.
 *
 *

 * The following features are implemented:
 *

 *

 *
{@link org.afplib.afplib.impl.ExtendedResourceLocalIdentifierImpl#getResType Res Type}

 *
{@link org.afplib.afplib.impl.ExtendedResourceLocalIdentifierImpl#getResLID Res LID}

 *

 *
 * @generated
 */
public class ExtendedResourceLocalIdentifierImpl extends TripletImpl implements ExtendedResourceLocalIdentifier {
	/**
	 * The default value of the '{@link #getResType() Res Type}' attribute.
	 *
	 *
	 * @see #getResType()
	 * @generated
	 * @ordered
	 */
	protected static final Integer RES_TYPE_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getResType() Res Type}' attribute.
	 *
	 *
	 * @see #getResType()
	 * @generated
	 * @ordered
	 */
	protected Integer resType = RES_TYPE_EDEFAULT;

	/**
	 * The default value of the '{@link #getResLID() Res LID}' attribute.
	 *
	 *
	 * @see #getResLID()
	 * @generated
	 * @ordered
	 */
	protected static final Integer RES_LID_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getResLID() Res LID}' attribute.
	 *
	 *
	 * @see #getResLID()
	 * @generated
	 * @ordered
	 */
	protected Integer resLID = RES_LID_EDEFAULT;

	/**
	 *
	 *
	 * @generated
	 */
	protected ExtendedResourceLocalIdentifierImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return AfplibPackage.eINSTANCE.getExtendedResourceLocalIdentifier();
	}

	/**
	 *
	 *
	 * @generated
	 */
	public Integer getResType() {
		return resType;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setResType(Integer newResType) {
		Integer oldResType = resType;
		resType = newResType;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.EXTENDED_RESOURCE_LOCAL_IDENTIFIER__RES_TYPE, oldResType, resType));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public Integer getResLID() {
		return resLID;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setResLID(Integer newResLID) {
		Integer oldResLID = resLID;
		resLID = newResLID;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.EXTENDED_RESOURCE_LOCAL_IDENTIFIER__RES_LID, oldResLID, resLID));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case AfplibPackage.EXTENDED_RESOURCE_LOCAL_IDENTIFIER__RES_TYPE:
				return getResType();
			case AfplibPackage.EXTENDED_RESOURCE_LOCAL_IDENTIFIER__RES_LID:
				return getResLID();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case AfplibPackage.EXTENDED_RESOURCE_LOCAL_IDENTIFIER__RES_TYPE:
				setResType((Integer)newValue);
				return;
			case AfplibPackage.EXTENDED_RESOURCE_LOCAL_IDENTIFIER__RES_LID:
				setResLID((Integer)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case AfplibPackage.EXTENDED_RESOURCE_LOCAL_IDENTIFIER__RES_TYPE:
				setResType(RES_TYPE_EDEFAULT);
				return;
			case AfplibPackage.EXTENDED_RESOURCE_LOCAL_IDENTIFIER__RES_LID:
				setResLID(RES_LID_EDEFAULT);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case AfplibPackage.EXTENDED_RESOURCE_LOCAL_IDENTIFIER__RES_TYPE:
				return RES_TYPE_EDEFAULT == null ? resType != null : !RES_TYPE_EDEFAULT.equals(resType);
			case AfplibPackage.EXTENDED_RESOURCE_LOCAL_IDENTIFIER__RES_LID:
				return RES_LID_EDEFAULT == null ? resLID != null : !RES_LID_EDEFAULT.equals(resLID);
		}
		return super.eIsSet(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		if (eIsProxy()) return super.toString();

		StringBuffer result = new StringBuffer(super.toString());
		result.append(" (ResType: ");
		result.append(resType);
		result.append(", ResLID: ");
		result.append(resLID);
		result.append(')');
		return result.toString();
	}

} //ExtendedResourceLocalIdentifierImpl


text:
namespace embree
{
  struct MetallicPaint
  {
    static void* create(const Parms& parms)
    {
      const Color shadeColor    = parms.getColor("shadeColor",one);
      const Color glitterColor  = parms.getColor("glitterColor",zero);
      const float glitterSpread = parms.getFloat("glitterSpread",1.0f);
      const float eta           = parms.getFloat("eta",1.4f);
      return ispc::MetallicPaint__new((ispc::vec3f&)shadeColor,
                                      (ispc::vec3f&)glitterColor,
                                      glitterSpread,
                                      eta);
    }
  };
}


text:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { NotificationModule } from '../../modules/notification.module';
import { ButtonModule } from '../../modules/button.module';
import { InputModule } from '../../modules/input.module';

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule, CommonModule, FormsModule,
		NotificationModule, ButtonModule, InputModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})

export class AppModule { }


text:
/**
 * Created by Aus on 2017/7/27.
 */
import React from 'react'
import ListTitle from '../../components/DataDisplay/ListTitle/'
import {Checkbox} from '../../components/Form/'
import Tools from '../../components/Tools/Tools'

class CheckboxPage extends React.Component {
    constructor (props) {
        super(props);
        this.state = {
            value1: {required: true, labelName: '单选', value: ['cherry']},
            value2: {required: true, readOnly: true, labelName: '整个readonly', value: ['apple', 'banana', 'cherry', 'date']}
        };
    }
    handleChange (type, value) {
        this.setState((previousState)=>{
            previousState[type] = Object.assign(previousState[type], value);
            return {...previousState}
        });
    }
    render () {
        const {value1, value2} = this.state;
        const options1 = [
            {label: '苹果', value: 'apple'}, {label: '香蕉', value: 'banana'},
            {label: '樱桃', value: 'cherry', disabled: true}, {label: '枣', value: 'date'}
        ];

        return (

                    {Tools.linkTo('/index')}} />
                    Checkbox

                <ListTitle title="普通" />

                    <Checkbox
                        options={options1}
                        {...value1}
                        onChange={this.handleChange.bind(this, 'value1')}
                    />
                    <Checkbox
                        options={options1}
                        {...value2}
                    />

        )
    }
}

export default CheckboxPage


text:
<?php

declare(strict_types = 1);

namespace DataTables\Table;

use Cake\Error\FatalErrorException;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;

/**
 * Class Tables
 *
 * @author   Allan Carvalho <allan.m.carvalho@outlook.com>
 * @license  MIT License https://github.com/allanmcarvalho/cakephp-datatables/blob/master/LICENSE
 * @link     https://github.com/allanmcarvalho/cakephp-datatables
 */
abstract class Tables {

	/**
	 * The database table name that will be used to load the DataTables ORM table.
	 *
	 * @var string
	 */
	protected $_ormTableName;

	/**
	 * @var \Cake\ORM\Table
	 */
	private $_ormTable;

	public function __construct() {
		$className = get_called_class();
		$classShortName = explode('\\', get_called_class());
		$classShortName = array_pop($classShortName);
		if (substr($classShortName, -6, 6) !== 'Tables') {
			throw new FatalErrorException("The class '$className' must have the name ending with 'Tables'");
		}
		if (empty($this->_ormTableName)) {
			$this->_ormTableName = substr_replace($classShortName, '', -6, 6);
		}
	}

	/**
	 * @return \Cake\ORM\Table
	 */
	public function getOrmTable(): Table {
		return TableRegistry::getTableLocator()->get($this->_ormTableName);
	}

}


text:
/**
 * @file main.c
 * \n Source File
 * \n Outpour MSP430 Firmware
 *
 * \brief Main entry and init routines
 */

// Includes
#include "outpour.h"

/***************************
 * Module Data Definitions
 **************************/

/**************************
 * Module Prototypes
 **************************/

/***************************
 * Module Public Functions
 **************************/

/**
* \brief "C" entry point
*
* @return int Ignored
*/
int main(void) {

    WDTCTL = WDTPW | WDTHOLD;   // Stop watchdog timer

    // Perform Hardware Initialization
    clock_init();
    pin_init();
    uart_init();

    // Call sys exec and never return.
    sysExec_exec();

    // System should never reach this point in execution.
    // But just in case.....
    disableGlobalInterrupt();
    // Force watchdog reset
    WDTCTL = 0xDEAD;
    while (1);
}

/**********************
 * Private Functions
 **********************/

/**
* \brief sys_error
* \brief A catastrophic situation has occured.  Restart system.
*/
void sysError(void) {
#if 0
    // For development, loop infinitely.
    while (1);
#else
    // Reset system
    // Force watchdog reset
    WDTCTL = 0xDEAD;
    while (1);
#endif
}

#ifdef FOR_USE_WITH_BOOTLOADER

//
//  External ISR prototypes used by ProxyVectorTable
//
extern __interrupt void ISR_Timer1_A0(void);
extern __interrupt void USCI0TX_ISR(void);
extern __interrupt void USCI0RX_ISR(void);
extern __interrupt void watchdog_timer(void);

/******************************************************************************
 *
 * @brief   Dummy Interrupt service routine
 *  This ISR will be executed if an undeclared interrupt is called
 *
 * @return  none
 *****************************************************************************/
__interrupt void Dummy_Isr(void)
{
    // Something catastrophic has happened.
    // Erase the application record so that the bootloader will go into SOS mode.
    msp430Flash_erase_segment(APR_LOCATION);
    // Force watchdog reset
    WDTCTL = 0xDEAD;
    while(1);
}

/**
 * \var ProxyVectorTable
 *
 * \brief This is a "proxy" interrupt table which is used by the
 *         bootloader to jump to each interrupt routine in the
 *         application.  This technique is based on a TI
 *         bootloader design.  Please see document SLAA600A for
 *         a description of this scheme.  Note that if an
 *         interrupt vector is not used by the application, the
 *         Dummy_Isr function pointer is used.  Currently the
 *         only interrupts used by the application are the
 *         timer and UART rx/tx.
 *
 * \brief Some details about the proxy table;
 * \li It always resides in the same location as specified in
 *     the linker command file.  The location must be known by
 *     the bootloader.
 * \li It contains a BRA instruction (0x4030) followed by the
 *     address of each ISR processing routine.  The bootloader
 *     jumps to the application ISR routine by jumping to the
 *     location associated with the hardware interrupt in the
 *     table.
 * \li Note that the number and location of each vector should
 *     match the declaration in Boot's Vector_Table
 */

#   ifdef __IAR_SYSTEMS_ICC__
#       pragma location="APP_PROXY_VECTORS"
__root const uint16_t ProxyVectorTable[] =
#   elif defined (__TI_COMPILER_VERSION__)
#       pragma DATA_SECTION(ProxyVectorTable, ".APP_PROXY_VECTORS")
#       pragma RETAIN(ProxyVectorTable)
const uint16_t ProxyVectorTable[] =
#   endif
{
    0x4030, (uint16_t) Dummy_Isr,           // APP_PROXY_VECTOR(0) P1
    0x4030, (uint16_t) Dummy_Isr,           // APP_PROXY_VECTOR(1) P2
    0x4030, (uint16_t) Dummy_Isr,           // APP_PROXY_VECTOR(2) ADC10
    0x4030, (uint16_t) USCI0TX_ISR,         // APP_PROXY_VECTOR(3) USCI I2C TX/RX
    0x4030, (uint16_t) USCI0RX_ISR,         // APP_PROXY_VECTOR(4) USCI I2C STAT
    0x4030, (uint16_t) Dummy_Isr,           // APP_PROXY_VECTOR(5) TA0_1
    0x4030, (uint16_t) Dummy_Isr,           // APP_PROXY_VECTOR(6) T0_0
    0x4030, (uint16_t) watchdog_timer,      // APP_PROXY_VECTOR(7) WDT
    0x4030, (uint16_t) Dummy_Isr,           // APP_PROXY_VECTOR(8) COMP_A
    0x4030, (uint16_t) Dummy_Isr,           // APP_PROXY_VECTOR(9) TA1_1
    0x4030, (uint16_t) ISR_Timer1_A0,       // APP_PROXY_VECTOR(10) TA1_0
    0x4030, (uint16_t) Dummy_Isr,           // APP_PROXY_VECTOR(11) NMI
};
#endif

/******************************
 * Doxygen Support Defines
 ******************************/

/**
* \defgroup PUBLIC_API Public API
* \brief Public API's are functions called by other C modules to
*        initiate some type of work or set/get data in the
*        module.
*/

/**
* \defgroup SYSTEM_INIT_API System and Module Initialization API
* \brief These routines are called once at system start to
*        initialize data and/or hardware.  Each main processing
*        module in the system has its own initialization
*        routine.
*/

/**
* \defgroup EXEC_ROUTINE Top Level Processing Routines.
* \brief Exec routines are called on each iteration of the main
*        processing loop for the software.  They are responsible
*        for "orchestrating" the specific functionality of a
*        specific module in the system.  Because the system does
*        not have multiple threads, all work must be done in a
*        piece meal fashion using state machine processing by
*        each Exec as needed.
*/

/**
* \defgroup ISR Interrupt Handler API
* \brief Interrupt handler for the system.  Currently there are
*        three types used:  UART, A0 Timer and Watchdog timer.
*        \li The Uart has an individual ISR for transmit and
*        receive.
*        \li The A0 Timer interrupt is a one second tick timer
*        used to bring the system out of low power mode and
*        initiate the main loop processing.
*        \li The Watchdog timer interrupt is used as part of the
*        Capacitive touch processing.
*/


text:
<?php
namespace ChrisAndChris\Common\RowMapperBundle\Entity;

/**
 * A strict entity is an entity requiring all fields to get populated
 *
 * @name StrictEntity
 * @version    1.0.0
 * @since      v2.1.1
 * @package    RowMapperBundle
 * @author     ChrisAndChris
 * @link       https://github.com/chrisandchris
 */
interface StrictEntity extends Entity
{

}


text:
gem 'rspec', '~> 2.4'
require 'rspec'
require 'nginx/manager/version'

include Nginx::Manager


text:
/**  A one line description of the class.
 *
 * #include UnitekController.hpp
 * Created 09-30-17 By: Smitty
 *
 * A longer description.
 */

#ifndef UNITEKCONTROLLER_HPP
#define UNITEKCONTROLLER_HPP

#include <Arduino.h>
#include "UnitekRegisters.hpp"

class UnitekController
{
public:
  UnitekController(void);

  uint8_t testFunc(void);

  // TODO: implement/refactor
  // CAN_message_t setupMCMessage(uint8_t regID, uint8_t buf1, uint8_t buf2 = 0x00, bool polling = false);

};

#endif  //UNITEKCONTROLLER_HPP


text:
/*
 * This file handles the architecture-dependent parts of process handling..
 */

#include <linux/cpu.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/elfcore.h>
#include <linux/smp.h>
#include <linux/slab.h>
#include <linux/user.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/ptrace.h>
#include <linux/notifier.h>
#include <linux/kprobes.h>
#include <linux/kdebug.h>
#include <linux/prctl.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include <linux/ftrace.h>

#include <asm/pgtable.h>
#include <asm/processor.h>
#include <asm/fpu/internal.h>
#include <asm/mmu_context.h>
#include <asm/prctl.h>
#include <asm/desc.h>
#include <asm/proto.h>
#include <asm/ia32.h>
#include <asm/idle.h>
#include <asm/syscalls.h>
#include <asm/debugreg.h>
#include <asm/switch_to.h>

asmlinkage extern void ret_from_fork(void);

__visible DEFINE_PER_CPU(unsigned long, rsp_scratch);

/* Prints also some state that isn't saved in the pt_regs */
void __show_regs(struct pt_regs *regs, int all)
{
	unsigned long cr0 = 0L, cr2 = 0L, cr3 = 0L, cr4 = 0L, fs, gs, shadowgs;
	unsigned long d0, d1, d2, d3, d6, d7;
	unsigned int fsindex, gsindex;
	unsigned int ds, cs, es;

	printk(KERN_DEFAULT "RIP: %04lx:[<%016lx>] ", regs->cs & 0xffff, regs->ip);
	printk_address(regs->ip);
	printk(KERN_DEFAULT "RSP: %04lx:%016lx  EFLAGS: %08lx\n", regs->ss,
			regs->sp, regs->flags);
	printk(KERN_DEFAULT "RAX: %016lx RBX: %016lx RCX: %016lx\n",
	       regs->ax, regs->bx, regs->cx);
	printk(KERN_DEFAULT "RDX: %016lx RSI: %016lx RDI: %016lx\n",
	       regs->dx, regs->si, regs->di);
	printk(KERN_DEFAULT "RBP: %016lx R08: %016lx R09: %016lx\n",
	       regs->bp, regs->r8, regs->r9);
	printk(KERN_DEFAULT "R10: %016lx R11: %016lx R12: %016lx\n",
	       regs->r10, regs->r11, regs->r12);
	printk(KERN_DEFAULT "R13: %016lx R14: %016lx R15: %016lx\n",
	       regs->r13, regs->r14, regs->r15);

	asm("movl %%ds,%0" : "=r" (ds));
	asm("movl %%cs,%0" : "=r" (cs));
	asm("movl %%es,%0" : "=r" (es));
	asm("movl %%fs,%0" : "=r" (fsindex));
	asm("movl %%gs,%0" : "=r" (gsindex));

	rdmsrl(MSR_FS_BASE, fs);
	rdmsrl(MSR_GS_BASE, gs);
	rdmsrl(MSR_KERNEL_GS_BASE, shadowgs);

	if (!all)
		return;

	cr0 = read_cr0();
	cr2 = read_cr2();
	cr3 = read_cr3();
	cr4 = __read_cr4();

	printk(KERN_DEFAULT "FS:  %016lx(%04x) GS:%016lx(%04x) knlGS:%016lx\n",
	       fs, fsindex, gs, gsindex, shadowgs);
	printk(KERN_DEFAULT "CS:  %04x DS: %04x ES: %04x CR0: %016lx\n", cs, ds,
			es, cr0);
	printk(KERN_DEFAULT "CR2: %016lx CR3: %016lx CR4: %016lx\n", cr2, cr3,
			cr4);

	get_debugreg(d0, 0);
	get_debugreg(d1, 1);
	get_debugreg(d2, 2);
	get_debugreg(d3, 3);
	get_debugreg(d6, 6);
	get_debugreg(d7, 7);

	/* Only print out debug registers if they are in their non-default state. */
	if ((d0 == 0) && (d1 == 0) && (d2 == 0) && (d3 == 0) &&
	    (d6 == DR6_RESERVED) && (d7 == 0x400))
		return;

	printk(KERN_DEFAULT "DR0: %016lx DR1: %016lx DR2: %016lx\n", d0, d1, d2);
	printk(KERN_DEFAULT "DR3: %016lx DR6: %016lx DR7: %016lx\n", d3, d6, d7);

}

void release_thread(struct task_struct *dead_task)
{
	if (dead_task->mm) {
#ifdef CONFIG_MODIFY_LDT_SYSCALL
		if (dead_task->mm->context.ldt) {
			pr_warn("WARNING: dead process %s still has LDT? <%p/%d>\n",
				dead_task->comm,
				dead_task->mm->context.ldt,
				dead_task->mm->context.ldt->size);
			BUG();
		}
#endif
	}
}

static inline void set_32bit_tls(struct task_struct *t, int tls, u32 addr)
{
	struct user_desc ud = {
		.base_addr = addr,
		.limit = 0xfffff,
		.seg_32bit = 1,
		.limit_in_pages = 1,
		.useable = 1,
	};
	struct desc_struct *desc = t->thread.tls_array;
	desc += tls;
	fill_ldt(desc, &ud);
}

static inline u32 read_32bit_tls(struct task_struct *t, int tls)
{
	return get_desc_base(&t->thread.tls_array[tls]);
}

int copy_thread_tls(unsigned long clone_flags, unsigned long sp,
		unsigned long arg, struct task_struct *p, unsigned long tls)
{
	int err;
	struct pt_regs *childregs;
	struct task_struct *me = current;

	p->thread.sp0 = (unsigned long)task_stack_page(p) + THREAD_SIZE;
	childregs = task_pt_regs(p);
	p->thread.sp = (unsigned long) childregs;
	set_tsk_thread_flag(p, TIF_FORK);
	p->thread.io_bitmap_ptr = NULL;

	savesegment(gs, p->thread.gsindex);
	p->thread.gs = p->thread.gsindex ? 0 : me->thread.gs;
	savesegment(fs, p->thread.fsindex);
	p->thread.fs = p->thread.fsindex ? 0 : me->thread.fs;
	savesegment(es, p->thread.es);
	savesegment(ds, p->thread.ds);
	memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps));

	if (unlikely(p->flags & PF_KTHREAD)) {
		/* kernel thread */
		memset(childregs, 0, sizeof(struct pt_regs));
		childregs->sp = (unsigned long)childregs;
		childregs->ss = __KERNEL_DS;
		childregs->bx = sp; /* function */
		childregs->bp = arg;
		childregs->orig_ax = -1;
		childregs->cs = __KERNEL_CS | get_kernel_rpl();
		childregs->flags = X86_EFLAGS_IF | X86_EFLAGS_FIXED;
		return 0;
	}
	*childregs = *current_pt_regs();

	childregs->ax = 0;
	if (sp)
		childregs->sp = sp;

	err = -ENOMEM;
	if (unlikely(test_tsk_thread_flag(me, TIF_IO_BITMAP))) {
		p->thread.io_bitmap_ptr = kmemdup(me->thread.io_bitmap_ptr,
						  IO_BITMAP_BYTES, GFP_KERNEL);
		if (!p->thread.io_bitmap_ptr) {
			p->thread.io_bitmap_max = 0;
			return -ENOMEM;
		}
		set_tsk_thread_flag(p, TIF_IO_BITMAP);
	}

	/*
	 * Set a new TLS for the child thread?
	 */
	if (clone_flags & CLONE_SETTLS) {
#ifdef CONFIG_IA32_EMULATION
		if (is_ia32_task())
			err = do_set_thread_area(p, -1,
				(struct user_desc __user *)tls, 0);
		else
#endif
			err = do_arch_prctl(p, ARCH_SET_FS, tls);
		if (err)
			goto out;
	}
	err = 0;
out:
	if (err && p->thread.io_bitmap_ptr) {
		kfree(p->thread.io_bitmap_ptr);
		p->thread.io_bitmap_max = 0;
	}

	return err;
}

static void
start_thread_common(struct pt_regs *regs, unsigned long new_ip,
		    unsigned long new_sp,
		    unsigned int _cs, unsigned int _ss, unsigned int _ds)
{
	loadsegment(fs, 0);
	loadsegment(es, _ds);
	loadsegment(ds, _ds);
	load_gs_index(0);
	regs->ip		= new_ip;
	regs->sp		= new_sp;
	regs->cs		= _cs;
	regs->ss		= _ss;
	regs->flags		= X86_EFLAGS_IF;
	force_iret();
}

void
start_thread(struct pt_regs *regs, unsigned long new_ip, unsigned long new_sp)
{
	start_thread_common(regs, new_ip, new_sp,
			    __USER_CS, __USER_DS, 0);
}

#ifdef CONFIG_COMPAT
void compat_start_thread(struct pt_regs *regs, u32 new_ip, u32 new_sp)
{
	start_thread_common(regs, new_ip, new_sp,
			    test_thread_flag(TIF_X32)
			    ? __USER_CS : __USER32_CS,
			    __USER_DS, __USER_DS);
}
#endif

/*
 *	switch_to(x,y) should switch tasks from x to y.
 *
 * This could still be optimized:
 * - fold all the options into a flag word and test it with a single test.
 * - could test fs/gs bitsliced
 *
 * Kprobes not supported here. Set the probe on schedule instead.
 * Function graph tracer not supported too.
 */
__visible __notrace_funcgraph struct task_struct *
__switch_to(struct task_struct *prev_p, struct task_struct *next_p)
{
	struct thread_struct *prev = &prev_p->thread;
	struct thread_struct *next = &next_p->thread;
	struct fpu *prev_fpu = &prev->fpu;
	struct fpu *next_fpu = &next->fpu;
	int cpu = smp_processor_id();
	struct tss_struct *tss = &per_cpu(cpu_tss, cpu);
	unsigned fsindex, gsindex;
	fpu_switch_t fpu_switch;

	fpu_switch = switch_fpu_prepare(prev_fpu, next_fpu, cpu);

	/* We must save %fs and %gs before load_TLS() because
	 * %fs and %gs may be cleared by load_TLS().
	 *
	 * (e.g. xen_load_tls())
	 */
	savesegment(fs, fsindex);
	savesegment(gs, gsindex);

	/*
	 * Load TLS before restoring any segments so that segment loads
	 * reference the correct GDT entries.
	 */
	load_TLS(next, cpu);

	/*
	 * Leave lazy mode, flushing any hypercalls made here.  This
	 * must be done after loading TLS entries in the GDT but before
	 * loading segments that might reference them, and and it must
	 * be done before fpu__restore(), so the TS bit is up to
	 * date.
	 */
	arch_end_context_switch(next_p);

	/* Switch DS and ES.
	 *
	 * Reading them only returns the selectors, but writing them (if
	 * nonzero) loads the full descriptor from the GDT or LDT.  The
	 * LDT for next is loaded in switch_mm, and the GDT is loaded
	 * above.
	 *
	 * We therefore need to write new values to the segment
	 * registers on every context switch unless both the new and old
	 * values are zero.
	 *
	 * Note that we don't need to do anything for CS and SS, as
	 * those are saved and restored as part of pt_regs.
	 */
	savesegment(es, prev->es);
	if (unlikely(next->es | prev->es))
		loadsegment(es, next->es);

	savesegment(ds, prev->ds);
	if (unlikely(next->ds | prev->ds))
		loadsegment(ds, next->ds);

	/*
	 * Switch FS and GS.
	 *
	 * These are even more complicated than FS and GS: they have
	 * 64-bit bases are that controlled by arch_prctl.  Those bases
	 * only differ from the values in the GDT or LDT if the selector
	 * is 0.
	 *
	 * Loading the segment register resets the hidden base part of
	 * the register to 0 or the value from the GDT / LDT.  If the
	 * next base address zero, writing 0 to the segment register is
	 * much faster than using wrmsr to explicitly zero the base.
	 *
	 * The thread_struct.fs and thread_struct.gs values are 0
	 * if the fs and gs bases respectively are not overridden
	 * from the values implied by fsindex and gsindex.  They
	 * are nonzero, and store the nonzero base addresses, if
	 * the bases are overridden.
	 *
	 * (fs != 0 && fsindex != 0) || (gs != 0 && gsindex != 0) should
	 * be impossible.
	 *
	 * Therefore we need to reload the segment registers if either
	 * the old or new selector is nonzero, and we need to override
	 * the base address if next thread expects it to be overridden.
	 *
	 * This code is unnecessarily slow in the case where the old and
	 * new indexes are zero and the new base is nonzero -- it will
	 * unnecessarily write 0 to the selector before writing the new
	 * base address.
	 *
	 * Note: This all depends on arch_prctl being the only way that
	 * user code can override the segment base.  Once wrfsbase and
	 * wrgsbase are enabled, most of this code will need to change.
	 */
	if (unlikely(fsindex | next->fsindex | prev->fs)) {
		loadsegment(fs, next->fsindex);

		/*
		 * If user code wrote a nonzero value to FS, then it also
		 * cleared the overridden base address.
		 *
		 * XXX: if user code wrote 0 to FS and cleared the base
		 * address itself, we won't notice and we'll incorrectly
		 * restore the prior base address next time we reschdule
		 * the process.
		 */
		if (fsindex)
			prev->fs = 0;
	}
	if (next->fs)
		wrmsrl(MSR_FS_BASE, next->fs);
	prev->fsindex = fsindex;

	if (unlikely(gsindex | next->gsindex | prev->gs)) {
		load_gs_index(next->gsindex);

		/* This works (and fails) the same way as fsindex above. */
		if (gsindex)
			prev->gs = 0;
	}
	if (next->gs)
		wrmsrl(MSR_KERNEL_GS_BASE, next->gs);
	prev->gsindex = gsindex;

	switch_fpu_finish(next_fpu, fpu_switch);

	/*
	 * Switch the PDA and FPU contexts.
	 */
	this_cpu_write(current_task, next_p);

	/*
	 * If it were not for PREEMPT_ACTIVE we could guarantee that the
	 * preempt_count of all tasks was equal here and this would not be
	 * needed.
	 */
	task_thread_info(prev_p)->saved_preempt_count = this_cpu_read(__preempt_count);
	this_cpu_write(__preempt_count, task_thread_info(next_p)->saved_preempt_count);

	/* Reload esp0 and ss1.  This changes current_thread_info(). */
	load_sp0(tss, next);

	/*
	 * Now maybe reload the debug registers and handle I/O bitmaps
	 */
	if (unlikely(task_thread_info(next_p)->flags & _TIF_WORK_CTXSW_NEXT ||
		     task_thread_info(prev_p)->flags & _TIF_WORK_CTXSW_PREV))
		__switch_to_xtra(prev_p, next_p, tss);

	if (static_cpu_has_bug(X86_BUG_SYSRET_SS_ATTRS)) {
		/*
		 * AMD CPUs have a misfeature: SYSRET sets the SS selector but
		 * does not update the cached descriptor.  As a result, if we
		 * do SYSRET while SS is NULL, we'll end up in user mode with
		 * SS apparently equal to __USER_DS but actually unusable.
		 *
		 * The straightforward workaround would be to fix it up just
		 * before SYSRET, but that would slow down the system call
		 * fast paths.  Instead, we ensure that SS is never NULL in
		 * system call context.  We do this by replacing NULL SS
		 * selectors at every context switch.  SYSCALL sets up a valid
		 * SS, so the only way to get NULL is to re-enter the kernel
		 * from CPL 3 through an interrupt.  Since that can't happen
		 * in the same task as a running syscall, we are guaranteed to
		 * context switch between every interrupt vector entry and a
		 * subsequent SYSRET.
		 *
		 * We read SS first because SS reads are much faster than
		 * writes.  Out of caution, we force SS to __KERNEL_DS even if
		 * it previously had a different non-NULL value.
		 */
		unsigned short ss_sel;
		savesegment(ss, ss_sel);
		if (ss_sel != __KERNEL_DS)
			loadsegment(ss, __KERNEL_DS);
	}

	return prev_p;
}

void set_personality_64bit(void)
{
	/* inherit personality from parent */

	/* Make sure to be in 64bit mode */
	clear_thread_flag(TIF_IA32);
	clear_thread_flag(TIF_ADDR32);
	clear_thread_flag(TIF_X32);

	/* Ensure the corresponding mm is not marked. */
	if (current->mm)
		current->mm->context.ia32_compat = 0;

	/* TBD: overwrites user setup. Should have two bits.
	   But 64bit processes have always behaved this way,
	   so it's not too bad. The main problem is just that
	   32bit childs are affected again. */
	current->personality &= ~READ_IMPLIES_EXEC;
}

void set_personality_ia32(bool x32)
{
	/* inherit personality from parent */

	/* Make sure to be in 32bit mode */
	set_thread_flag(TIF_ADDR32);

	/* Mark the associated mm as containing 32-bit tasks. */
	if (x32) {
		clear_thread_flag(TIF_IA32);
		set_thread_flag(TIF_X32);
		if (current->mm)
			current->mm->context.ia32_compat = TIF_X32;
		current->personality &= ~READ_IMPLIES_EXEC;
		/* is_compat_task() uses the presence of the x32
		   syscall bit flag to determine compat status */
		current_thread_info()->status &= ~TS_COMPAT;
	} else {
		set_thread_flag(TIF_IA32);
		clear_thread_flag(TIF_X32);
		if (current->mm)
			current->mm->context.ia32_compat = TIF_IA32;
		current->personality |= force_personality32;
		/* Prepare the first "return" to user space */
		current_thread_info()->status |= TS_COMPAT;
	}
}
EXPORT_SYMBOL_GPL(set_personality_ia32);

long do_arch_prctl(struct task_struct *task, int code, unsigned long addr)
{
	int ret = 0;
	int doit = task == current;
	int cpu;

	switch (code) {
	case ARCH_SET_GS:
		if (addr >= TASK_SIZE_OF(task))
			return -EPERM;
		cpu = get_cpu();
		/* handle small bases via the GDT because that's faster to
		   switch. */
		if (addr <= 0xffffffff) {
			set_32bit_tls(task, GS_TLS, addr);
			if (doit) {
				load_TLS(&task->thread, cpu);
				load_gs_index(GS_TLS_SEL);
			}
			task->thread.gsindex = GS_TLS_SEL;
			task->thread.gs = 0;
		} else {
			task->thread.gsindex = 0;
			task->thread.gs = addr;
			if (doit) {
				load_gs_index(0);
				ret = wrmsrl_safe(MSR_KERNEL_GS_BASE, addr);
			}
		}
		put_cpu();
		break;
	case ARCH_SET_FS:
		/* Not strictly needed for fs, but do it for symmetry
		   with gs */
		if (addr >= TASK_SIZE_OF(task))
			return -EPERM;
		cpu = get_cpu();
		/* handle small bases via the GDT because that's faster to
		   switch. */
		if (addr <= 0xffffffff) {
			set_32bit_tls(task, FS_TLS, addr);
			if (doit) {
				load_TLS(&task->thread, cpu);
				loadsegment(fs, FS_TLS_SEL);
			}
			task->thread.fsindex = FS_TLS_SEL;
			task->thread.fs = 0;
		} else {
			task->thread.fsindex = 0;
			task->thread.fs = addr;
			if (doit) {
				/* set the selector to 0 to not confuse
				   __switch_to */
				loadsegment(fs, 0);
				ret = wrmsrl_safe(MSR_FS_BASE, addr);
			}
		}
		put_cpu();
		break;
	case ARCH_GET_FS: {
		unsigned long base;
		if (task->thread.fsindex == FS_TLS_SEL)
			base = read_32bit_tls(task, FS_TLS);
		else if (doit)
			rdmsrl(MSR_FS_BASE, base);
		else
			base = task->thread.fs;
		ret = put_user(base, (unsigned long __user *)addr);
		break;
	}
	case ARCH_GET_GS: {
		unsigned long base;
		unsigned gsindex;
		if (task->thread.gsindex == GS_TLS_SEL)
			base = read_32bit_tls(task, GS_TLS);
		else if (doit) {
			savesegment(gs, gsindex);
			if (gsindex)
				rdmsrl(MSR_KERNEL_GS_BASE, base);
			else
				base = task->thread.gs;
		} else
			base = task->thread.gs;
		ret = put_user(base, (unsigned long __user *)addr);
		break;
	}

	default:
		ret = -EINVAL;
		break;
	}

	return ret;
}

long sys_arch_prctl(int code, unsigned long addr)
{
	return do_arch_prctl(current, code, addr);
}

unsigned long KSTK_ESP(struct task_struct *task)
{
	return task_pt_regs(task)->sp;
}


text:
<?php

declare(strict_types=1);

namespace Bindto\Converter;

use Bindto\Annotation\ConvertAnnotationInterface;
use Bindto\Mapper\ConvertingObjectMapper;
use Symfony\Component\OptionsResolver\OptionsResolver;

class NestedObjectConverter extends AbstractConverter
{
    /**
     * @var ConvertingObjectMapper
     */
    private $parentMapper;

    public function __construct(ConvertingObjectMapper $parentMapper)
    {
        $this->parentMapper = $parentMapper;
    }

    /**
     * {@inheritdoc}
     */
    public function apply($value, $propertyName, array $options, $from, array $metadata)
    {
        $options = $this->resolveOptions($options);

        $this->parentMapper->enterNestedExceptionStack($propertyName);
        {
            $result = $this->parentMapper->map($value, new $options['class'](), $metadata);
        }
        $this->parentMapper->exitNestedExceptionStack();

        return $result;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'class' => null,
        ]);
        $resolver->addAllowedTypes('class', ['string']);
    }

    /**
     * {@inheritdoc}
     */
    public function canProduceType(string $type): bool
    {
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function supportsAnnotation(ConvertAnnotationInterface $annotation): bool
    {
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function autoconfigure(ConvertAnnotationInterface $sourceAnnotation, string $typeName, bool $isArray, bool $isNullable): array
    {
        return [];
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cocos2D;

namespace tests
{
    public class SpriteChildrenVisibility : SpriteTestDemo
    {
        public SpriteChildrenVisibility()
        {
            CCSize s = CCDirector.SharedDirector.WinSize;

            CCSpriteFrameCache.SharedSpriteFrameCache.AddSpriteFramesWithFile("animations/grossini.plist");

            CCNode aParent;
            CCSprite sprite1, sprite2, sprite3;
            //
            // SpriteBatchNode
            //
            // parents
            aParent = new CCSpriteBatchNode("animations/grossini", 50);
            aParent.Position = (new CCPoint(s.Width / 3, s.Height / 2));
            AddChild(aParent, 0);

            sprite1 = new CCSprite("grossini_dance_01.png");
            sprite1.Position = (new CCPoint(0, 0));

            sprite2 = new CCSprite("grossini_dance_02.png");
            sprite2.Position = (new CCPoint(20, 30));

            sprite3 = new CCSprite("grossini_dance_03.png");
            sprite3.Position = (new CCPoint(-20, 30));

            aParent.AddChild(sprite1);
            sprite1.AddChild(sprite2, -2);
            sprite1.AddChild(sprite3, 2);

            sprite1.RunAction(new CCBlink (5, 10));

            //
            // Sprite
            //
            aParent = new CCNode ();
            aParent.Position = (new CCPoint(2 * s.Width / 3, s.Height / 2));
            AddChild(aParent, 0);

            sprite1 = new CCSprite("grossini_dance_01.png");
            sprite1.Position = (new CCPoint(0, 0));

            sprite2 = new CCSprite("grossini_dance_02.png");
            sprite2.Position = (new CCPoint(20, 30));

            sprite3 = new CCSprite("grossini_dance_03.png");
            sprite3.Position = (new CCPoint(-20, 30));

            aParent.AddChild(sprite1);
            sprite1.AddChild(sprite2, -2);
            sprite1.AddChild(sprite3, 2);

            sprite1.RunAction(new CCBlink (5, 10));
        }

        public override void OnExit()
        {
            base.OnExit();
            CCSpriteFrameCache.SharedSpriteFrameCache.RemoveUnusedSpriteFrames();
        }

        public override string title()
        {
            return "Sprite & SpriteBatchNode Visibility";
        }
    }
}