text:
/* This file contains the implementation of the OTARequestorInterface class. All the core
 * OTA Requestor logic is contained in this class.
 */

#include <app/clusters/basic/basic.h>
#include <app/clusters/ota-requestor/ota-requestor-server.h>
#include <lib/core/CHIPEncoding.h>
#include <platform/CHIPDeviceLayer.h>
#include <platform/DeviceInstanceInfoProvider.h>
#include <platform/OTAImageProcessor.h>
#include <protocols/bdx/BdxUri.h>
#include <zap-generated/CHIPClusters.h>

#include "BDXDownloader.h"
#include "DefaultOTARequestor.h"

namespace chip {

using namespace app;
using namespace app::Clusters;
using namespace app::Clusters::OtaSoftwareUpdateProvider;
using namespace app::Clusters::OtaSoftwareUpdateProvider::Commands;
using namespace app::Clusters::OtaSoftwareUpdateRequestor;
using namespace app::Clusters::OtaSoftwareUpdateRequestor::Commands;
using namespace app::Clusters::OtaSoftwareUpdateRequestor::Structs;
using app::DataModel::Nullable;
using bdx::TransferSession;
using Protocols::InteractionModel::Status;

// Global instance of the OTARequestorInterface.
OTARequestorInterface * globalOTARequestorInstance = nullptr;

// Abort the QueryImage download request if there's been no progress for 5 minutes
static constexpr System::Clock::Timeout kDownloadTimeoutSec = chip::System::Clock::Seconds32(5 * 60);

static void LogQueryImageResponse(const QueryImageResponse::DecodableType & response)
{
    ChipLogDetail(SoftwareUpdate, "QueryImageResponse:");
    ChipLogDetail(SoftwareUpdate, "  status: %u", to_underlying(response.status));
    if (response.delayedActionTime.HasValue())
    {
        ChipLogDetail(SoftwareUpdate, "  delayedActionTime: %" PRIu32 " seconds", response.delayedActionTime.Value());
    }
    if (response.imageURI.HasValue())
    {
        ChipLogDetail(SoftwareUpdate, "  imageURI: %.*s", static_cast<int>(response.imageURI.Value().size()),
                      response.imageURI.Value().data());
    }
    if (response.softwareVersion.HasValue())
    {
        ChipLogDetail(SoftwareUpdate, "  softwareVersion: %" PRIu32 "", response.softwareVersion.Value());
    }
    if (response.softwareVersionString.HasValue())
    {
        ChipLogDetail(SoftwareUpdate, "  softwareVersionString: %.*s",
                      static_cast<int>(response.softwareVersionString.Value().size()),
                      response.softwareVersionString.Value().data());
    }
    if (response.updateToken.HasValue())
    {
        ChipLogDetail(SoftwareUpdate, "  updateToken: %u", static_cast<unsigned int>(response.updateToken.Value().size()));
    }
    if (response.userConsentNeeded.HasValue())
    {
        ChipLogDetail(SoftwareUpdate, "  userConsentNeeded: %d", response.userConsentNeeded.Value());
    }
    if (response.metadataForRequestor.HasValue())
    {
        ChipLogDetail(SoftwareUpdate, "  metadataForRequestor: %u",
                      static_cast<unsigned int>(response.metadataForRequestor.Value().size()));
    }
}

static void LogApplyUpdateResponse(const ApplyUpdateResponse::DecodableType & response)
{
    ChipLogDetail(SoftwareUpdate, "ApplyUpdateResponse:");
    ChipLogDetail(SoftwareUpdate, "  action: %u", to_underlying(response.action));
    ChipLogDetail(SoftwareUpdate, "  delayedActionTime: %" PRIu32 " seconds", response.delayedActionTime);
}

void SetRequestorInstance(OTARequestorInterface * instance)
{
    globalOTARequestorInstance = instance;
}

OTARequestorInterface * GetRequestorInstance()
{
    return globalOTARequestorInstance;
}

void DefaultOTARequestor::InitState(intptr_t context)
{
    DefaultOTARequestor * requestorCore = reinterpret_cast<DefaultOTARequestor *>(context);
    VerifyOrDie(requestorCore != nullptr);

    // This initialization may occur due to the following:
    //   1) Regular boot up - the states should already be correct
    //   2) Reboot from applying an image - once the image has been confirmed, the provider will be notified of the new version and
    //   all relevant states will reset for a new OTA update. If the image cannot be confirmed, the driver will be responsible for
    //   resetting the states appropriately, including the current update state.
    OtaRequestorServerSetUpdateState(requestorCore->mCurrentUpdateState);
    OtaRequestorServerSetUpdateStateProgress(app::DataModel::NullNullable);
}

CHIP_ERROR DefaultOTARequestor::Init(Server & server, OTARequestorStorage & storage, OTARequestorDriver & driver,
                                     BDXDownloader & downloader)
{
    mServer             = &server;
    mCASESessionManager = server.GetCASESessionManager();
    mStorage            = &storage;
    mOtaRequestorDriver = &driver;
    mBdxDownloader      = &downloader;

    ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSoftwareVersion(mCurrentVersion));

    // Load data from KVS
    LoadCurrentUpdateInfo();

    // Schedule the initializations that needs to be performed in the CHIP context
    DeviceLayer::PlatformMgr().ScheduleWork(InitState, reinterpret_cast<intptr_t>(this));

    return chip::DeviceLayer::PlatformMgrImpl().AddEventHandler(OnCommissioningCompleteRequestor, reinterpret_cast<intptr_t>(this));
}

void DefaultOTARequestor::OnQueryImageResponse(void * context, const QueryImageResponse::DecodableType & response)
{
    LogQueryImageResponse(response);

    DefaultOTARequestor * requestorCore = static_cast<DefaultOTARequestor *>(context);
    VerifyOrDie(requestorCore != nullptr);

    switch (response.status)
    {
    case OTAQueryStatus::kUpdateAvailable: {
        UpdateDescription update;
        CHIP_ERROR err = requestorCore->ExtractUpdateDescription(response, update);

        if (err != CHIP_NO_ERROR)
        {
            ChipLogError(SoftwareUpdate, "QueryImageResponse contains invalid fields: %" CHIP_ERROR_FORMAT, err.Format());
            requestorCore->RecordErrorUpdateState(err);
            return;
        }

        // This should never happen since receiving a response implies that a CASE session had previously been established with a
        // valid provider
        if (!requestorCore->mProviderLocation.HasValue())
        {
            ChipLogError(SoftwareUpdate, "No provider location set");
            requestorCore->RecordErrorUpdateState(CHIP_ERROR_INCORRECT_STATE);
            return;
        }

        // The Operational Node ID in the host field SHALL match the NodeID of the OTA Provider responding with the
        // QueryImageResponse
        if (update.nodeId != requestorCore->mProviderLocation.Value().providerNodeID)
        {
            ChipLogError(SoftwareUpdate,
                         "The ImageURI provider node 0x" ChipLogFormatX64
                         " does not match the QueryImageResponse provider node 0x" ChipLogFormatX64,
                         ChipLogValueX64(update.nodeId), ChipLogValueX64(requestorCore->mProviderLocation.Value().providerNodeID));
            requestorCore->RecordErrorUpdateState(CHIP_ERROR_WRONG_NODE_ID);
            return;
        }

        if (update.softwareVersion > requestorCore->mCurrentVersion)
        {
            ChipLogDetail(SoftwareUpdate, "Update available from version %" PRIu32 " to %" PRIu32, requestorCore->mCurrentVersion,
                          update.softwareVersion);
            MutableByteSpan updateToken(requestorCore->mUpdateTokenBuffer);
            // This function copies the bytespan to mutablebytespan only if size of mutablebytespan buffer is greater or equal to
            // bytespan otherwise we are copying data upto available size.
            err = CopySpanToMutableSpan(update.updateToken, updateToken);
            if (err == CHIP_ERROR_BUFFER_TOO_SMALL)
            {
                memset(updateToken.data(), 0, updateToken.size());
                requestorCore->GenerateUpdateToken();
            }
            requestorCore->mTargetVersion = update.softwareVersion;
            requestorCore->mUpdateToken   = updateToken;

            // Store file designator needed for BDX transfers
            MutableCharSpan fileDesignator(requestorCore->mFileDesignatorBuffer);
            if (update.fileDesignator.size() > fileDesignator.size())
            {
                ChipLogError(SoftwareUpdate, "File designator size %u is too large to store",
                             static_cast<unsigned int>(update.fileDesignator.size()));
                requestorCore->RecordErrorUpdateState(CHIP_ERROR_BUFFER_TOO_SMALL);
                return;
            }
            memcpy(fileDesignator.data(), update.fileDesignator.data(), update.fileDesignator.size());
            fileDesignator.reduce_size(update.fileDesignator.size());
            requestorCore->mFileDesignator = fileDesignator;

            requestorCore->mOtaRequestorDriver->UpdateAvailable(update,
                                                                System::Clock::Seconds32(response.delayedActionTime.ValueOr(0)));
        }
        else
        {
            ChipLogDetail(SoftwareUpdate, "Available update version %" PRIu32 " is <= current version %" PRIu32 ", update ignored",
                          update.softwareVersion, requestorCore->mCurrentVersion);

            requestorCore->mOtaRequestorDriver->UpdateNotFound(UpdateNotFoundReason::kUpToDate,
                                                               System::Clock::Seconds32(response.delayedActionTime.ValueOr(0)));
            requestorCore->RecordNewUpdateState(OTAUpdateStateEnum::kIdle, OTAChangeReasonEnum::kSuccess);
        }

        break;
    }
    case OTAQueryStatus::kBusy: {
        CHIP_ERROR status = requestorCore->mOtaRequestorDriver->UpdateNotFound(
            UpdateNotFoundReason::kBusy, System::Clock::Seconds32(response.delayedActionTime.ValueOr(0)));
        if ((status == CHIP_ERROR_MAX_RETRY_EXCEEDED) || (status == CHIP_ERROR_PROVIDER_LIST_EXHAUSTED))
        {
            requestorCore->RecordNewUpdateState(OTAUpdateStateEnum::kIdle, OTAChangeReasonEnum::kSuccess);
        }
        else
        {
            requestorCore->RecordNewUpdateState(OTAUpdateStateEnum::kDelayedOnQuery, OTAChangeReasonEnum::kDelayByProvider);
        }

        break;
    }
    case OTAQueryStatus::kNotAvailable: {
        requestorCore->mOtaRequestorDriver->UpdateNotFound(UpdateNotFoundReason::kNotAvailable,
                                                           System::Clock::Seconds32(response.delayedActionTime.ValueOr(0)));
        requestorCore->RecordNewUpdateState(OTAUpdateStateEnum::kIdle, OTAChangeReasonEnum::kSuccess);
        break;
    }
    default:
        requestorCore->RecordErrorUpdateState(CHIP_ERROR_BAD_REQUEST);
        break;
    }
}

void DefaultOTARequestor::OnQueryImageFailure(void * context, CHIP_ERROR error)
{
    DefaultOTARequestor * requestorCore = static_cast<DefaultOTARequestor *>(context);
    VerifyOrDie(requestorCore != nullptr);

    ChipLogError(SoftwareUpdate, "Received QueryImage failure response: %" CHIP_ERROR_FORMAT, error.Format());

    // A previously valid CASE session may have become invalid
    if (error == CHIP_ERROR_TIMEOUT)
    {
        ChipLogError(SoftwareUpdate, "CASE session may be invalid, tear down session");
        requestorCore->DisconnectFromProvider();
        error = CHIP_ERROR_CONNECTION_CLOSED_UNEXPECTEDLY;
    }

    requestorCore->RecordErrorUpdateState(error);
}

void DefaultOTARequestor::OnApplyUpdateResponse(void * context, const ApplyUpdateResponse::DecodableType & response)
{
    LogApplyUpdateResponse(response);

    DefaultOTARequestor * requestorCore = static_cast<DefaultOTARequestor *>(context);
    VerifyOrDie(requestorCore != nullptr);

    switch (response.action)
    {
    case OTAApplyUpdateAction::kProceed:
        requestorCore->mOtaRequestorDriver->UpdateConfirmed(System::Clock::Seconds32(response.delayedActionTime));
        break;
    case OTAApplyUpdateAction::kAwaitNextAction:
        requestorCore->mOtaRequestorDriver->UpdateSuspended(System::Clock::Seconds32(response.delayedActionTime));
        requestorCore->RecordNewUpdateState(OTAUpdateStateEnum::kDelayedOnApply, OTAChangeReasonEnum::kDelayByProvider);
        break;
    case OTAApplyUpdateAction::kDiscontinue:
        requestorCore->mOtaRequestorDriver->UpdateDiscontinued();
        requestorCore->RecordNewUpdateState(OTAUpdateStateEnum::kIdle, OTAChangeReasonEnum::kSuccess);
        break;
    case OTAApplyUpdateAction::kUnknownEnumValue:
        OnApplyUpdateFailure(context, CHIP_ERROR_INVALID_ARGUMENT);
        break;
    }
}

void DefaultOTARequestor::OnApplyUpdateFailure(void * context, CHIP_ERROR error)
{
    DefaultOTARequestor * requestorCore = static_cast<DefaultOTARequestor *>(context);
    VerifyOrDie(requestorCore != nullptr);

    ChipLogDetail(SoftwareUpdate, "ApplyUpdate failure response %" CHIP_ERROR_FORMAT, error.Format());
    requestorCore->RecordErrorUpdateState(error);
}

void DefaultOTARequestor::OnNotifyUpdateAppliedResponse(void * context, const app::DataModel::NullObjectType & response) {}

void DefaultOTARequestor::OnNotifyUpdateAppliedFailure(void * context, CHIP_ERROR error)
{
    DefaultOTARequestor * requestorCore = static_cast<DefaultOTARequestor *>(context);
    VerifyOrDie(requestorCore != nullptr);

    ChipLogDetail(SoftwareUpdate, "NotifyUpdateApplied failure response %" CHIP_ERROR_FORMAT, error.Format());
    requestorCore->RecordErrorUpdateState(error);
}

void DefaultOTARequestor::Reset()
{
    mProviderLocation.ClearValue();
    mUpdateToken.reduce_size(0);
    RecordNewUpdateState(OTAUpdateStateEnum::kIdle, OTAChangeReasonEnum::kSuccess);
    mTargetVersion = 0;

    // Persist in case of a reboot or crash
    StoreCurrentUpdateInfo();
}

void DefaultOTARequestor::HandleAnnounceOTAProvider(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath,
                                                    const AnnounceOtaProvider::DecodableType & commandData)
{
    VerifyOrReturn(commandObj != nullptr, ChipLogError(SoftwareUpdate, "Invalid commandObj, cannot handle AnnounceOTAProvider"));

    auto & announcementReason = commandData.announcementReason;

    ChipLogProgress(SoftwareUpdate, "OTA Requestor received AnnounceOTAProvider");

    ProviderLocationType providerLocation = { .providerNodeID = commandData.providerNodeId,
                                              .endpoint       = commandData.endpoint,
                                              .fabricIndex    = commandObj->GetAccessingFabricIndex() };

    ChipLogDetail(SoftwareUpdate, "  FabricIndex: %u", providerLocation.fabricIndex);
    ChipLogDetail(SoftwareUpdate, "  ProviderNodeID: 0x" ChipLogFormatX64, ChipLogValueX64(providerLocation.providerNodeID));
    ChipLogDetail(SoftwareUpdate, "  VendorID: 0x%x", commandData.vendorId);
    ChipLogDetail(SoftwareUpdate, "  AnnouncementReason: %u", to_underlying(announcementReason));
    if (commandData.metadataForNode.HasValue())
    {
        ChipLogDetail(SoftwareUpdate, "  MetadataForNode: %u",
                      static_cast<unsigned int>(commandData.metadataForNode.Value().size()));
    }
    ChipLogDetail(SoftwareUpdate, "  Endpoint: %u", providerLocation.endpoint);

    mOtaRequestorDriver->ProcessAnnounceOTAProviders(providerLocation, announcementReason);

    commandObj->AddStatus(commandPath, Status::Success);
}

void DefaultOTARequestor::ConnectToProvider(OnConnectedAction onConnectedAction)
{
    VerifyOrDie(mServer != nullptr);

    if (!mProviderLocation.HasValue())
    {
        ChipLogError(SoftwareUpdate, "Provider location not set");
        RecordErrorUpdateState(CHIP_ERROR_INCORRECT_STATE);
        return;
    }

    const FabricInfo * fabricInfo = mServer->GetFabricTable().FindFabricWithIndex(mProviderLocation.Value().fabricIndex);

    if (fabricInfo == nullptr)
    {
        ChipLogError(SoftwareUpdate, "Cannot find fabric");
        RecordErrorUpdateState(CHIP_ERROR_INCORRECT_STATE);
        return;
    }

    // Set the action to take once connection is successfully established
    mOnConnectedAction = onConnectedAction;

    ChipLogDetail(SoftwareUpdate, "Establishing session to provider node ID 0x" ChipLogFormatX64 " on fabric index %d",
                  ChipLogValueX64(mProviderLocation.Value().providerNodeID), mProviderLocation.Value().fabricIndex);

    mCASESessionManager->FindOrEstablishSession(fabricInfo->GetPeerIdForNode(mProviderLocation.Value().providerNodeID),
                                                &mOnConnectedCallback, &mOnConnectionFailureCallback);
}

void DefaultOTARequestor::DisconnectFromProvider()
{
    VerifyOrDie(mServer != nullptr);

    if (!mProviderLocation.HasValue())
    {
        ChipLogError(SoftwareUpdate, "Provider location not set");
        RecordErrorUpdateState(CHIP_ERROR_INCORRECT_STATE);
        return;
    }

    const FabricInfo * fabricInfo = mServer->GetFabricTable().FindFabricWithIndex(mProviderLocation.Value().fabricIndex);
    if (fabricInfo == nullptr)
    {
        ChipLogError(SoftwareUpdate, "Cannot find fabric");
        RecordErrorUpdateState(CHIP_ERROR_INCORRECT_STATE);
        return;
    }

    PeerId peerID = fabricInfo->GetPeerIdForNode(mProviderLocation.Value().providerNodeID);
    mCASESessionManager->FindExistingSession(peerID)->Disconnect();
    mCASESessionManager->ReleaseSession(peerID);
}

// Requestor is directed to cancel image update in progress. All the Requestor state is
// cleared, UpdateState is reset to Idle
void DefaultOTARequestor::CancelImageUpdate()
{
    mBdxDownloader->EndDownload(CHIP_ERROR_CONNECTION_ABORTED);

    mOtaRequestorDriver->UpdateCancelled();

    Reset();
}

CHIP_ERROR DefaultOTARequestor::GetUpdateStateProgressAttribute(EndpointId endpointId, app::DataModel::Nullable<uint8_t> & progress)
{
    VerifyOrReturnError(OtaRequestorServerGetUpdateStateProgress(endpointId, progress) == EMBER_ZCL_STATUS_SUCCESS,
                        CHIP_ERROR_BAD_REQUEST);
    return CHIP_NO_ERROR;
}

CHIP_ERROR DefaultOTARequestor::GetUpdateStateAttribute(EndpointId endpointId, OTAUpdateStateEnum & state)
{
    VerifyOrReturnError(OtaRequestorServerGetUpdateState(endpointId, state) == EMBER_ZCL_STATUS_SUCCESS, CHIP_ERROR_BAD_REQUEST);
    return CHIP_NO_ERROR;
}

// Called whenever FindOrEstablishSession is successful
void DefaultOTARequestor::OnConnected(void * context, OperationalDeviceProxy * deviceProxy)
{
    DefaultOTARequestor * requestorCore = static_cast<DefaultOTARequestor *>(context);
    VerifyOrDie(requestorCore != nullptr);
    VerifyOrDie(deviceProxy != nullptr);

    switch (requestorCore->mOnConnectedAction)
    {
    case kQueryImage: {
        CHIP_ERROR err = requestorCore->SendQueryImageRequest(*deviceProxy);

        if (err != CHIP_NO_ERROR)
        {
            ChipLogError(SoftwareUpdate, "Failed to send QueryImage command: %" CHIP_ERROR_FORMAT, err.Format());
            requestorCore->RecordErrorUpdateState(err);
            return;
        }
        break;
    }
    case kDownload: {
        CHIP_ERROR err = requestorCore->StartDownload(*deviceProxy);

        if (err != CHIP_NO_ERROR)
        {
            ChipLogError(SoftwareUpdate, "Failed to start download: %" CHIP_ERROR_FORMAT, err.Format());
            requestorCore->RecordErrorUpdateState(err);
            return;
        }
        break;
    }
    case kApplyUpdate: {
        CHIP_ERROR err = requestorCore->SendApplyUpdateRequest(*deviceProxy);

        if (err != CHIP_NO_ERROR)
        {
            ChipLogError(SoftwareUpdate, "Failed to send ApplyUpdate command: %" CHIP_ERROR_FORMAT, err.Format());
            requestorCore->RecordErrorUpdateState(err);
            return;
        }
        break;
    }
    case kNotifyUpdateApplied: {
        CHIP_ERROR err = requestorCore->SendNotifyUpdateAppliedRequest(*deviceProxy);

        if (err != CHIP_NO_ERROR)
        {
            ChipLogError(SoftwareUpdate, "Failed to send NotifyUpdateApplied command: %" CHIP_ERROR_FORMAT, err.Format());
            requestorCore->RecordErrorUpdateState(err);
            return;
        }
        break;
    }
    default:
        break;
    }
}

// Called whenever FindOrEstablishSession fails
void DefaultOTARequestor::OnConnectionFailure(void * context, PeerId peerId, CHIP_ERROR error)
{
    DefaultOTARequestor * requestorCore = static_cast<DefaultOTARequestor *>(context);
    VerifyOrDie(requestorCore != nullptr);

    ChipLogError(SoftwareUpdate, "Failed to connect to node 0x" ChipLogFormatX64 ": %" CHIP_ERROR_FORMAT,
                 ChipLogValueX64(peerId.GetNodeId()), error.Format());

    switch (requestorCore->mOnConnectedAction)
    {
    case kQueryImage:
        requestorCore->RecordErrorUpdateState(error);
        break;
    case kDownload:
        requestorCore->RecordErrorUpdateState(error);
        break;
    case kApplyUpdate:
        requestorCore->RecordErrorUpdateState(error);
        break;
    default:
        break;
    }
}

void DefaultOTARequestor::TriggerImmediateQueryInternal()
{
    // We are now connecting to a provider for the purpose of sending a QueryImage,
    // treat this as a move to the Querying state
    RecordNewUpdateState(OTAUpdateStateEnum::kQuerying, OTAChangeReasonEnum::kSuccess);

    ConnectToProvider(kQueryImage);
}

CHIP_ERROR DefaultOTARequestor::TriggerImmediateQuery(FabricIndex fabricIndex)
{
    ProviderLocationType providerLocation;
    bool providerFound = false;

    if (fabricIndex == kUndefinedFabricIndex)
    {
        bool listExhausted = false;
        providerFound      = mOtaRequestorDriver->GetNextProviderLocation(providerLocation, listExhausted);
    }
    else
    {
        for (auto providerIter = mDefaultOtaProviderList.Begin(); providerIter.Next();)
        {
            providerLocation = providerIter.GetValue();

            if (providerLocation.GetFabricIndex() == fabricIndex)
            {
                providerFound = true;
                break;
            }
        }
    }

    if (!providerFound)
    {
        ChipLogError(SoftwareUpdate, "No OTA Providers available for immediate query");
        return CHIP_ERROR_NOT_FOUND;
    }

    SetCurrentProviderLocation(providerLocation);

    // Go through the driver as it has additional logic to execute
    mOtaRequestorDriver->SendQueryImage();

    ChipLogProgress(SoftwareUpdate, "Triggered immediate OTA query for fabric: 0x%x",
                    static_cast<unsigned>(providerLocation.GetFabricIndex()));

    return CHIP_NO_ERROR;
}

void DefaultOTARequestor::DownloadUpdate()
{
    RecordNewUpdateState(OTAUpdateStateEnum::kDownloading, OTAChangeReasonEnum::kSuccess);
    ConnectToProvider(kDownload);
}

void DefaultOTARequestor::DownloadUpdateDelayedOnUserConsent()
{
    RecordNewUpdateState(OTAUpdateStateEnum::kDelayedOnUserConsent, OTAChangeReasonEnum::kSuccess);
}

void DefaultOTARequestor::ApplyUpdate()
{
    RecordNewUpdateState(OTAUpdateStateEnum::kApplying, OTAChangeReasonEnum::kSuccess);

    // If image is successfully applied, the device will reboot so persist all relevant data
    StoreCurrentUpdateInfo();

    ConnectToProvider(kApplyUpdate);
}

void DefaultOTARequestor::NotifyUpdateApplied()
{
    // Log the VersionApplied event
    uint16_t productId;
    if (DeviceLayer::GetDeviceInstanceInfoProvider()->GetProductId(productId) != CHIP_NO_ERROR)
    {
        ChipLogError(SoftwareUpdate, "Cannot get Product ID");
        RecordErrorUpdateState(CHIP_ERROR_INCORRECT_STATE);
        return;
    }

    OtaRequestorServerOnVersionApplied(mCurrentVersion, productId);

    ConnectToProvider(kNotifyUpdateApplied);
}

CHIP_ERROR DefaultOTARequestor::ClearDefaultOtaProviderList(FabricIndex fabricIndex)
{
    CHIP_ERROR error = mDefaultOtaProviderList.Delete(fabricIndex);

    // Ignore the error if no entry for the associated fabric index has been found.
    ReturnErrorCodeIf(error == CHIP_ERROR_NOT_FOUND, CHIP_NO_ERROR);
    ReturnErrorOnFailure(error);

    return mStorage->StoreDefaultProviders(mDefaultOtaProviderList);
}

CHIP_ERROR DefaultOTARequestor::AddDefaultOtaProvider(const ProviderLocationType & providerLocation)
{
    // Look for an entry with the same fabric index indicated
    auto iterator = mDefaultOtaProviderList.Begin();
    while (iterator.Next())
    {
        ProviderLocationType pl = iterator.GetValue();
        if (pl.GetFabricIndex() == providerLocation.GetFabricIndex())
        {
            ChipLogError(SoftwareUpdate, "Default OTA provider entry with fabric %d already exists", pl.GetFabricIndex());
            return CHIP_IM_GLOBAL_STATUS(ConstraintError);
        }
    }

    ReturnErrorOnFailure(mDefaultOtaProviderList.Add(providerLocation));

    return mStorage->StoreDefaultProviders(mDefaultOtaProviderList);
}

void DefaultOTARequestor::OnDownloadStateChanged(OTADownloader::State state, OTAChangeReasonEnum reason)
{
    VerifyOrDie(mOtaRequestorDriver != nullptr);

    switch (state)
    {
    case OTADownloader::State::kComplete:
        mOtaRequestorDriver->UpdateDownloaded();
        mBdxMessenger.Reset();
        break;
    case OTADownloader::State::kIdle:
        if (reason != OTAChangeReasonEnum::kSuccess)
        {
            RecordErrorUpdateState(CHIP_ERROR_CONNECTION_ABORTED, reason);
        }
        mBdxMessenger.Reset();
        break;
    default:
        break;
    }
}

void DefaultOTARequestor::OnUpdateProgressChanged(Nullable<uint8_t> percent)
{
    OtaRequestorServerSetUpdateStateProgress(percent);
}

IdleStateReason DefaultOTARequestor::MapErrorToIdleStateReason(CHIP_ERROR error)
{
    if (error == CHIP_NO_ERROR)
    {
        return IdleStateReason::kIdle;
    }
    if (error == CHIP_ERROR_CONNECTION_CLOSED_UNEXPECTEDLY)
    {
        return IdleStateReason::kInvalidSession;
    }

    return IdleStateReason::kUnknown;
}

void DefaultOTARequestor::RecordNewUpdateState(OTAUpdateStateEnum newState, OTAChangeReasonEnum reason, CHIP_ERROR error)
{
    // Set server UpdateState attribute
    OtaRequestorServerSetUpdateState(newState);

    // The UpdateStateProgress attribute only applies to the downloading state
    if (newState != OTAUpdateStateEnum::kDownloading)
    {
        app::DataModel::Nullable<uint8_t> percent;
        percent.SetNull();
        OtaRequestorServerSetUpdateStateProgress(percent);
    }

    // Log the StateTransition event
    Nullable<uint32_t> targetSoftwareVersion;
    if ((newState == OTAUpdateStateEnum::kDownloading) || (newState == OTAUpdateStateEnum::kApplying) ||
        (newState == OTAUpdateStateEnum::kRollingBack))
    {
        targetSoftwareVersion.SetNonNull(mTargetVersion);
    }
    OtaRequestorServerOnStateTransition(mCurrentUpdateState, newState, reason, targetSoftwareVersion);

    OTAUpdateStateEnum prevState = mCurrentUpdateState;
    // Update the new state before handling the state transition
    mCurrentUpdateState = newState;

    if ((newState == OTAUpdateStateEnum::kIdle) && (prevState != OTAUpdateStateEnum::kIdle))
    {
        IdleStateReason idleStateReason = MapErrorToIdleStateReason(error);
        mOtaRequestorDriver->HandleIdleStateEnter(idleStateReason);
    }
    else if ((prevState == OTAUpdateStateEnum::kIdle) && (newState != OTAUpdateStateEnum::kIdle))
    {
        mOtaRequestorDriver->HandleIdleStateExit();
    }
}

void DefaultOTARequestor::RecordErrorUpdateState(CHIP_ERROR error, OTAChangeReasonEnum reason)
{
    // Log the DownloadError event
    OTAImageProcessorInterface * imageProcessor = mBdxDownloader->GetImageProcessorDelegate();
    VerifyOrDie(imageProcessor != nullptr);
    Nullable<uint8_t> progressPercent = imageProcessor->GetPercentComplete();
    Nullable<int64_t> platformCode;
    OtaRequestorServerOnDownloadError(mTargetVersion, imageProcessor->GetBytesDownloaded(), progressPercent, platformCode);

    // Whenever an error occurs, always reset to Idle state
    RecordNewUpdateState(OTAUpdateStateEnum::kIdle, reason, error);
}

CHIP_ERROR DefaultOTARequestor::GenerateUpdateToken()
{
    if (mUpdateToken.empty())
    {
        VerifyOrReturnError(mServer != nullptr, CHIP_ERROR_INCORRECT_STATE);
        VerifyOrReturnError(mProviderLocation.HasValue(), CHIP_ERROR_INCORRECT_STATE);

        const FabricInfo * fabricInfo = mServer->GetFabricTable().FindFabricWithIndex(mProviderLocation.Value().fabricIndex);
        VerifyOrReturnError(fabricInfo != nullptr, CHIP_ERROR_INCORRECT_STATE);

        static_assert(sizeof(NodeId) == sizeof(uint64_t), "Unexpected NodeId size");
        Encoding::BigEndian::Put64(mUpdateTokenBuffer, fabricInfo->GetPeerId().GetNodeId());
        mUpdateToken = ByteSpan(mUpdateTokenBuffer, sizeof(NodeId));
    }

    return CHIP_NO_ERROR;
}

CHIP_ERROR DefaultOTARequestor::SendQueryImageRequest(OperationalDeviceProxy & deviceProxy)
{
    VerifyOrReturnError(mProviderLocation.HasValue(), CHIP_ERROR_INCORRECT_STATE);

    constexpr OTADownloadProtocol kProtocolsSupported[] = { OTADownloadProtocol::kBDXSynchronous };
    QueryImage::Type args;

    uint16_t vendorId;
    ReturnErrorOnFailure(DeviceLayer::GetDeviceInstanceInfoProvider()->GetVendorId(vendorId));
    args.vendorId = static_cast<VendorId>(vendorId);

    ReturnErrorOnFailure(DeviceLayer::GetDeviceInstanceInfoProvider()->GetProductId(args.productId));

    ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSoftwareVersion(args.softwareVersion));

    args.protocolsSupported = kProtocolsSupported;
    args.requestorCanConsent.SetValue(!Basic::IsLocalConfigDisabled() && mOtaRequestorDriver->CanConsent());

    uint16_t hardwareVersion;
    if (DeviceLayer::GetDeviceInstanceInfoProvider()->GetHardwareVersion(hardwareVersion) == CHIP_NO_ERROR)
    {
        args.hardwareVersion.SetValue(hardwareVersion);
    }

    char location[DeviceLayer::ConfigurationManager::kMaxLocationLength];
    size_t codeLen = 0;
    if ((DeviceLayer::ConfigurationMgr().GetCountryCode(location, sizeof(location), codeLen) == CHIP_NO_ERROR) && (codeLen == 2))
    {
        args.location.SetValue(CharSpan(location, codeLen));
    }
    else
    {
        // Country code unavailable or invalid, use default
        args.location.SetValue(CharSpan("XX", strlen("XX")));
    }

    Controller::OtaSoftwareUpdateProviderCluster cluster(*deviceProxy.GetExchangeManager(), deviceProxy.GetSecureSession().Value(),
                                                         mProviderLocation.Value().endpoint);

    return cluster.InvokeCommand(args, this, OnQueryImageResponse, OnQueryImageFailure);
}

CHIP_ERROR DefaultOTARequestor::ExtractUpdateDescription(const QueryImageResponseDecodableType & response,
                                                         UpdateDescription & update) const
{
    NodeId nodeId;
    CharSpan fileDesignator;

    VerifyOrReturnError(response.imageURI.HasValue(), CHIP_ERROR_INVALID_ARGUMENT);
    ReturnErrorOnFailure(bdx::ParseURI(response.imageURI.Value(), nodeId, fileDesignator));
    VerifyOrReturnError(IsSpanUsable(fileDesignator), CHIP_ERROR_INVALID_ARGUMENT);
    update.nodeId         = nodeId;
    update.fileDesignator = fileDesignator;

    VerifyOrReturnError(response.softwareVersion.HasValue(), CHIP_ERROR_INVALID_ARGUMENT);
    VerifyOrReturnError(response.softwareVersionString.HasValue(), CHIP_ERROR_INVALID_ARGUMENT);
    update.softwareVersion    = response.softwareVersion.Value();
    update.softwareVersionStr = response.softwareVersionString.Value();

    VerifyOrReturnError(response.updateToken.HasValue(), CHIP_ERROR_INVALID_ARGUMENT);
    update.updateToken = response.updateToken.Value();

    update.userConsentNeeded    = response.userConsentNeeded.ValueOr(false);
    update.metadataForRequestor = response.metadataForRequestor.ValueOr({});

    return CHIP_NO_ERROR;
}

CHIP_ERROR DefaultOTARequestor::StartDownload(OperationalDeviceProxy & deviceProxy)
{
    VerifyOrReturnError(mBdxDownloader != nullptr, CHIP_ERROR_INCORRECT_STATE);

    // TODO: allow caller to provide their own OTADownloader instance and set BDX parameters

    TransferSession::TransferInitData initOptions;
    initOptions.TransferCtlFlags = bdx::TransferControlFlags::kReceiverDrive;
    initOptions.MaxBlockSize     = mOtaRequestorDriver->GetMaxDownloadBlockSize();
    initOptions.FileDesLength    = static_cast<uint16_t>(mFileDesignator.size());
    initOptions.FileDesignator   = reinterpret_cast<const uint8_t *>(mFileDesignator.data());

    chip::Messaging::ExchangeManager * exchangeMgr = deviceProxy.GetExchangeManager();
    VerifyOrReturnError(exchangeMgr != nullptr, CHIP_ERROR_INCORRECT_STATE);

    Optional<SessionHandle> session = deviceProxy.GetSecureSession();
    VerifyOrReturnError(session.HasValue(), CHIP_ERROR_INCORRECT_STATE);

    chip::Messaging::ExchangeContext * exchangeCtx = exchangeMgr->NewContext(session.Value(), &mBdxMessenger);
    VerifyOrReturnError(exchangeCtx != nullptr, CHIP_ERROR_NO_MEMORY);

    mBdxMessenger.Init(mBdxDownloader, exchangeCtx);
    mBdxDownloader->SetMessageDelegate(&mBdxMessenger);
    mBdxDownloader->SetStateDelegate(this);

    CHIP_ERROR err = mBdxDownloader->SetBDXParams(initOptions, kDownloadTimeoutSec);
    if (err == CHIP_NO_ERROR)
    {
        err = mBdxDownloader->BeginPrepareDownload();
    }

    if (err != CHIP_NO_ERROR)
    {
        mBdxMessenger.Reset();
    }

    return err;
}

CHIP_ERROR DefaultOTARequestor::SendApplyUpdateRequest(OperationalDeviceProxy & deviceProxy)
{
    VerifyOrReturnError(mProviderLocation.HasValue(), CHIP_ERROR_INCORRECT_STATE);
    ReturnErrorOnFailure(GenerateUpdateToken());

    ApplyUpdateRequest::Type args;
    args.updateToken = mUpdateToken;
    args.newVersion  = mTargetVersion;

    Controller::OtaSoftwareUpdateProviderCluster cluster(*deviceProxy.GetExchangeManager(), deviceProxy.GetSecureSession().Value(),
                                                         mProviderLocation.Value().endpoint);

    return cluster.InvokeCommand(args, this, OnApplyUpdateResponse, OnApplyUpdateFailure);
}

CHIP_ERROR DefaultOTARequestor::SendNotifyUpdateAppliedRequest(OperationalDeviceProxy & deviceProxy)
{
    VerifyOrReturnError(mProviderLocation.HasValue(), CHIP_ERROR_INCORRECT_STATE);
    ReturnErrorOnFailure(GenerateUpdateToken());

    NotifyUpdateApplied::Type args;
    args.updateToken     = mUpdateToken;
    args.softwareVersion = mCurrentVersion;

    Controller::OtaSoftwareUpdateProviderCluster cluster(*deviceProxy.GetExchangeManager(), deviceProxy.GetSecureSession().Value(),
                                                         mProviderLocation.Value().endpoint);

    // There is no response for a notify so consider this OTA complete. Clear the provider location and reset any states to indicate
    // so.
    Reset();

    return cluster.InvokeCommand(args, this, OnNotifyUpdateAppliedResponse, OnNotifyUpdateAppliedFailure);
}

void DefaultOTARequestor::StoreCurrentUpdateInfo()
{
    // TODO: change OTA requestor storage interface to store both values at once
    CHIP_ERROR error = CHIP_NO_ERROR;
    if (mProviderLocation.HasValue())
    {
        error = mStorage->StoreCurrentProviderLocation(mProviderLocation.Value());
    }
    else
    {
        error = mStorage->ClearCurrentProviderLocation();
    }

    if ((error == CHIP_NO_ERROR) || (error == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND))
    {
        if (mUpdateToken.size() > 0)
        {
            error = mStorage->StoreUpdateToken(mUpdateToken);
        }
        else
        {
            error = mStorage->ClearUpdateToken();
        }
    }

    if ((error == CHIP_NO_ERROR) || (error == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND))
    {
        error = mStorage->StoreCurrentUpdateState(mCurrentUpdateState);
    }

    if ((error == CHIP_NO_ERROR) || (error == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND))
    {
        if (mTargetVersion > 0)
        {
            error = mStorage->StoreTargetVersion(mTargetVersion);
        }
        else
        {
            error = mStorage->ClearTargetVersion();
        }
    }

    if ((error != CHIP_NO_ERROR) && (error != CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND))
    {
        ChipLogError(SoftwareUpdate, "Failed to store current update: %" CHIP_ERROR_FORMAT, error.Format());
    }
}

void DefaultOTARequestor::LoadCurrentUpdateInfo()
{
    mStorage->LoadDefaultProviders(mDefaultOtaProviderList);

    ProviderLocationType providerLocation;
    if (mStorage->LoadCurrentProviderLocation(providerLocation) == CHIP_NO_ERROR)
    {
        mProviderLocation.SetValue(providerLocation);
    }

    MutableByteSpan updateToken(mUpdateTokenBuffer);
    if (mStorage->LoadUpdateToken(updateToken) == CHIP_NO_ERROR)
    {
        mUpdateToken = updateToken;
    }

    if (mStorage->LoadCurrentUpdateState(mCurrentUpdateState) != CHIP_NO_ERROR)
    {
        mCurrentUpdateState = OTAUpdateStateEnum::kIdle;
    }

    if (mStorage->LoadTargetVersion(mTargetVersion) != CHIP_NO_ERROR)
    {
        mTargetVersion = 0;
    }
}

// Invoked when the device becomes commissioned
void DefaultOTARequestor::OnCommissioningCompleteRequestor(const DeviceLayer::ChipDeviceEvent * event, intptr_t arg)
{
    VerifyOrReturn(event->Type == DeviceLayer::DeviceEventType::kCommissioningComplete);

    ChipLogProgress(SoftwareUpdate, "Device commissioned, schedule a default provider query");

    // TODO: Should we also send UpdateApplied here?

    // Schedule a query. At the end of this query/update process the Default Provider timer is started
    OTARequestorDriver * driver = (reinterpret_cast<DefaultOTARequestor *>(arg))->mOtaRequestorDriver;
    driver->OTACommissioningCallback();
}

} // namespace chip


text:
{-# LANGUAGE ScopedTypeVariables #-}

module Language.Haskell.GhcMod.GHCChoice where

import Control.Exception
import CoreMonad
import Exception
import GHC

----------------------------------------------------------------

-- | Try the left 'Ghc' action. If 'IOException' occurs, try
--   the right 'Ghc' action.
(||>) :: Ghc a -> Ghc a -> Ghc a
x ||> y = x `gcatch` (\(_ :: IOException) -> y)

-- | Go to the next 'Ghc' monad by throwing 'AltGhcgoNext'.
goNext :: Ghc a
goNext = liftIO . throwIO $ userError "goNext"

-- | Run any one 'Ghc' monad.
runAnyOne :: [Ghc a] -> Ghc a
runAnyOne = foldr (||>) goNext

----------------------------------------------------------------

-- | Try the left 'GhcMonad' action. If 'IOException' occurs, try
--   the right 'GhcMonad' action.
(|||>) :: GhcMonad m => m a -> m a -> m a
x |||> y = x `gcatch` (\(_ :: IOException) -> y)

redpajama_set_name: RedPajamaGithub


text:
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_create (JNIEnv *env, jobject thisObj) {
}

JNIEXPORT void JNICALL Java_org_zeromq_Zlist_destroy (JNIEnv *env, jobject thisObj) {
}

//  Return the item at the head of list. If the list is empty, returns NULL.
//  Leaves cursor pointing at the head item, or NULL if the list is empty.
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_first (JNIEnv *env, jobject thisObj) {
}

//  Return the next item. If the list is empty, returns NULL. To move to
//  the start of the list call zlist_first (). Advances the cursor.
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_next (JNIEnv *env, jobject thisObj) {
}

//  Return the item at the tail of list. If the list is empty, returns NULL.
//  Leaves cursor pointing at the tail item, or NULL if the list is empty.
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_last (JNIEnv *env, jobject thisObj) {
}

//  Return first item in the list, or null, leaves the cursor
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_head (JNIEnv *env, jobject thisObj) {
}

//  Return last item in the list, or null, leaves the cursor
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_tail (JNIEnv *env, jobject thisObj) {
}

//  Return the current item of list. If the list is empty, returns NULL.
//  Leaves cursor pointing at the current item, or NULL if the list is empty.
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_item (JNIEnv *env, jobject thisObj) {
}

//  Append an item to the end of the list, return 0 if OK or -1 if this
//  failed for some reason (out of memory). Note that if a duplicator has
//  been set, this method will also duplicate the item.
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_append (JNIEnv *env, jobject thisObj) {
}

//  Push an item to the start of the list, return 0 if OK or -1 if this
//  failed for some reason (out of memory). Note that if a duplicator has
//  been set, this method will also duplicate the item.
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_push (JNIEnv *env, jobject thisObj) {
}

//  Pop the item off the start of the list, if any
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_pop (JNIEnv *env, jobject thisObj) {
}

//  Checks if an item already is present. Uses compare method to determine if
//  items are equal. If the compare method is NULL the check will only compare
//  pointers. Returns true if item is present else false.
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_exists (JNIEnv *env, jobject thisObj) {
}

//  Remove the specified item from the list if present
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_remove (JNIEnv *env, jobject thisObj) {
}

//  Make a copy of list. If the list has autofree set, the copied list will
//  duplicate all items, which must be strings. Otherwise, the list will hold
//  pointers back to the items in the original list. If list is null, returns
//  NULL.
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_dup (JNIEnv *env, jobject thisObj) {
}

//  Purge all items from list
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_purge (JNIEnv *env, jobject thisObj) {
}

//  Return number of items in the list
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_size (JNIEnv *env, jobject thisObj) {
}

//  Sort the list by ascending key value using a straight ASCII comparison.
//  The sort is not stable, so may reorder items with the same keys.
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_sort (JNIEnv *env, jobject thisObj) {
}

//  Set list for automatic item destruction; item values MUST be strings.
//  By default a list item refers to a value held elsewhere. When you set
//  this, each time you append or push a list item, zlist will take a copy
//  of the string value. Then, when you destroy the list, it will free all
//  item values automatically. If you use any other technique to allocate
//  list values, you must free them explicitly before destroying the list.
//  The usual technique is to pop list items and destroy them, until the
//  list is empty.
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_autofree (JNIEnv *env, jobject thisObj) {
}

//  Sets a compare function for this list. The function compares two items.
//  It returns an integer less than, equal to, or greater than zero if the
//  first item is found, respectively, to be less than, to match, or be
//  greater than the second item.
//  This function is used for sorting, removal and exists checking.
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_comparefn (JNIEnv *env, jobject thisObj) {
}

//  Set a free function for the specified list item. When the item is
//  destroyed, the free function, if any, is called on that item.
//  Use this when list items are dynamically allocated, to ensure that
//  you don't have memory leaks. You can pass 'free' or NULL as a free_fn.
//  Returns the item, or NULL if there is no such item.
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_freefn (JNIEnv *env, jobject thisObj) {
}

//  Self test of this class
JNIEXPORT void JNICALL Java_org_zeromq_Zlist_test (JNIEnv *env, jobject thisObj) {
}


text:
using System.Collections.Generic;
using Kaftar.Core.Domain.Domain.Events.Base;

namespace Kaftar.Core.Domain.AggregateRoots
{
    public class AggregateRoot:Entity
    {
        protected IList<IDomainEvent> Events=new List<IDomainEvent>();
    }
}


text:
All URIs are relative to *https://trusthub.twilio.com*

Method | HTTP request | Description
------------- | ------------- | -------------
[**CreateCustomerProfile**](CustomerProfilesApi.md#CreateCustomerProfile) | **Post** /v1/CustomerProfiles |
[**DeleteCustomerProfile**](CustomerProfilesApi.md#DeleteCustomerProfile) | **Delete** /v1/CustomerProfiles/{Sid} |
[**FetchCustomerProfile**](CustomerProfilesApi.md#FetchCustomerProfile) | **Get** /v1/CustomerProfiles/{Sid} |
[**ListCustomerProfile**](CustomerProfilesApi.md#ListCustomerProfile) | **Get** /v1/CustomerProfiles |
[**UpdateCustomerProfile**](CustomerProfilesApi.md#UpdateCustomerProfile) | **Post** /v1/CustomerProfiles/{Sid} |

## CreateCustomerProfile

> TrusthubV1CustomerProfile CreateCustomerProfile(ctx, optional)

Create a new Customer-Profile.

### Path Parameters

This endpoint does not need any path parameter.

### Other Parameters

Other parameters are passed through a pointer to a CreateCustomerProfileParams struct

Name | Type | Description
------------- | ------------- | -------------
**FriendlyName** | **string** | The string that you assigned to describe the resource.
**Email** | **string** | The email address that will receive updates when the Customer-Profile resource changes status.
**PolicySid** | **string** | The unique string of a policy that is associated to the Customer-Profile resource.
**StatusCallback** | **string** | The URL we call to inform your application of status changes.

### Return type

[**TrusthubV1CustomerProfile**](TrusthubV1CustomerProfile.md)

### Authorization

[accountSid_authToken](../README.md#accountSid_authToken)

### HTTP request headers

- **Content-Type**: application/x-www-form-urlencoded
- **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)

## DeleteCustomerProfile

> DeleteCustomerProfile(ctx, Sid)

Delete a specific Customer-Profile.

### Path Parameters

Name | Type | Description
------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**Sid** | **string** | The unique string that we created to identify the Customer-Profile resource.

### Other Parameters

Other parameters are passed through a pointer to a DeleteCustomerProfileParams struct

Name | Type | Description
------------- | ------------- | -------------

### Return type

 (empty response body)

### Authorization

[accountSid_authToken](../README.md#accountSid_authToken)

### HTTP request headers

- **Content-Type**: Not defined
- **Accept**: Not defined

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)

## FetchCustomerProfile

> TrusthubV1CustomerProfile FetchCustomerProfile(ctx, Sid)

Fetch a specific Customer-Profile instance.

### Path Parameters

Name | Type | Description
------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**Sid** | **string** | The unique string that we created to identify the Customer-Profile resource.

### Other Parameters

Other parameters are passed through a pointer to a FetchCustomerProfileParams struct

Name | Type | Description
------------- | ------------- | -------------

### Return type

[**TrusthubV1CustomerProfile**](TrusthubV1CustomerProfile.md)

### Authorization

[accountSid_authToken](../README.md#accountSid_authToken)

### HTTP request headers

- **Content-Type**: Not defined
- **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)

## ListCustomerProfile

> []TrusthubV1CustomerProfile ListCustomerProfile(ctx, optional)

Retrieve a list of all Customer-Profiles for an account.

### Path Parameters

This endpoint does not need any path parameter.

### Other Parameters

Other parameters are passed through a pointer to a ListCustomerProfileParams struct

Name | Type | Description
------------- | ------------- | -------------
**Status** | **string** | The verification status of the Customer-Profile resource.
**FriendlyName** | **string** | The string that you assigned to describe the resource.
**PolicySid** | **string** | The unique string of a policy that is associated to the Customer-Profile resource.
**PageSize** | **int** | How many resources to return in each list page. The default is 50, and the maximum is 1000.
**Limit** | **int** | Max number of records to return.

### Return type

[**[]TrusthubV1CustomerProfile**](TrusthubV1CustomerProfile.md)

### Authorization

[accountSid_authToken](../README.md#accountSid_authToken)

### HTTP request headers

- **Content-Type**: Not defined
- **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)

## UpdateCustomerProfile

> TrusthubV1CustomerProfile UpdateCustomerProfile(ctx, Sidoptional)

Updates a Customer-Profile in an account.

### Path Parameters

Name | Type | Description
------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**Sid** | **string** | The unique string that we created to identify the Customer-Profile resource.

### Other Parameters

Other parameters are passed through a pointer to a UpdateCustomerProfileParams struct

Name | Type | Description
------------- | ------------- | -------------
**Status** | **string** |
**StatusCallback** | **string** | The URL we call to inform your application of status changes.
**FriendlyName** | **string** | The string that you assigned to describe the resource.
**Email** | **string** | The email address that will receive updates when the Customer-Profile resource changes status.

### Return type

[**TrusthubV1CustomerProfile**](TrusthubV1CustomerProfile.md)

### Authorization

[accountSid_authToken](../README.md#accountSid_authToken)

### HTTP request headers

- **Content-Type**: application/x-www-form-urlencoded
- **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Entyloma ossifragi Rostr., 1890

### Remarks
null


text:
//
// treedirect.h
//
// Functions for a client to access the distributed B-tree directly
// without going through SQlite.
//

#ifndef _DTREEDIRECT_H
#define _DTREEDIRECT_H

#define NODEFINE_SQLITE3_VERSION
#include "sqlite.h"
#include "dtreeaux.h"

#include "btreeInt.h"
#include "gaiatypes.h"
#include "util.h"
#include "datastruct.h"
#include "clientlib.h"
#include "clientdir.h"
#include "yesql-init.h"

struct DdConnection {
  char *dbname;
  sqlite3 *db;
  Btree *pBtree;
};

struct DdTable {
  DdConnection *conn;
  BtCursor *pCur;
  u64 iTable;
};

int DdInit(); // Initialize. Call once across all threads.
void DdUninit(); // Uninitialize. Call once across all threads.
int DdInitConnection(const char *dbname, DdConnection *&conn); // Initialize a
  // connection. Call once per thread. Returns err status (0=ok) and sets conn.
int DdCloseConnection(DdConnection *conn); // Close a connection.
int DdOpenTable(DdConnection *conn, u64 iTable, DdTable *&table); // Open a
  // table given connection and table number. Call once per thread. Returns
  // error status (0=ok) and sets table.
int DdCreateTable(DdConnection *conn, u64 iTable, DdTable *&table); // Create
  // and open a table given connection. Returns table number in iTable
  // and handle in table
void DdCloseTable(DdTable *table); // Close a table.
int DdStartTx(DdConnection *conn); // Start a transaction
int DdRollbackTx(DdConnection *conn); // Rollback a transaction
int DdCommitTx(DdConnection *conn); // Try to commit a transaction. Returns 0
  // if committed, -1 if aborted.
int DdInsert(DdTable *table, i64 key, const char *value, int valuelen);
  // Insert on a table. The key is key, value is value with length valuelen
Oid DdGetOid(DdTable *table, i64 key);
  // Get oid of leaf node storing a given key
int DdUpdate(DdTable *table, i64 key, char *buf, int buflen,
  int (*callback)(char *buf, int len, void *arg), void *arg);
  // Update key.
  // Read into buf with buflen, invokes callback to change buf, then write
  // back buf with length returned by callback
int DdDelete(DdTable *table, i64 key); // Delete key.
int DdLookup(DdTable *table, i64 key, char *buf, int buflen,
             int *valuelen, bool tryDirect=true);
  // Lookup key, writes value in *buf up to buflen characters, set *valuelen
  // to number of bytes written to buf. Returns error status (0=ok). Sets
  // *valuelen=0 if key not found.
int DdScan(DdTable *table, i64 key, int nelems,
  void (*callback)(i64 key, const char *data, int len, int n, bool eof,
  void *callbackparm), void *callbackparm, bool fetchdata=true); // Scan table
  // starting a first key <= given key for up to nelements.
  // For each found element, invoke callback with key, data, length of data,
  // a sequence number (starting with 0 up to elements-1), a flag indicating
  // whether there are no more elements (if this flag is set, data and len
  // will be set to 0), and a callback parameter given to DdScan().
  // Returns 0 if no error (reaching eof before nelems is not error),
  // non-zero otherwise.

#endif


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;

namespace LinqToDB.DataProvider.SQLite
{
	using Common;
	using Configuration;
	using Data;

	public static class SQLiteTools
	{
		private static readonly Lazy<IDataProvider> _SQLiteClassicDataProvider = new Lazy<IDataProvider>(() =>
		{
			var provider = new SQLiteDataProvider(ProviderName.SQLiteClassic);

			DataConnection.AddDataProvider(provider);

			return provider;
		}, true);

		private static readonly Lazy<IDataProvider> _SQLiteMSDataProvider = new Lazy<IDataProvider>(() =>
		{
			var provider = new SQLiteDataProvider(ProviderName.SQLiteMS);

			DataConnection.AddDataProvider(provider);

			return provider;
		}, true);

		public static bool AlwaysCheckDbNull = true;

		internal static IDataProvider? ProviderDetector(IConnectionStringSettings css, string connectionString)
		{
			if (css.IsGlobal)
				return null;

			switch (css.ProviderName)
			{
				case SQLiteProviderAdapter.SystemDataSQLiteClientNamespace   :
				case ProviderName.SQLiteClassic                              : return _SQLiteClassicDataProvider.Value;
				case SQLiteProviderAdapter.MicrosoftDataSQLiteClientNamespace:
				case "Microsoft.Data.SQLite"                                 :
				case ProviderName.SQLiteMS                                   : return _SQLiteMSDataProvider.Value;
				case ""                                                      :
				case null                                                    :
					if (css.Name.Contains("SQLite") || css.Name.Contains("Sqlite"))
						goto case ProviderName.SQLite;
					break;
				case ProviderName.SQLite                                     :
					if (css.Name.Contains("MS") || css.Name.Contains("Microsoft"))
						return _SQLiteMSDataProvider.Value;

					if (css.Name.Contains("Classic"))
						return _SQLiteClassicDataProvider.Value;

					return GetDataProvider();
				case var providerName when providerName.Contains("SQLite") || providerName.Contains("Sqlite"):
					if (css.ProviderName.Contains("MS") || css.ProviderName.Contains("Microsoft"))
						return _SQLiteMSDataProvider.Value;

					if (css.ProviderName.Contains("Classic"))
						return _SQLiteClassicDataProvider.Value;

					return GetDataProvider();
			}

			return null;
		}

		private static string? _detectedProviderName;
		public  static string  DetectedProviderName =>
			_detectedProviderName ??= DetectProviderName();

		static string DetectProviderName()
		{
			try
			{
				var path = typeof(SQLiteTools).Assembly.GetPath();

				if (   !File.Exists(Path.Combine(path, $"{SQLiteProviderAdapter.SystemDataSQLiteAssemblyName}.dll")))
					if (File.Exists(Path.Combine(path, $"{SQLiteProviderAdapter.MicrosoftDataSQLiteAssemblyName}.dll")))
						return ProviderName.SQLiteMS;
			}
			catch
			{
			}

			return ProviderName.SQLiteClassic;
		}

		public static IDataProvider GetDataProvider(string? providerName = null)
		{
			switch (providerName)
			{
				case ProviderName.SQLiteClassic: return _SQLiteClassicDataProvider.Value;
				case ProviderName.SQLiteMS     : return _SQLiteMSDataProvider.Value;
			}

			if (DetectedProviderName == ProviderName.SQLiteClassic)
				return _SQLiteClassicDataProvider.Value;

			return _SQLiteMSDataProvider.Value;
		}

		public static void ResolveSQLite(string path)
		{
			new AssemblyResolver(
				path,
				DetectedProviderName == ProviderName.SQLiteClassic
						? SQLiteProviderAdapter.SystemDataSQLiteAssemblyName
						: SQLiteProviderAdapter.MicrosoftDataSQLiteAssemblyName);
		}

		public static void ResolveSQLite(Assembly assembly)
		{
			new AssemblyResolver(assembly, assembly.FullName!);
		}

		#region CreateDataConnection

		public static DataConnection CreateDataConnection(string connectionString, string? providerName = null)
		{
			return new DataConnection(GetDataProvider(providerName), connectionString);
		}

		public static DataConnection CreateDataConnection(IDbConnection connection, string? providerName = null)
		{
			return new DataConnection(GetDataProvider(providerName), connection);
		}

		public static DataConnection CreateDataConnection(IDbTransaction transaction, string? providerName = null)
		{
			return new DataConnection(GetDataProvider(providerName), transaction);
		}

		#endregion

		public static void CreateDatabase(string databaseName, bool deleteIfExists = false)
		{
			if (databaseName == null) throw new ArgumentNullException(nameof(databaseName));

			DataTools.CreateFileDatabase(
				databaseName, deleteIfExists, ".sqlite",
				dbName =>
				{
					// don't use CreateFile method of System.Data.Sqlite as it just creates empty file
					using (File.Create(dbName)) { };
				});
		}

		public static void DropDatabase(string databaseName)
		{
			if (databaseName == null) throw new ArgumentNullException(nameof(databaseName));

			DataTools.DropFileDatabase(databaseName, ".sqlite");
		}

		#region BulkCopy

		public  static BulkCopyType  DefaultBulkCopyType { get; set; } = BulkCopyType.MultipleRows;

		[Obsolete("Please use the BulkCopy extension methods within DataConnectionExtensions")]
		public static BulkCopyRowsCopied MultipleRowsCopy<T>(
			DataConnection               dataConnection,
			IEnumerable<T>               source,
			int                          maxBatchSize       = 1000,
			Action<BulkCopyRowsCopied>?  rowsCopiedCallback = null)
			where T : class
		{
			return dataConnection.BulkCopy(
				new BulkCopyOptions
				{
					BulkCopyType       = BulkCopyType.MultipleRows,
					MaxBatchSize       = maxBatchSize,
					RowsCopiedCallback = rowsCopiedCallback,
				}, source);
		}

		#endregion
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hatfield.EnviroData.Core;
using Hatfield.EnviroData.WQDataProfile;

namespace Hatfield.EnviroData.DataAcquisition.ESDAT.Converters
{
    public class DatasetMapper : DatasetMapperBase, IESDATSharedMapper<Dataset>
    {
        public Guid Guid { get; set; }

        public DatasetMapper(ODM2DuplicateChecker duplicateChecker, IWQDefaultValueProvider WQDefaultValueProvider, WayToHandleNewData wayToHandleNewData, List<IResult> results) : base(duplicateChecker, WQDefaultValueProvider, wayToHandleNewData, results)
        {
        }

        public Dataset Map(ESDATModel esdatModel)
        {
            var entity = Draft(esdatModel);
            entity = GetDuplicate(_wayToHandleNewData, entity);

            return entity;
        }

        public Dataset Draft(ESDATModel esdatModel)
        {
            var entity = new Dataset();

            entity.DatasetTypeCV = _WQDefaultValueProvider.DefaultDatasetTypeCV;
            entity.DatasetUUID = Guid;
            entity.DatasetCode = esdatModel.LabRequestId.ToString();
            entity.DatasetTitle = String.Format("{0}: {1} ({2})", esdatModel.LabName, esdatModel.LabRequestId.ToString(), esdatModel.DateReported);
            entity.DatasetAbstract = string.Empty;

            Validate(entity);

            return entity;
        }
    }
}


text:
.. _Seeding:

Seeding
#######

Introduction
============

Orator includes a simple method of seeding your database with test data using seed classes.
Seed classes may have any name you wish, but probably should follow some sensible convention,
such as ``UsersTableSeeder``, etc.
By default, a ``DatabaseSeeder`` class is defined for you the first time you create a seed class.
From this class, you can use the ``call`` method to run other seed classes,
allowing you to control the seeding order.

Writing Seeders
===============

To generate a seeder, you may issue the ``make:seed`` command.
All seeders generated by the command will be placed in a ``seeds`` directory
relative to where the command has been executed:

.. code-block:: text

    orator make:seed user_table_seeder

.. note::

    If you want the seed classes to be stored in another directory, use the ``-p/--path`` option

A seeder class only contains one method by default: ``run``.
This method is called when the ``db:seed`` command is executed.
Within the ``run`` method, you can insert data into your database however you wish.
You can use the :ref:`QueryBuilder` to manually insert data or you can use :ref:`ModelFactories`.

As an example, let's modify the ``UsersTableSeeder`` class you just created.
Let's add a database insert statement to the ``run`` method:

.. code-block:: python

    from orator.seeds import Seeder

    class UsersTableSeeder(Seeder):

        def run(self):
            """
            Run the database seeds.
            """

            # Here you could just use random string generators
            # rather than hardcoded values
            self.db.table('users').insert({
                'name': 'john',
                'email': 'john@doe.com'
            })

Using Model Factories
---------------------

Of course, manually specifying the attributes for each model seed is cumbersome.
Instead, you can use :ref:`ModelFactories` to conveniently generate large amounts of database records.
First, review the :ref:`model factory documentation <ModelFactories>` to learn how to define your factories.
You can use an external factory or use the seeder class ``factory`` attribute.

For example, let's create 50 users and attach a relationship to each user:

.. code-block:: python

    from orator.seeds import Seeder
    from orator.orm import Factory

    factory = Factory()

    @factory.define(User)
    def users_factory(faker):
        return {
            'name': faker.name(),
            'email': faker.email()
        }

    @factory.define(Post)
    def posts_factory(faker):
        return {
            'title': faker.name(),
            'content': faker.text()
        }

    class UsersTableSeeder(Seeder):

        factory = factory  # This is only needed when using an external factory

        def run(self):
            """
            Run the database seeds.
            """
            self.factory(User, 50).create().each(
                lambda u: u.posts().save(self.factory(Post).make())
            )

Or using directly the ``factory`` attribute without an external factory:

.. code-block:: python

    class UsersTableSeeder(Seeder):

        def run(self):
            """
            Run the database seeds.
            """
            self.factory.register(User, self.users_factory)
            self.factory.register(Post, self.posts_factory)

            self.factory(User, 50).create().each(
                lambda u: u.posts().save(self.factory(Post).make())
            )

        def users_factory(self, faker):
            return {
                'name': faker.name(),
                'email': faker.email()
            }

        def posts_factory(self, faker):
            return {
                'title': faker.name(),
                'content': faker.text()
            }

Calling Additional Seeders
--------------------------

Within the ``DatabaseSeeder`` class, you can use the ``call`` method to execute additional seed classes.
Using the ``call`` method allows you to break up your database seeding into multiple files
so that no single seeder class becomes overwhelmingly large.
Simply pass the seeder class you wish to run:

.. code-block:: python

    def run(self):
        """
        Run the database seeds.
        """
        self.call(UsersTableSeeder)
        self.call(PostsTableSeeder)
        self.call(CommentsTableSeeder)

Running Seeders
===============

Once you have written your seeder classes, you may use the ``db:seed`` command to seed your database.
By default, the ``db:seed`` command runs the ``database_seeder`` file, which can be used to call other seed classes.
However, you can use the ``--seeder`` option to specify a specific seeder class to run individually:

.. code-block:: text

    orator db:seed

    orator db:seed --seeder users_table_seeder

You can also seed your database using the ``migrate:refresh`` command,
which will also rollback and re-run all of your migrations.
This command is useful for completely re-building your database:

.. code-block:: text

    orator migrate:refresh --seed


text:
add-apt-repository -y ppa:fkrull/deadsnakes
apt-get update

set +e
# Upgrade swig to 3.0.8
SWIG_VERSION="3.0.8"
swig_ver_flat=$(echo $SWIG_VERSION | sed 's/\.//g' | sed 's/^0*//g')
local_swig_ver=$(swig -version | grep -i version | awk '{print $3}')
local_swig_ver_flat=$(echo $local_swig_ver | sed 's/\.//g' | sed 's/^0*//g')
if [[ -z $local_swig_ver_flat ]]; then
  local_swig_ver_flat=0
fi
if (( $local_swig_ver_flat < $swig_ver_flat )); then
  set -e
  wget -q http://downloads.sourceforge.net/swig/swig-3.0.8.tar.gz
  tar xzf swig-3.0.8.tar.gz
  pushd swig-3.0.8
  apt-get install -y --no-install-recommends libpcre3-dev
  ./configure
  make
  make install
  rm -f /usr/bin/swig
  ln -s /usr/local/bin/swig /usr/bin/swig
  popd
  rm -rf swig-3.0.8 swig-3.0.8.tar.gz
fi
set -e
# Install Python 3.5 and dev library
apt-get install -y --no-install-recommends python3.5 libpython3.5-dev

# Install pip3.5
set +e
pip35_version=$(pip3.5 --version | grep "python 3.5")
if [[ -z $pip35_version ]]; then
  set -e
  wget -q https://bootstrap.pypa.io/get-pip.py
  python3.5 get-pip.py
  rm -f get-pip.py
fi

set -e
# Install six.
pip3.5 install --upgrade six==1.10.0

# Install protobuf.
pip3.5 install --upgrade protobuf==3.3.0

# Remove obsolete version of six, which can sometimes confuse virtualenv.
rm -rf /usr/lib/python3/dist-packages/six*

# Install numpy, scipy and scikit-learn required by the builds

# numpy needs to be installed from source to fix segfaults. See:
# https://github.com/tensorflow/tensorflow/issues/6968
# This workaround isn't needed for Ubuntu 16.04 or later.
pip3.5 install --no-binary=:all: --upgrade numpy==1.12.0

pip3.5 install scipy==0.18.1

pip3.5 install scikit-learn==0.18.1

# pandas required by `inflow`
pip3 install pandas==0.19.2

# Install recent-enough version of wheel for Python 3.5 wheel builds
pip3.5 install wheel==0.29.0

pip3.5 install portpicker

pip3.5 install werkzeug

pip3.5 install grpcio

# Eager execution needs autograd:
pip3.5 install --upgrade autograd


text:
Clazz.declarePackage ("J.adapter.readers.cif");
Clazz.load (["J.adapter.smarter.AtomSetCollectionReader"], "J.adapter.readers.cif.ModulationReader", ["java.lang.Float", "java.util.Hashtable", "J.util.Escape", "$.JmolList", "$.Logger", "$.Matrix3f", "$.Matrix4f", "$.Modulation", "$.ModulationSet", "$.P3", "$.SB", "$.V3"], function () {
c$ = Clazz.decorateAsClass (function () {
this.allowRotations = true;
this.modVib = false;
this.modAxes = null;
this.modAverage = false;
this.modType = null;
this.checkSpecial = true;
this.modDebug = false;
this.modSelected = -1;
this.modDim = 0;
this.incommensurate = false;
this.atoms = null;
this.bsAtoms = null;
this.q1 = null;
this.q1Norm = null;
this.htModulation = null;
this.htAtomMods = null;
this.htSubsystems = null;
this.suffix = null;
this.q123 = null;
this.qlen = null;
this.haveOccupancy = false;
this.iopLast = -1;
this.gammaE = null;
this.gammaIS = null;
this.nOps = 0;
Clazz.instantialize (this, arguments);
}, J.adapter.readers.cif, "ModulationReader", J.adapter.smarter.AtomSetCollectionReader);
$_M(c$, "initializeModulation",
function () {
this.modDebug = this.checkFilterKey ("MODDEBUG");
this.modAxes = this.getFilter ("MODAXES=");
this.modType = this.getFilter ("MODTYPE=");
this.modSelected = this.parseIntStr ("" + this.getFilter ("MOD="));
this.modVib = this.checkFilterKey ("MODVIB");
this.modAverage = this.checkFilterKey ("MODAVE");
this.checkSpecial = !this.checkFilterKey ("NOSPECIAL");
this.atomSetCollection.setCheckSpecial (this.checkSpecial);
this.allowRotations = !this.checkFilterKey ("NOSYM");
});
$_M(c$, "setModDim",
function (ndim) {
if (this.modAverage) return;
this.modDim = ndim;
if (this.modDim > 3) {
this.appendLoadNote ("Too high modulation dimension (" + this.modDim + ") -- reading average structure");
this.modDim = 0;
this.modAverage = true;
} else {
this.appendLoadNote ("Modulation dimension = " + this.modDim);
this.htModulation =  new java.util.Hashtable ();
}this.incommensurate = (this.modDim > 0);
}, "~N");
$_M(c$, "getModulationVector",
function (id) {
return this.htModulation.get (id + "@0");
}, "~S");
$_M(c$, "addModulation",
function (map, id, pt, iModel) {
var ch = id.charAt (0);
switch (ch) {
case 'O':
case 'D':
case 'U':
if (this.modType != null && this.modType.indexOf (ch) < 0 || this.modSelected > 0 && this.modSelected != 1) return;
break;
}
if (this.modSelected > 0 && id.contains ("_q_")) switch (this.modSelected) {
case 1:
pt.y = pt.z = 0;
break;
case 2:
pt.x = pt.z = 0;
break;
case 3:
pt.x = pt.y = 0;
break;
}
if (pt.x == 0 && pt.y == 0 && pt.z == 0) return;
if (map == null) map = this.htModulation;
id += "@" + (iModel >= 0 ? iModel : this.atomSetCollection.getCurrentAtomSetIndex ());
J.util.Logger.info ("Adding " + id + " " + pt);
map.put (id, pt);
}, "java.util.Map,~S,J.util.P3,~N");
$_M(c$, "setModulation",
function () {
if (!this.incommensurate || this.htModulation == null) return;
if (this.modDebug) ($t$ = J.util.Logger.debugging = ($t$ = J.util.Logger.debuggingHigh = true, J.util.Logger.prototype.debuggingHigh = J.util.Logger.debuggingHigh, $t$), J.util.Logger.prototype.debugging = J.util.Logger.debugging, $t$);
this.setModulationForStructure (this.atomSetCollection.getCurrentAtomSetIndex ());
if (this.modDebug) ($t$ = J.util.Logger.debugging = ($t$ = J.util.Logger.debuggingHigh = false, J.util.Logger.prototype.debuggingHigh = J.util.Logger.debuggingHigh, $t$), J.util.Logger.prototype.debugging = J.util.Logger.debugging, $t$);
});
$_M(c$, "finalizeModulation",
function () {
if (!this.incommensurate) return;
if (!this.modVib) this.addJmolScript ("modulation on" + (this.haveOccupancy ? ";display occupancy > 0.5" : ""));
});
$_M(c$, "getMod",
($fz = function (key) {
return this.htModulation.get (key + this.suffix);
}, $fz.isPrivate = true, $fz), "~S");
$_M(c$, "setModulationForStructure",
($fz = function (iModel) {
this.suffix = "@" + iModel;
var key;
if (this.htModulation.containsKey ("X_" + this.suffix)) return;
this.htModulation.put ("X_" + this.suffix,  new J.util.P3 ());
this.q123 =  new J.util.Matrix3f ();
this.qlen =  Clazz.newDoubleArray (this.modDim, 0);
for (var i = 0; i < this.modDim; i++) {
var pt = this.getMod ("W_" + (i + 1));
if (pt == null) {
J.util.Logger.info ("Not enough cell wave vectors for d=" + this.modDim);
return;
}if (i == 0) this.q1 = J.util.P3.newP (pt);
this.q123.setRowV (i, pt);
this.qlen[i] = pt.length ();
}
this.q1Norm = J.util.V3.new3 (this.q1.x == 0 ? 0 : 1, this.q1.y == 0 ? 0 : 1, this.q1.z == 0 ? 0 : 1);
var qlist100 = J.util.P3.new3 (1, 0, 0);
var pt;
var n = this.atomSetCollection.getAtomCount ();
var map =  new java.util.Hashtable ();
for (var e, $e = this.htModulation.entrySet ().iterator (); $e.hasNext () && ((e = $e.next ()) || true);) {
if ((key = this.checkKey (e.getKey ())) == null) continue;
pt = e.getValue ();
switch (key.charAt (0)) {
case 'O':
this.haveOccupancy = true;
case 'D':
if (pt.z == 1 && key.charAt (2) != 'S') {
var a = pt.x;
var d = 2 * 3.141592653589793 * pt.y;
pt.x = (a * Math.cos (d));
pt.y = (a * Math.sin (-d));
pt.z = 0;
J.util.Logger.info ("msCIF setting " + key + " " + pt);
}break;
case 'W':
if (this.modDim > 1) {
continue;
}case 'F':
if (key.indexOf ("_q_") >= 0) {
this.appendLoadNote ("Wave vector " + key + "=" + pt);
} else {
var fn = Clazz.floatToInt (pt.dot (this.q1) / this.q1.dot (this.q1) * 1.01);
var k2 = key + "_q_";
if (!this.htModulation.containsKey (k2 + this.suffix)) {
this.addModulation (map, k2, J.util.P3.new3 (fn, 0, 0), iModel);
}}break;
}
}
if (!map.isEmpty ()) this.htModulation.putAll (map);
var haveAtomMods = false;
for (var e, $e = this.htModulation.entrySet ().iterator (); $e.hasNext () && ((e = $e.next ()) || true);) {
if ((key = this.checkKey (e.getKey ())) == null) continue;
var params = e.getValue ();
var atomName = key.substring (key.indexOf (";") + 1);
var pt_ = atomName.indexOf ("#=");
if (pt_ >= 0) {
params = this.getMod (atomName.substring (pt_ + 2));
atomName = atomName.substring (0, pt_);
}if (J.util.Logger.debuggingHigh) J.util.Logger.debug ("SetModulation: " + key + " " + params);
var type = key.charCodeAt (0);
pt_ = key.indexOf ("#") + 1;
var utens = null;
switch (type) {
case 'U':
utens = key.substring (4, key.indexOf (";"));
case 'O':
case 'D':
var id = key.charAt (2);
var axis = key.charAt (pt_);
type = (id == 'S' ? 1 : id == '0' ? 3 : type == 79 ? 2 : type == 85 ? 4 : 0);
if (this.htAtomMods == null) this.htAtomMods =  new java.util.Hashtable ();
var fn = (id == 'S' ? 0 : this.parseIntStr (key.substring (2)));
if (fn == 0) {
this.addAtomModulation (atomName, axis, type, params, utens, qlist100);
} else {
var qlist = this.getMod ("F_" + fn + "_q_");
if (qlist == null) {
J.util.Logger.error ("Missing qlist for F_" + fn);
}this.addAtomModulation (atomName, axis, type, params, utens, qlist);
}haveAtomMods = true;
break;
}
}
if (!haveAtomMods) return;
this.atoms = this.atomSetCollection.getAtoms ();
this.symmetry = this.atomSetCollection.getSymmetry ();
this.iopLast = -1;
var sb =  new J.util.SB ();
for (var i = this.atomSetCollection.getLastAtomSetAtomIndex (); i < n; i++) this.modulateAtom (this.atoms[i], sb);

this.atomSetCollection.setAtomSetAtomProperty ("modt", sb.toString (), -1);
this.htAtomMods = null;
}, $fz.isPrivate = true, $fz), "~N");
$_M(c$, "addAtomModulation",
($fz = function (atomName, axis, type, params, utens, qcoefs) {
var list = this.htAtomMods.get (atomName);
if (list == null) this.htAtomMods.put (atomName, list =  new J.util.JmolList ());
list.addLast ( new J.util.Modulation (axis, type, params, utens, qcoefs));
}, $fz.isPrivate = true, $fz), "~S,~S,~N,J.util.P3,~S,J.util.P3");
$_M(c$, "checkKey",
($fz = function (key) {
var pt_ = key.indexOf (this.suffix);
return (pt_ < 0 ? null : key.substring (0, pt_));
}, $fz.isPrivate = true, $fz), "~S");
$_M(c$, "modulateAtom",
function (a, sb) {
var list = this.htAtomMods.get (a.atomName);
if (list == null || this.symmetry == null || a.bsSymmetry == null) return;
var iop = a.bsSymmetry.nextSetBit (0);
if (iop < 0) iop = 0;
if (J.util.Logger.debuggingHigh) J.util.Logger.debug ("\nsetModulation: i=" + a.index + " " + a.atomName + " xyz=" + a + " occ=" + a.foccupancy);
if (iop != this.iopLast) {
this.iopLast = iop;
this.gammaE =  new J.util.Matrix3f ();
this.symmetry.getSpaceGroupOperation (iop).getRotationScale (this.gammaE);
this.gammaIS = this.symmetry.getOperationGammaIS (iop);
this.nOps = this.symmetry.getSpaceGroupOperationCount ();
}if (J.util.Logger.debugging) {
J.util.Logger.debug ("setModulation iop = " + iop + " " + this.symmetry.getSpaceGroupXyz (iop, false) + " " + a.bsSymmetry);
}var q123w = J.util.Matrix4f.newMV (this.q123,  new J.util.V3 ());
this.setSubsystemMatrix (a.atomName, q123w);
var ms =  new J.util.ModulationSet (a.index + " " + a.atomName, J.util.P3.newP (a), this.modDim, list, this.gammaE, this.gammaIS, q123w, this.qlen);
ms.calculate ();
if (!Float.isNaN (ms.vOcc)) {
var pt = this.getMod ("J_O#0;" + a.atomName);
var occ0 = ms.vOcc0;
var occ;
if (Float.isNaN (occ0)) {
occ = ms.vOcc;
} else if (pt == null) {
occ = a.foccupancy + ms.vOcc;
} else if (a.vib != null) {
var site_mult = a.vib.x;
var o_site = a.foccupancy * site_mult / this.nOps / pt.y;
occ = o_site * (pt.y + ms.vOcc);
} else {
occ = pt.x * (pt.y + ms.vOcc);
}a.foccupancy = Math.min (1, Math.max (0, occ));
a.vib = ms;
}if (ms.htUij != null) {
if (J.util.Logger.debuggingHigh) {
J.util.Logger.debug ("setModulation Uij(initial)=" + J.util.Escape.eAF (a.anisoBorU));
J.util.Logger.debug ("setModulation tensor=" + J.util.Escape.e (a.tensors.get (0).getInfo ("all")));
}for (var e, $e = ms.htUij.entrySet ().iterator (); $e.hasNext () && ((e = $e.next ()) || true);) this.addUStr (a, e.getKey (), e.getValue ().floatValue ());

if (a.tensors != null) a.tensors.get (0).isUnmodulated = true;
var t = this.atomSetCollection.addRotatedTensor (a, this.symmetry.getTensor (a.anisoBorU), iop, false);
t.isModulated = true;
if (J.util.Logger.debuggingHigh) {
J.util.Logger.debug ("setModulation Uij(final)=" + J.util.Escape.eAF (a.anisoBorU) + "\n");
J.util.Logger.debug ("setModulation tensor=" + a.tensors.get (0).getInfo ("all"));
}}if (this.modVib || a.foccupancy != 0) {
var t = this.q1Norm.dot (a);
if (Math.abs (t - Clazz.floatToInt (t)) > 0.001) t = Clazz.doubleToInt (Math.floor (t));
sb.append ((Clazz.floatToInt (t)) + "\n");
}this.symmetry.toCartesian (ms, true);
}, "J.adapter.smarter.Atom,J.util.SB");
$_M(c$, "setSubsystemMatrix",
($fz = function (atomName, q123w) {
var o;
if (true || this.htSubsystems == null || (o = this.htSubsystems.get (";" + atomName)) == null) return;
var subcode = o;
var wmatrix = this.htSubsystems.get (subcode);
q123w.mulM4 (wmatrix);
}, $fz.isPrivate = true, $fz), "~S,J.util.Matrix4f");
$_M(c$, "addSubsystem",
function (code, m4, atomName) {
if (this.htSubsystems == null) this.htSubsystems =  new java.util.Hashtable ();
if (m4 == null) this.htSubsystems.put (";" + atomName, code);
 else this.htSubsystems.put (code, m4);
}, "~S,J.util.Matrix4f,~S");
$_M(c$, "addUStr",
($fz = function (atom, id, val) {
var i = Clazz.doubleToInt ("U11U22U33U12U13U23OTPUISO".indexOf (id) / 3);
if (J.util.Logger.debuggingHigh) J.util.Logger.debug ("MOD RDR adding " + id + " " + i + " " + val + " to " + atom.anisoBorU[i]);
this.setU (atom, i, val + atom.anisoBorU[i]);
}, $fz.isPrivate = true, $fz), "J.adapter.smarter.Atom,~S,~N");
$_M(c$, "setU",
function (atom, i, val) {
var data = this.atomSetCollection.getAnisoBorU (atom);
if (data == null) this.atomSetCollection.setAnisoBorU (atom, data =  Clazz.newFloatArray (8, 0), 8);
data[i] = val;
}, "J.adapter.smarter.Atom,~N,~N");
Clazz.defineStatics (c$,
"U_LIST", "U11U22U33U12U13U23OTPUISO");
});


text:
require 'spec_helper'

describe WeekController do
  after do
    Timecop.return
  end

  let!(:rafal) {create(:user, email: 'rafal@selleo.com', name: 'Rafal', retired: true)}
  let!(:wojtek) {create(:user, email: 'wojtek@selleo.com', name: 'Wojtek', retired: true)}
  let!(:adrian) {create(:user, email: 'adrian@selleo.com', name: 'Adrian')}

  let!(:tom) { create(:user, email: 'tom@selleo.com', name: 'Tom') }
  let!(:bart) { create(:user, email: 'bart@selleo.com', name: 'Bart') }
  let!(:simon) { create(:user, email: 'simon@selleo.com', name: 'Simon') }
  let!(:radek) { create(:user, email: 'radek@selleo.com', name: 'Radek') }
  let!(:stevo) { create(:user, email: 'stevo@selleo.com', name: 'Stevo') }

  before do
    Timecop.freeze(Time.parse('2013-02-27 13:15 UTC'))

    adrian.thanks_to_user(wojtek, {value: 20})

    # bart +13 -1
    tom.thanks_to_user(bart, {value: 3})
    tom.thanks_to_user(bart, {value: 2})
    tom.thanks_to_user(bart, {value: 1})
    simon.thanks_to_user(bart, {value: 5})
    simon.thanks_to_user(bart, {value: 1})

    # tom +1 -6
    simon.thanks_to_user(tom, {value: 1})
    radek.thanks_to_user(bart, {value: 1})

    # radek +3 -1
    simon.thanks_to_user(radek, {value: 2})
    bart.thanks_to_user(radek, {value: 1})
    # simon -9

    Timecop.freeze(Time.parse('2013-03-04 13:15 UTC'))
  end

  describe "top_collectors" do
    before do
      get :top_collectors
    end

    subject(:response_object) { JSON.parse(response.body)["tops"] }
    let(:users) { [tom, bart, radek].map(&:ember_user_info).map(&:stringify_keys) }
    it { expect(response_object).to include(*users) }
  end

  describe "top_hamsters" do
    before do
      get :top_hamsters
    end

    subject(:response_object) { JSON.parse(response.body)["hamsters"] }
    let(:users) { [stevo, bart, radek].map(&:ember_user_info).map(&:stringify_keys) }

    it { expect(response_object).to include(*users) }
  end
end


text:
NAME="Body Sensor Location"
UUID=0x2A38


text:
namespace Coremero.Storage
{
    public interface ICredentialStorage
    {
        string GetKey(string keyName, string defaultKey);
    }
}


text:
package trace

import (
	"context"

	"go.opencensus.io/trace"
	"google.golang.org/api/googleapi"
	"google.golang.org/genproto/googleapis/rpc/code"
	"google.golang.org/grpc/status"
)

// EndSpanFunc is a function that ends a span, reporting an error if necessary.
type EndSpanFunc func(error)

// Attribute annotates a span with additional data.
type Attribute struct {
	key   string
	value interface{}
}

func (a Attribute) traceAttr() trace.Attribute {
	// always use a string attribute for now
	// if need for additional types arise, this can be expanded.
	return trace.StringAttribute(a.key, a.value.(string))
}

// AddInstanceName creates an attribute with the Cloud SQL instance name.
func AddInstanceName(name string) Attribute {
	return Attribute{key: "/cloudsql/instance", value: name}
}

// AddDialerID creates an attribute to identify a particular dialer.
func AddDialerID(dialerID string) Attribute {
	return Attribute{key: "/cloudsql/dialer_id", value: dialerID}
}

// StartSpan begins a span with the provided name and returns a context and a
// function to end the created span.
func StartSpan(ctx context.Context, name string, attrs ...Attribute) (context.Context, EndSpanFunc) {
	var span *trace.Span
	ctx, span = trace.StartSpan(ctx, name)
	as := make([]trace.Attribute, 0, len(attrs))
	for _, a := range attrs {
		as = append(as, a.traceAttr())
	}
	span.AddAttributes(as...)
	return ctx, func(err error) {
		if err != nil {
			span.SetStatus(toStatus(err))
		}
		span.End()
	}
}

// toStatus interrogates an error and converts it to an appropriate
// OpenCensus status.
// Note: this function is borrowed from
// https://github.com/googleapis/google-cloud-go/blob/master/internal/trace/trace.go
func toStatus(err error) trace.Status {
	if err2, ok := err.(*googleapi.Error); ok {
		return trace.Status{Code: httpStatusCodeToOCCode(err2.Code), Message: err2.Message}
	} else if s, ok := status.FromError(err); ok {
		return trace.Status{Code: int32(s.Code()), Message: s.Message()}
	} else {
		return trace.Status{Code: int32(code.Code_UNKNOWN), Message: err.Error()}
	}
}

// Reference: https://github.com/googleapis/googleapis/blob/26b634d2724ac5dd30ae0b0cbfb01f07f2e4050e/google/rpc/code.proto
func httpStatusCodeToOCCode(httpStatusCode int) int32 {
	switch httpStatusCode {
	case 200:
		return int32(code.Code_OK)
	case 499:
		return int32(code.Code_CANCELLED)
	case 500:
		return int32(code.Code_UNKNOWN) // Could also be Code_INTERNAL, Code_DATA_LOSS
	case 400:
		return int32(code.Code_INVALID_ARGUMENT) // Could also be Code_OUT_OF_RANGE
	case 504:
		return int32(code.Code_DEADLINE_EXCEEDED)
	case 404:
		return int32(code.Code_NOT_FOUND)
	case 409:
		return int32(code.Code_ALREADY_EXISTS) // Could also be Code_ABORTED
	case 403:
		return int32(code.Code_PERMISSION_DENIED)
	case 401:
		return int32(code.Code_UNAUTHENTICATED)
	case 429:
		return int32(code.Code_RESOURCE_EXHAUSTED)
	case 501:
		return int32(code.Code_UNIMPLEMENTED)
	case 503:
		return int32(code.Code_UNAVAILABLE)
	default:
		return int32(code.Code_UNKNOWN)
	}
}


text:
use clap::{App, Arg, ArgMatches, SubCommand};
use exercise::{
    cmd::{configure, fetch_configlet, generate, update},
    errors::Result,
};
use failure::format_err;

// Creates a new CLI app with appropriate matches
// and returns the initialized matches.
fn init_app<'a>() -> ArgMatches<'a> {
    App::new(env!("CARGO_PKG_NAME"))
        .version(env!("CARGO_PKG_VERSION"))
        .about(env!("CARGO_PKG_DESCRIPTION"))
        .subcommand(
            SubCommand::with_name("generate")
                .about("Generates new exercise")
                .arg(Arg::with_name("exercise_name").required(true).help("The name of the generated exercise"))
                .arg(Arg::with_name("configure").long("configure").short("c").help(
                    "If set, the command will edit the config.json file after generating the exercise",
                ))
                .arg(Arg::with_name("use_maplit").long("use-maplit").short("m").help("Use the maplit crate to improve the readability of the generated test suite")),
        )
        .subcommand(
            SubCommand::with_name("update")
                .about("Updates the specified exercise")
                .arg(Arg::with_name("exercise_name").help("The name of the updated exercise"))
                .arg(Arg::with_name("use_maplit").long("use-maplit").short("m").help("Use the maplit crate to improve the readability of the updated test suite"))
                .arg(Arg::with_name("dont_update_readme").long("dont-update-readme").short("r").help("If set, the README of the exercise would not be updated"))
                .arg(Arg::with_name("configure").long("configure").short("c").help(
                    "If set, the command will edit the config.json file after updating the exercise",
                ))
        )
        .subcommand(
            SubCommand::with_name("configure")
                .about("Edits config.json for the specified exercise")
                .arg(Arg::with_name("exercise_name").required(true).help("The name of the configured exercise")),
        )
        .subcommand(
            SubCommand::with_name("fetch_configlet")
                .about("Downloads and extracts configlet utility into the repo's /bin directory")
        )
        .get_matches()
}

// Determine which subcommand was used
// and call the appropriate function.
fn process_matches(matches: &ArgMatches<'_>) -> Result<()> {
    match matches.subcommand() {
        ("generate", Some(generate_matches)) => {
            let exercise_name = generate_matches
                .value_of("exercise_name")
                .ok_or_else(|| format_err!("exercise name not present in args"))?;
            let run_configure = generate_matches.is_present("configure");
            let use_maplit = generate_matches.is_present("use_maplit");

            generate::generate_exercise(exercise_name, use_maplit)?;

            if run_configure {
                configure::configure_exercise(exercise_name)?;
            }
        }

        ("update", Some(update_matches)) => {
            let exercise_name = update_matches
                .value_of("exercise_name")
                .ok_or_else(|| format_err!("exercise name not present in args"))?;

            let run_configure = update_matches.is_present("configure");

            let use_maplit = update_matches.is_present("use_maplit");

            let update_readme = !update_matches.is_present("dont_update_readme");

            update::update_exercise(exercise_name, use_maplit)?;

            if run_configure {
                configure::configure_exercise(exercise_name)?;
            }

            if update_readme {
                exercise::run_configlet_command("generate", &[".", "-o", exercise_name])?;
            }
        }

        ("configure", Some(configure_matches)) => {
            configure::configure_exercise(
                configure_matches
                    .value_of("exercise_name")
                    .ok_or_else(|| format_err!("exercise name not present in args"))?,
            )?;
        }

        ("fetch_configlet", Some(_fetch_configlet_matches)) => {
            if let Ok(fetch_path) = fetch_configlet::download() {
                println!(
                    "Downloaded and moved the configlet utility to the {:?} path",
                    fetch_path
                );
            } else {
                println!("Failed to fetch the configlet utility");
            }
        }

        ("", None) => {
            println!("No subcommand was used.\nUse exercise --help to learn about the possible subcommands.");
        }

        _ => unreachable!(),
    };

    Ok(())
}

fn main() -> Result<()> {
    let matches = init_app();

    process_matches(&matches)?;
    Ok(())
}


text:
package com.twilio.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.twilio.sdk.verbs.Say;
import com.twilio.sdk.verbs.TwiMLException;
import com.twilio.sdk.verbs.TwiMLResponse;

@SuppressWarnings("serial")
@WebServlet("/voice")
public class IncomingCallServlet extends HttpServlet {

  // Handle HTTP POST to /voice
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // Create a TwiML builder object
    TwiMLResponse twiml = new TwiMLResponse();
    try {
      Say message = new Say("hello world!");
      message.setVoice("alice");
      twiml.append(message);
    } catch (TwiMLException e) {
      e.printStackTrace();
    }

    // Render TwiML as XML
    response.setContentType("text/xml");
    response.getWriter().print(twiml.toXML());
  }
}


text:
import {Component, OnInit} from '@angular/core';
import {ROUTES} from '../sidebar/sidebar-routes.config';
import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common';

@Component({
    selector: 'navbar',
    templateUrl: 'navbar.component.html'
})

export class NavbarComponent implements OnInit {
    private listTitles: any[];
    private location: Location;

    constructor(location: Location) {
        this.location = location;
    }

    public ngOnInit() {
        this.listTitles = ROUTES.filter((listTitle) => listTitle);
    }

    public getTitle() {
        let titlee = this.location.prepareExternalUrl(this.location.path());
        if (titlee.charAt(0) === '#') {
            titlee = titlee.slice(2);
        }
        for (let item = 0; item < this.listTitles.length; item++) {
            if (this.listTitles[item].path === titlee) {
                return this.listTitles[item].title;
            }
        }
        return 'Dashboard';
    }
}


text:
import pytest

from staty import BadRequestException
from staty.handlers.requests import raise_for_status

def test_basic_response(ok_response):
    response = raise_for_status(ok_response)
    assert response == ok_response

# noinspection PyTypeChecker,PyShadowingNames
def test_error_response(bad_request_response):
    with pytest.raises(BadRequestException):
        raise_for_status(bad_request_response)


text:
var actions = require('./helpers/projectActions.js');

var CREATE_TIMEOUT = 180000;

function createAndBuild(projectname, projectid, done) {
    actions.createProject(projectname, projectid, function (error) {
        expect(error).toBe(null);
        actions.buildProject(projectid, function (error) {
            expect(error).toBe(null);
            actions.removeProject(projectid);
            done();
        });
    });
}

describe('create', function() {

    it('Test#001 : create project with ascii name, no spaces', function(done) {
        var projectname = 'testcreate';
        var projectid = 'com.test.create.app1';

        createAndBuild(projectname, projectid, done);
    }, CREATE_TIMEOUT);

    it('Test#002 : create project with ascii name, and spaces', function(done) {
        var projectname = 'test create';
        var projectid = 'com.test.create.app2';

        createAndBuild(projectname, projectid, done);
    }, CREATE_TIMEOUT);

    it('Test#003 : create project with unicode name, no spaces', function(done) {
        var projectname = '応応応応用用用用';
        var projectid = 'com.test.create.app3';

        createAndBuild(projectname, projectid, done);
    }, CREATE_TIMEOUT);

    it('Test#004 : create project with unicode name, and spaces', function(done) {
        var projectname = '応応応応 用用用用';
        var projectid = 'com.test.create.app4';

        createAndBuild(projectname, projectid, done);
    }, CREATE_TIMEOUT);

    it('Test#005 : create project with ascii+unicode name, no spaces', function(done) {
        var projectname = '応応応応hello用用用用';
        var projectid = 'com.test.create.app5';

        createAndBuild(projectname, projectid, done);
    }, CREATE_TIMEOUT);

    it('Test#006 : create project with ascii+unicode name, and spaces', function(done) {
        var projectname = '応応応応 hello 用用用用';
        var projectid = 'com.test.create.app6';

        createAndBuild(projectname, projectid, done);
    }, CREATE_TIMEOUT);

});