text:
@interface APHParkinsonActivityViewControllerTests : XCTestCase

@end

@interface APCDataArchive (PrivateTest)
@property (nonatomic, strong) NSString *reference;
@property (nonatomic, strong) APCTask *task;
@property (nonatomic, strong) NSNumber *schemaRevision;
@end

@interface APHParkinsonActivityViewController_Test : APHParkinsonActivityViewController
@property (nonatomic) MockAPCUser *mockUser;
@property (nonatomic) ORKTaskResult *overrideTaskResult;
@end

@implementation APHParkinsonActivityViewControllerTests

- (void)setUp {
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

- (void)testDidFinishWithReason_SavedOrComplete
{
    NSArray *reasonsToSave = @[@(ORKTaskViewControllerFinishReasonSaved), @(ORKTaskViewControllerFinishReasonCompleted)];
    for (NSNumber *reason in reasonsToSave) {

        MockAPHMedicationTrackerTask *task = [[MockAPHMedicationTrackerTask alloc] init];
        APHParkinsonActivityViewController_Test *vc = [[APHParkinsonActivityViewController_Test alloc] initWithTask:task taskRunUUID:[NSUUID UUID]];
        task.mockDataStore.skippedSelectMedicationsSurveyQuestion = YES;
        [task.dataGroupsManager setSurveyAnswerWithStepResult:[MockPDResult new]];

        // verify assumptions
        XCTAssertTrue(task.dataStore.hasChanges);
        XCTAssertTrue(task.dataGroupsManager.hasChanges);
        XCTAssertNil(vc.user.dataGroups);

        // Setup an expectation that the user will be updated
        NSString *expectationName = [NSString stringWithFormat:@"expectation with reason %@", reason];
        XCTestExpectation *expectation = [self expectationWithDescription:expectationName];
        vc.mockUser.updateDataGroupsCompletionCalled = ^{
            [expectation fulfill];
        };

        // Expectation is that when the task is finished, if completed or saved that the results
        // Should be saved to the user and data store
        [vc taskViewController:vc didFinishWithReason:[reason unsignedIntegerValue] error:nil];

        // Wait for update to be called
        [self waitForExpectationsWithTimeout:1.0 handler:nil];

        // validated expectations
        XCTAssertFalse(task.dataStore.hasChanges, @"reason=%@", reason);
        XCTAssertTrue(task.mockDataStore.commitChanges_called, @"reason=%@", reason);
        XCTAssertTrue(vc.mockUser.updateDataGroups_called, @"reason=%@", reason);
        NSArray *expectedDataGroups = @[@"parkinsons"];
        XCTAssertEqualObjects(vc.user.dataGroups, expectedDataGroups, @"reason=%@", reason);
    }
}

- (void)testDidFinishWithReason_CancelOrFail
{
    NSArray *reasonsToSave = @[@(ORKTaskViewControllerFinishReasonDiscarded), @(ORKTaskViewControllerFinishReasonFailed)];
    for (NSNumber *reason in reasonsToSave) {

        MockAPHMedicationTrackerTask *task = [[MockAPHMedicationTrackerTask alloc] init];
        APHParkinsonActivityViewController_Test *vc = [[APHParkinsonActivityViewController_Test alloc] initWithTask:task taskRunUUID:[NSUUID UUID]];
        task.mockDataStore.skippedSelectMedicationsSurveyQuestion = YES;
        [task.dataGroupsManager setSurveyAnswerWithStepResult:[MockPDResult new]];

        // verify assumptions
        XCTAssertTrue(task.dataStore.hasChanges);
        XCTAssertTrue(task.dataGroupsManager.hasChanges);
        XCTAssertNil(vc.user.dataGroups);

        // Expectation is that when the task is finished, if completed or saved that the results
        // Should be saved to the user and data store
        NSError *err = [reason unsignedIntegerValue] == ORKTaskViewControllerFinishReasonFailed ? [NSError errorWithDomain:@"foo" code:1 userInfo:nil] : nil;
        [vc taskViewController:vc didFinishWithReason:[reason unsignedIntegerValue] error:err];

        // validated expectations
        XCTAssertFalse(task.dataStore.hasChanges, @"reason=%@", reason);
        XCTAssertTrue(task.mockDataStore.reset_called, @"reason=%@", reason);
        XCTAssertFalse(task.mockDataStore.commitChanges_called, @"reason=%@", reason);
        XCTAssertFalse(vc.mockUser.updateDataGroups_called, @"reason=%@", reason);
        XCTAssertNil(vc.user.dataGroups);
    }
}

- (void)testArchiveResults_NoSubTask
{
    APHParkinsonActivityViewController_Test *vc = [self createViewController:NO trackedMedications:nil];
    MockAPCTaskResultArchiver *mockArchiver = (MockAPCTaskResultArchiver *)vc.taskResultArchiver;

    // Setup results
    vc.overrideTaskResult = [[ORKTaskResult alloc] initWithIdentifier:APHMedicationTrackerTaskIdentifier];
    vc.overrideTaskResult.results = @[[[ORKStepResult alloc] initWithIdentifier:APCDataGroupsStepIdentifier],
                                      [[ORKStepResult alloc] initWithIdentifier:APHMedicationTrackerSelectionStepIdentifier],
                                      [[ORKStepResult alloc] initWithIdentifier:APHMedicationTrackerFrequencyStepIdentifier]];

    // Run method under test
    [vc archiveResults];

    // For the case where the survey is the activity (not a subtask of another activity) then the base archive
    // should point at the medication survey results
    XCTAssertNil(vc.medicationTrackerArchive);
    XCTAssertNotNil(vc.archive);
    XCTAssertEqual(mockArchiver.archivedResults.count, 1);
    NSDictionary *archivedObjects = [[mockArchiver.archivedResults allValues] firstObject];
    XCTAssertEqualObjects(archivedObjects[@"archive"], vc.archive);
    XCTAssertEqualObjects(archivedObjects[@"result"], vc.overrideTaskResult);
    XCTAssertEqualObjects(vc.archive.reference, vc.overrideTaskResult.identifier);
    XCTAssertNotNil(vc.archive.task);
}

- (void)testArchiveResults_NoMedicationTracking_NoMomentInDayResult
{
    APHParkinsonActivityViewController_Test *vc = [self createViewController:YES trackedMedications:@[]];
    MockAPCTaskResultArchiver *mockArchiver = (MockAPCTaskResultArchiver *)vc.taskResultArchiver;

    // Setup results
    vc.overrideTaskResult = [[ORKTaskResult alloc] initWithIdentifier:@"Tapping Activity"];
    vc.overrideTaskResult.results = @[[[ORKStepResult alloc] initWithIdentifier:@"tapping.result"]];

    // Run method under test
    [vc archiveResults];

    // If there are no medication tracking results then the med archive is not created, but the
    // results should still include a moment in day result
    XCTAssertNil(vc.medicationTrackerArchive);
    XCTAssertNotNil(vc.archive);
    XCTAssertEqual(mockArchiver.archivedResults.count, 1);
    NSDictionary *archivedObjects = [[mockArchiver.archivedResults allValues] firstObject];
    XCTAssertEqualObjects(archivedObjects[@"archive"], vc.archive);

    ORKTaskResult *archivedResult = archivedObjects[@"result"];
    XCTAssertNotEqualObjects(archivedResult, vc.overrideTaskResult);
    XCTAssertNotNil([archivedResult resultForIdentifier:APHMedicationTrackerMomentInDayStepIdentifier]);
    XCTAssertNotNil([archivedResult resultForIdentifier:@"tapping.result"]);
    XCTAssertEqualObjects(vc.archive.reference, @"abc123");
    XCTAssertNotNil(vc.archive.task);
}

- (void)testArchiveResults_NoMedicationTracking_WithMomentInDayResult
{
    APHParkinsonActivityViewController_Test *vc = [self createViewController:YES trackedMedications:@[@"Levodopa"]];
    MockAPCTaskResultArchiver *mockArchiver = (MockAPCTaskResultArchiver *)vc.taskResultArchiver;

    // Setup results
    vc.overrideTaskResult = [[ORKTaskResult alloc] initWithIdentifier:@"Tapping Activity"];
    vc.overrideTaskResult.results = @[[[ORKStepResult alloc] initWithIdentifier:APHMedicationTrackerMomentInDayStepIdentifier],
                                      [[ORKStepResult alloc] initWithIdentifier:APHMedicationTrackerActivityTimingStepIdentifier],
                                      [[ORKStepResult alloc] initWithIdentifier:@"tapping.result"]];

    // Run method under test
    [vc archiveResults];

    // If there are no medication tracking results then the med archive is not created, and
    // because there is a moment in day result, it should be included.
    XCTAssertNil(vc.medicationTrackerArchive);
    XCTAssertNotNil(vc.archive);
    XCTAssertEqual(mockArchiver.archivedResults.count, 1);
    NSDictionary *archivedObjects = [[mockArchiver.archivedResults allValues] firstObject];
    XCTAssertEqualObjects(archivedObjects[@"archive"], vc.archive);
    ORKTaskResult *archivedResult = archivedObjects[@"result"];
    XCTAssertEqualObjects(archivedResult, vc.overrideTaskResult);
    XCTAssertEqualObjects(vc.archive.reference,  @"abc123");
    XCTAssertNotNil(vc.archive.task);
}

- (void)testArchiveResults_WithMedicationTracking_NoMomentInDayResult
{
    APHParkinsonActivityViewController_Test *vc = [self createViewController:YES trackedMedications:@[]];
    MockAPCTaskResultArchiver *mockArchiver = (MockAPCTaskResultArchiver *)vc.taskResultArchiver;

    // Setup results
    vc.overrideTaskResult = [[ORKTaskResult alloc] initWithIdentifier:@"Tapping Activity"];
    vc.overrideTaskResult.results = @[[[ORKStepResult alloc] initWithIdentifier:APCDataGroupsStepIdentifier],
                                      [[ORKStepResult alloc] initWithIdentifier:APHMedicationTrackerSelectionStepIdentifier],
                                      [[ORKStepResult alloc] initWithIdentifier:@"tapping.result"]];

    // Run method under test
    [vc archiveResults];

    // If there are medication tracking results then the med archive is created, and the
    // results should include a moment in day result
    XCTAssertNotNil(vc.medicationTrackerArchive);
    XCTAssertNotNil(vc.archive);
    XCTAssertEqual(mockArchiver.archivedResults.count, 2);

    NSDictionary *archivedObjects = mockArchiver.archivedResults[@"Tapping Activity"];
    XCTAssertEqualObjects(archivedObjects[@"archive"], vc.archive);
    ORKTaskResult *archivedResult = archivedObjects[@"result"];
    XCTAssertNotEqualObjects(archivedResult, vc.overrideTaskResult);
    XCTAssertNotNil([archivedResult resultForIdentifier:APHMedicationTrackerMomentInDayStepIdentifier]);
    XCTAssertNotNil([archivedResult resultForIdentifier:@"tapping.result"]);
    XCTAssertEqualObjects(vc.archive.reference,  @"abc123");
    XCTAssertNotNil(vc.archive.task);

    NSDictionary *medArchive = mockArchiver.archivedResults[APHMedicationTrackerTaskIdentifier];
    XCTAssertEqualObjects(medArchive[@"archive"], vc.medicationTrackerArchive);
    ORKTaskResult *medResult = medArchive[@"result"];
    XCTAssertNotNil([medResult resultForIdentifier:APCDataGroupsStepIdentifier]);
    XCTAssertNotNil([medResult resultForIdentifier:APHMedicationTrackerSelectionStepIdentifier]);
    XCTAssertEqualObjects(vc.medicationTrackerArchive.reference,  APHMedicationTrackerTaskIdentifier);
    XCTAssertNil(vc.medicationTrackerArchive.task);
    XCTAssertEqualObjects(vc.medicationTrackerArchive.schemaRevision, @(8));
}

- (void)testArchiveResults_WithMedicationTracking_WithMomentInDayResult
{
    APHParkinsonActivityViewController_Test *vc = [self createViewController:YES trackedMedications:@[@"Levopdopa"]];
    MockAPCTaskResultArchiver *mockArchiver = (MockAPCTaskResultArchiver *)vc.taskResultArchiver;

    // Setup results
    vc.overrideTaskResult = [[ORKTaskResult alloc] initWithIdentifier:@"Tapping Activity"];
    vc.overrideTaskResult.results = @[[[ORKStepResult alloc] initWithIdentifier:APCDataGroupsStepIdentifier],
                                      [[ORKStepResult alloc] initWithIdentifier:APHMedicationTrackerSelectionStepIdentifier],
                                      [[ORKStepResult alloc] initWithIdentifier:APHMedicationTrackerFrequencyStepIdentifier],
                                      [[ORKStepResult alloc] initWithIdentifier:APHMedicationTrackerMomentInDayStepIdentifier],
                                      [[ORKStepResult alloc] initWithIdentifier:APHMedicationTrackerActivityTimingStepIdentifier],
                                      [[ORKStepResult alloc] initWithIdentifier:@"tapping.result"]];

    // Run method under test
    [vc archiveResults];

    // If there are medication tracking results then the med archive is created, and the
    // results should include a moment in day result
    XCTAssertNotNil(vc.medicationTrackerArchive);
    XCTAssertNotNil(vc.archive);
    XCTAssertEqual(mockArchiver.archivedResults.count, 2);

    NSDictionary *archivedObjects = mockArchiver.archivedResults[@"Tapping Activity"];
    XCTAssertEqualObjects(archivedObjects[@"archive"], vc.archive);
    ORKTaskResult *archivedResult = archivedObjects[@"result"];
    XCTAssertNotEqualObjects(archivedResult, vc.overrideTaskResult);
    XCTAssertNotNil([archivedResult resultForIdentifier:APHMedicationTrackerMomentInDayStepIdentifier]);
    XCTAssertNotNil([archivedResult resultForIdentifier:@"tapping.result"]);
    XCTAssertEqualObjects(vc.archive.reference,  @"abc123");
    XCTAssertNotNil(vc.archive.task);

    NSDictionary *medArchive = mockArchiver.archivedResults[APHMedicationTrackerTaskIdentifier];
    XCTAssertEqualObjects(medArchive[@"archive"], vc.medicationTrackerArchive);
    ORKTaskResult *medResult = medArchive[@"result"];
    XCTAssertNotNil([medResult resultForIdentifier:APCDataGroupsStepIdentifier]);
    XCTAssertNotNil([medResult resultForIdentifier:APHMedicationTrackerSelectionStepIdentifier]);
    XCTAssertNotNil([medResult resultForIdentifier:APHMedicationTrackerFrequencyStepIdentifier]);
    XCTAssertEqualObjects(vc.medicationTrackerArchive.reference,  APHMedicationTrackerTaskIdentifier);
    XCTAssertNil(vc.medicationTrackerArchive.task);
    XCTAssertEqualObjects(vc.medicationTrackerArchive.schemaRevision, @(8));
}

#pragma mark - helper methods

- (APHParkinsonActivityViewController_Test*)createViewController:(BOOL)hasSubTask trackedMedications:(NSArray*)trackedMedications {

    ORKOrderedTask  *inputTask = !hasSubTask ? nil : [ORKOrderedTask shortWalkTaskWithIdentifier:@"abc123"
                                                      intendedUseDescription:nil
                                                         numberOfStepsPerLeg:20
                                                                restDuration:10
                                                                     options:ORKPredefinedTaskOptionNone];
    MockAPHMedicationTrackerTask *task = [[MockAPHMedicationTrackerTask alloc] initWithDictionaryRepresentation:nil subTask:inputTask];
    APHParkinsonActivityViewController_Test *vc = [[APHParkinsonActivityViewController_Test alloc] initWithTask:task taskRunUUID:[NSUUID UUID]];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"APCTask" inManagedObjectContext:vc.mockUser.tempContext];
    vc.scheduledTask = [[APCTask alloc] initWithEntity:entity insertIntoManagedObjectContext:vc.mockUser.tempContext];
    MockAPCTaskResultArchiver *mockArchiver = [[MockAPCTaskResultArchiver alloc] init];
    vc.taskResultArchiver = mockArchiver;

    // If the tracked meds is non-nil, then set the value to the data store
    if (trackedMedications != nil) {
        NSMutableArray *meds = [NSMutableArray new];
        for (NSString *name in trackedMedications) {
            APHMedication *med = [APHMedication new];
            med.name = name;
            med.tracking = YES;
            [meds addObject:med];
        }
        task.mockDataStore.selectedMedications = meds;
        [task.mockDataStore commitChanges];
        task.mockDataGroupsManager.surveyStepResult = [MockPDResult new];
    }

    return vc;
}

@end

@implementation APHParkinsonActivityViewController_Test

- (MockAPCUser *)mockUser {
    if (_mockUser == nil) {
        _mockUser = [[MockAPCUser alloc] init];
    }
    return _mockUser;
}

- (APCUser *)user {
    return (id)self.mockUser;
}

- (ORKTaskResult *)result {
    return self.overrideTaskResult ?: [super result];
}

@end


text:
<?php

namespace ProdeMundial\CoreBundle\Manager;

use Doctrine\ORM\EntityManager;
use ProdeMundial\CoreBundle\Entity\User;

class StandingsManager
{
    private $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    /**
     * @return \Doctrine\ORM\QueryBuilder
     */
    private function getBaseQuery()
    {
        $date = new \DateTime();
        $query = $this->em->getRepository('ProdeMundialCoreBundle:Prediction')
            ->createQueryBuilder('p')
            ->select('u.username', 'count(p.id) as points')
            ->leftJoin('p.game', 'g')
            ->leftJoin('p.user', 'u')
            ->andWhere('p.result = g.prodeResult')
            ->groupBy('u')
            ->orderBy('points', 'DESC')
        ;

        return $query;
    }

    public function getGeneralStandings()
    {
        $users = $this->em->getRepository('ProdeMundialCoreBundle:User')->findAll();
        $results = $this->getBaseQuery()->getQuery()->getResult();

        return $this->completeStandings($results, $users);
    }

    public function getPaidStandings()
    {
        $users = $this->em->getRepository('ProdeMundialCoreBundle:User')->findByPaymentDone(true);
        $results = $this->getBaseQuery()->andWhere('u.paymentDone = 1')->getQuery()->getResult();

        return $this->completeStandings($results, $users);
    }

    public function getFreeStandings()
    {
        $users = $this->em->getRepository('ProdeMundialCoreBundle:User')->findByPaymentDone(false);
        $results = $this->getBaseQuery()->andWhere('u.paymentDone = 0')->getQuery()->getResult();

        return $this->completeStandings($results, $users);
    }

    private function completeStandings($results, $users)
    {
        /** @var User $user */
        foreach($users as $user) {
            if(!$this->in_array_r($user->getUsername(), $results, true)) {
                $results[] = array(
                    'username' => $user->getUsername(),
                    'points' => 0
                );
            }
        }

        return $results;
    }

    private function in_array_r($needle, $haystack, $strict = false) {
        foreach ($haystack as $item) {
            if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && $this->in_array_r($needle, $item, $strict))) {
                return true;
            }
        }

        return false;
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "network-commissioning.h"

#include <app-common/zap-generated/attributes/Accessors.h>
#include <app-common/zap-generated/cluster-objects.h>
#include <app/CommandHandlerInterface.h>
#include <app/InteractionModelEngine.h>
#include <app/clusters/general-commissioning-server/general-commissioning-server.h>
#include <app/server/Server.h>
#include <app/util/attribute-storage.h>
#include <lib/support/SafeInt.h>
#include <lib/support/SortUtils.h>
#include <lib/support/ThreadOperationalDataset.h>
#include <platform/DeviceControlServer.h>
#include <platform/PlatformManager.h>
#include <platform/internal/DeviceNetworkInfo.h>
#include <trace/trace.h>

using namespace chip;
using namespace chip::app;
using namespace chip::app::Clusters;
using namespace chip::app::Clusters::NetworkCommissioning;

namespace chip {
namespace app {
namespace Clusters {
namespace NetworkCommissioning {

using namespace DeviceLayer::NetworkCommissioning;

namespace {
// For WiFi and Thread scan results, each item will cose ~60 bytes in TLV, thus 15 is a safe upper bound of scan results.
constexpr size_t kMaxNetworksInScanResponse = 15;

enum ValidWiFiCredentialLength
{
    kOpen      = 0,
    kWEP64     = 5,
    kMinWPAPSK = 8,
    kMaxWPAPSK = 63,
    kWPAPSKHex = 64,
};

} // namespace

CHIP_ERROR Instance::Init()
{
    ReturnErrorOnFailure(chip::app::InteractionModelEngine::GetInstance()->RegisterCommandHandler(this));
    VerifyOrReturnError(registerAttributeAccessOverride(this), CHIP_ERROR_INCORRECT_STATE);
    ReturnErrorOnFailure(DeviceLayer::PlatformMgrImpl().AddEventHandler(OnPlatformEventHandler, reinterpret_cast<intptr_t>(this)));
    ReturnErrorOnFailure(mpBaseDriver->Init(this));
    mLastNetworkingStatusValue.SetNull();
    mLastConnectErrorValue.SetNull();
    mLastNetworkIDLen = 0;
    return CHIP_NO_ERROR;
}

void Instance::Shutdown()
{
    mpBaseDriver->Shutdown();
}

void Instance::InvokeCommand(HandlerContext & ctxt)
{
    if (mAsyncCommandHandle.Get() != nullptr)
    {
        // We have a command processing in the backend, reject all incoming commands.
        ctxt.mCommandHandler.AddStatus(ctxt.mRequestPath, Protocols::InteractionModel::Status::Busy);
        ctxt.SetCommandHandled();
        return;
    }

    // Since mPath is used for building the response command, and we have checked that we are not pending the response of another
    // command above. So it is safe to set the mPath here and not clear it when return.
    mPath = ctxt.mRequestPath;

    switch (ctxt.mRequestPath.mCommandId)
    {
    case Commands::ScanNetworks::Id:
        VerifyOrReturn(mFeatureFlags.Has(NetworkCommissioningFeature::kWiFiNetworkInterface) ||
                       mFeatureFlags.Has(NetworkCommissioningFeature::kThreadNetworkInterface));
        HandleCommand<Commands::ScanNetworks::DecodableType>(
            ctxt, [this](HandlerContext & ctx, const auto & req) { HandleScanNetworks(ctx, req); });
        return;

    case Commands::AddOrUpdateWiFiNetwork::Id:
        VerifyOrReturn(mFeatureFlags.Has(NetworkCommissioningFeature::kWiFiNetworkInterface));
        HandleCommand<Commands::AddOrUpdateWiFiNetwork::DecodableType>(
            ctxt, [this](HandlerContext & ctx, const auto & req) { HandleAddOrUpdateWiFiNetwork(ctx, req); });
        return;

    case Commands::AddOrUpdateThreadNetwork::Id:
        VerifyOrReturn(mFeatureFlags.Has(NetworkCommissioningFeature::kThreadNetworkInterface));
        HandleCommand<Commands::AddOrUpdateThreadNetwork::DecodableType>(
            ctxt, [this](HandlerContext & ctx, const auto & req) { HandleAddOrUpdateThreadNetwork(ctx, req); });
        return;

    case Commands::RemoveNetwork::Id:
        VerifyOrReturn(mFeatureFlags.Has(NetworkCommissioningFeature::kWiFiNetworkInterface) ||
                       mFeatureFlags.Has(NetworkCommissioningFeature::kThreadNetworkInterface));
        HandleCommand<Commands::RemoveNetwork::DecodableType>(
            ctxt, [this](HandlerContext & ctx, const auto & req) { HandleRemoveNetwork(ctx, req); });
        return;

    case Commands::ConnectNetwork::Id:
        VerifyOrReturn(mFeatureFlags.Has(NetworkCommissioningFeature::kWiFiNetworkInterface) ||
                       mFeatureFlags.Has(NetworkCommissioningFeature::kThreadNetworkInterface));
        HandleCommand<Commands::ConnectNetwork::DecodableType>(
            ctxt, [this](HandlerContext & ctx, const auto & req) { HandleConnectNetwork(ctx, req); });
        return;

    case Commands::ReorderNetwork::Id:
        VerifyOrReturn(mFeatureFlags.Has(NetworkCommissioningFeature::kWiFiNetworkInterface) ||
                       mFeatureFlags.Has(NetworkCommissioningFeature::kThreadNetworkInterface));
        HandleCommand<Commands::ReorderNetwork::DecodableType>(
            ctxt, [this](HandlerContext & ctx, const auto & req) { HandleReorderNetwork(ctx, req); });
        return;
    }
}

CHIP_ERROR Instance::Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder)
{
    switch (aPath.mAttributeId)
    {
    case Attributes::MaxNetworks::Id:
        return aEncoder.Encode(mpBaseDriver->GetMaxNetworks());

    case Attributes::Networks::Id:
        return aEncoder.EncodeList([this](const auto & encoder) {
            auto networks  = mpBaseDriver->GetNetworks();
            CHIP_ERROR err = CHIP_NO_ERROR;
            Structs::NetworkInfo::Type networkForEncode;
            NetworkCommissioning::Network network;
            for (; networks != nullptr && networks->Next(network);)
            {
                networkForEncode.networkID = ByteSpan(network.networkID, network.networkIDLen);
                networkForEncode.connected = network.connected;
                SuccessOrExit(err = encoder.Encode(networkForEncode));
            }
        exit:
            if (networks != nullptr)
            {
                networks->Release();
            }

            return err;
        });

    case Attributes::ScanMaxTimeSeconds::Id:
        if (mpWirelessDriver != nullptr)
        {
            return aEncoder.Encode(mpWirelessDriver->GetScanNetworkTimeoutSeconds());
        }
        return CHIP_NO_ERROR;

    case Attributes::ConnectMaxTimeSeconds::Id:
        if (mpWirelessDriver != nullptr)
        {
            return aEncoder.Encode(mpWirelessDriver->GetConnectNetworkTimeoutSeconds());
        }
        return CHIP_NO_ERROR;

    case Attributes::InterfaceEnabled::Id:
        return aEncoder.Encode(mpBaseDriver->GetEnabled());

    case Attributes::LastNetworkingStatus::Id:
        return aEncoder.Encode(mLastNetworkingStatusValue);

    case Attributes::LastNetworkID::Id:
        if (mLastNetworkIDLen == 0)
        {
            return aEncoder.EncodeNull();
        }
        else
        {
            return aEncoder.Encode(ByteSpan(mLastNetworkID, mLastNetworkIDLen));
        }

    case Attributes::LastConnectErrorValue::Id:
        return aEncoder.Encode(mLastConnectErrorValue);

    case Attributes::FeatureMap::Id:
        return aEncoder.Encode(mFeatureFlags);

    default:
        return CHIP_NO_ERROR;
    }
}

CHIP_ERROR Instance::Write(const ConcreteDataAttributePath & aPath, AttributeValueDecoder & aDecoder)
{
    switch (aPath.mAttributeId)
    {
    case Attributes::InterfaceEnabled::Id:
        bool value;
        ReturnErrorOnFailure(aDecoder.Decode(value));
        return mpBaseDriver->SetEnabled(value);
    default:
        return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
    }
}

void Instance::OnNetworkingStatusChange(NetworkCommissioning::Status aCommissioningError, Optional<ByteSpan> aNetworkId,
                                        Optional<int32_t> aConnectStatus)
{
    if (aNetworkId.HasValue() && aNetworkId.Value().size() > kMaxNetworkIDLen)
    {
        ChipLogError(DeviceLayer, "Invalid network id received when calling OnNetworkingStatusChange");
        return;
    }
    mLastNetworkingStatusValue.SetNonNull(aCommissioningError);
    if (aNetworkId.HasValue())
    {
        memcpy(mLastNetworkID, aNetworkId.Value().data(), aNetworkId.Value().size());
        mLastNetworkIDLen = static_cast<uint8_t>(aNetworkId.Value().size());
    }
    else
    {
        mLastNetworkIDLen = 0;
    }
    if (aConnectStatus.HasValue())
    {
        mLastConnectErrorValue.SetNonNull(aConnectStatus.Value());
    }
    else
    {
        mLastConnectErrorValue.SetNull();
    }
}

void Instance::HandleScanNetworks(HandlerContext & ctx, const Commands::ScanNetworks::DecodableType & req)
{
    MATTER_TRACE_EVENT_SCOPE("HandleScanNetwork", "NetworkCommissioning");
    if (mFeatureFlags.Has(NetworkCommissioningFeature::kWiFiNetworkInterface))
    {
        ByteSpan ssid;
        if (req.ssid.HasValue())
        {
            const auto & nullableSSID = req.ssid.Value();
            if (!nullableSSID.IsNull())
            {
                ssid = nullableSSID.Value();
                if (ssid.empty())
                {
                    // Normalize empty span value to null ByteSpan.
                    // Spec 7.17.1. Empty string is an equivalent of null.
                    ssid = ByteSpan();
                }
            }
        }
        if (ssid.size() > DeviceLayer::Internal::kMaxWiFiSSIDLength)
        {
            ctx.mCommandHandler.AddStatus(ctx.mRequestPath, Protocols::InteractionModel::Status::InvalidCommand);
            return;
        }
        mCurrentOperationBreadcrumb = req.breadcrumb;
        mAsyncCommandHandle         = CommandHandler::Handle(&ctx.mCommandHandler);
        ctx.mCommandHandler.FlushAcksRightAwayOnSlowCommand();
        mpDriver.Get<WiFiDriver *>()->ScanNetworks(ssid, this);
    }
    else if (mFeatureFlags.Has(NetworkCommissioningFeature::kThreadNetworkInterface))
    {
        mCurrentOperationBreadcrumb = req.breadcrumb;
        mAsyncCommandHandle         = CommandHandler::Handle(&ctx.mCommandHandler);
        ctx.mCommandHandler.FlushAcksRightAwayOnSlowCommand();
        mpDriver.Get<ThreadDriver *>()->ScanNetworks(this);
    }
    else
    {
        ctx.mCommandHandler.AddStatus(ctx.mRequestPath, Protocols::InteractionModel::Status::UnsupportedCommand);
    }
}

namespace {

void FillDebugTextAndNetworkIndex(Commands::NetworkConfigResponse::Type & response, MutableCharSpan debugText, uint8_t networkIndex)
{
    if (!debugText.empty())
    {
        response.debugText.SetValue(CharSpan(debugText.data(), debugText.size()));
    }
    if (response.networkingStatus == NetworkCommissioningStatus::kSuccess)
    {
        response.networkIndex.SetValue(networkIndex);
    }
}

bool CheckFailSafeArmed(CommandHandlerInterface::HandlerContext & ctx)
{
    auto & failSafeContext = chip::Server::GetInstance().GetFailSafeContext();

    if (failSafeContext.IsFailSafeArmed(ctx.mCommandHandler.GetAccessingFabricIndex()))
    {
        return true;
    }

    ctx.mCommandHandler.AddStatus(ctx.mRequestPath, Protocols::InteractionModel::Status::FailsafeRequired);
    return false;
}

} // namespace

void Instance::HandleAddOrUpdateWiFiNetwork(HandlerContext & ctx, const Commands::AddOrUpdateWiFiNetwork::DecodableType & req)
{
    MATTER_TRACE_EVENT_SCOPE("HandleAddOrUpdateWiFiNetwork", "NetworkCommissioning");

    VerifyOrReturn(CheckFailSafeArmed(ctx));

    // Spec 11.8.8.4
    // Valid Credentials length are:
    // - 0 bytes: Unsecured (open) connection
    // - 5 bytes: WEP-64 passphrase
    // - 10 hexadecimal ASCII characters: WEP-64 40-bit hex raw PSK
    // - 13 bytes: WEP-128 passphrase
    // - 26 hexadecimal ASCII characters: WEP-128 104-bit hex raw PSK
    // - 8..63 bytes: WPA/WPA2/WPA3 passphrase
    // - 64 bytes: WPA/WPA2/WPA3 raw hex PSK
    // Note 10 hex WEP64 and 13 bytes / 26 hex WEP128 passphrase are covered by 8~63 bytes WPA passphrase, so we don't check WEP64
    // hex and WEP128 passphrase.
    if (req.credentials.size() == ValidWiFiCredentialLength::kOpen || req.credentials.size() == ValidWiFiCredentialLength::kWEP64 ||
        (req.credentials.size() >= ValidWiFiCredentialLength::kMinWPAPSK &&
         req.credentials.size() <= ValidWiFiCredentialLength::kMaxWPAPSK))
    {
        // Valid length, the credentials can have any characters.
    }
    else if (req.credentials.size() == ValidWiFiCredentialLength::kWPAPSKHex)
    {
        for (size_t d = 0; d < req.credentials.size(); d++)
        {
            if (!isxdigit(req.credentials.data()[d]))
            {
                ctx.mCommandHandler.AddStatus(ctx.mRequestPath, Protocols::InteractionModel::Status::InvalidCommand);
                return;
            }
        }
    }
    else
    {
        // Invalid length
        ctx.mCommandHandler.AddStatus(ctx.mRequestPath, Protocols::InteractionModel::Status::InvalidCommand);
        return;
    }

    Commands::NetworkConfigResponse::Type response;
    MutableCharSpan debugText;
#if CHIP_CONFIG_NETWORK_COMMISSIONING_DEBUG_TEXT_BUFFER_SIZE
    char debugTextBuffer[CHIP_CONFIG_NETWORK_COMMISSIONING_DEBUG_TEXT_BUFFER_SIZE];
    debugText = MutableCharSpan(debugTextBuffer);
#endif
    uint8_t outNetworkIndex = 0;
    response.networkingStatus =
        mpDriver.Get<WiFiDriver *>()->AddOrUpdateNetwork(req.ssid, req.credentials, debugText, outNetworkIndex);
    FillDebugTextAndNetworkIndex(response, debugText, outNetworkIndex);
    ctx.mCommandHandler.AddResponse(ctx.mRequestPath, response);
    if (response.networkingStatus == NetworkCommissioningStatus::kSuccess)
    {
        UpdateBreadcrumb(req.breadcrumb);
    }
}

void Instance::HandleAddOrUpdateThreadNetwork(HandlerContext & ctx, const Commands::AddOrUpdateThreadNetwork::DecodableType & req)
{
    MATTER_TRACE_EVENT_SCOPE("HandleAddOrUpdateThreadNetwork", "NetworkCommissioning");

    VerifyOrReturn(CheckFailSafeArmed(ctx));

    Commands::NetworkConfigResponse::Type response;
    MutableCharSpan debugText;
#if CHIP_CONFIG_NETWORK_COMMISSIONING_DEBUG_TEXT_BUFFER_SIZE
    char debugTextBuffer[CHIP_CONFIG_NETWORK_COMMISSIONING_DEBUG_TEXT_BUFFER_SIZE];
    debugText = MutableCharSpan(debugTextBuffer);
#endif
    uint8_t outNetworkIndex = 0;
    response.networkingStatus =
        mpDriver.Get<ThreadDriver *>()->AddOrUpdateNetwork(req.operationalDataset, debugText, outNetworkIndex);
    FillDebugTextAndNetworkIndex(response, debugText, outNetworkIndex);
    ctx.mCommandHandler.AddResponse(ctx.mRequestPath, response);
    if (response.networkingStatus == NetworkCommissioningStatus::kSuccess)
    {
        UpdateBreadcrumb(req.breadcrumb);
    }
}

void Instance::UpdateBreadcrumb(const Optional<uint64_t> & breadcrumb)
{
    VerifyOrReturn(breadcrumb.HasValue());
    GeneralCommissioning::SetBreadcrumb(breadcrumb.Value());
}

void Instance::CommitSavedBreadcrumb()
{
    // We rejected the command when there is another ongoing command, so mCurrentOperationBreadcrumb reflects the breadcrumb
    // argument in the only background command.
    UpdateBreadcrumb(mCurrentOperationBreadcrumb);
    mCurrentOperationBreadcrumb.ClearValue();
}

void Instance::HandleRemoveNetwork(HandlerContext & ctx, const Commands::RemoveNetwork::DecodableType & req)
{
    MATTER_TRACE_EVENT_SCOPE("HandleRemoveNetwork", "NetworkCommissioning");

    VerifyOrReturn(CheckFailSafeArmed(ctx));

    Commands::NetworkConfigResponse::Type response;
    MutableCharSpan debugText;
#if CHIP_CONFIG_NETWORK_COMMISSIONING_DEBUG_TEXT_BUFFER_SIZE
    char debugTextBuffer[CHIP_CONFIG_NETWORK_COMMISSIONING_DEBUG_TEXT_BUFFER_SIZE];
    debugText = MutableCharSpan(debugTextBuffer);
#endif
    uint8_t outNetworkIndex   = 0;
    response.networkingStatus = mpWirelessDriver->RemoveNetwork(req.networkID, debugText, outNetworkIndex);
    FillDebugTextAndNetworkIndex(response, debugText, outNetworkIndex);
    ctx.mCommandHandler.AddResponse(ctx.mRequestPath, response);
    if (response.networkingStatus == NetworkCommissioningStatus::kSuccess)
    {
        UpdateBreadcrumb(req.breadcrumb);
    }
}

void Instance::HandleConnectNetwork(HandlerContext & ctx, const Commands::ConnectNetwork::DecodableType & req)
{
    MATTER_TRACE_EVENT_SCOPE("HandleConnectNetwork", "NetworkCommissioning");
    if (req.networkID.size() > DeviceLayer::NetworkCommissioning::kMaxNetworkIDLen)
    {
        ctx.mCommandHandler.AddStatus(ctx.mRequestPath, Protocols::InteractionModel::Status::InvalidValue);
        return;
    }

    VerifyOrReturn(CheckFailSafeArmed(ctx));

    mConnectingNetworkIDLen = static_cast<uint8_t>(req.networkID.size());
    memcpy(mConnectingNetworkID, req.networkID.data(), mConnectingNetworkIDLen);
    mAsyncCommandHandle         = CommandHandler::Handle(&ctx.mCommandHandler);
    mCurrentOperationBreadcrumb = req.breadcrumb;
    mpWirelessDriver->ConnectNetwork(req.networkID, this);
}

void Instance::HandleReorderNetwork(HandlerContext & ctx, const Commands::ReorderNetwork::DecodableType & req)
{
    MATTER_TRACE_EVENT_SCOPE("HandleReorderNetwork", "NetworkCommissioning");
    Commands::NetworkConfigResponse::Type response;
    MutableCharSpan debugText;
#if CHIP_CONFIG_NETWORK_COMMISSIONING_DEBUG_TEXT_BUFFER_SIZE
    char debugTextBuffer[CHIP_CONFIG_NETWORK_COMMISSIONING_DEBUG_TEXT_BUFFER_SIZE];
    debugText = MutableCharSpan(debugTextBuffer);
#endif
    response.networkingStatus = mpWirelessDriver->ReorderNetwork(req.networkID, req.networkIndex, debugText);
    FillDebugTextAndNetworkIndex(response, debugText, req.networkIndex);
    ctx.mCommandHandler.AddResponse(ctx.mRequestPath, response);
    if (response.networkingStatus == NetworkCommissioningStatus::kSuccess)
    {
        UpdateBreadcrumb(req.breadcrumb);
    }
}

void Instance::OnResult(Status commissioningError, CharSpan debugText, int32_t interfaceStatus)
{
    auto commandHandleRef = std::move(mAsyncCommandHandle);
    auto commandHandle    = commandHandleRef.Get();
    if (commandHandle == nullptr)
    {
        // When the platform shutted down, interaction model engine will invalidate all commandHandle to avoid dangling references.
        // We may receive the callback after it and should make it noop.
        return;
    }

    Commands::ConnectNetworkResponse::Type response;
    response.networkingStatus = commissioningError;
    if (!debugText.empty())
    {
        response.debugText.SetValue(debugText);
    }
    if (commissioningError == Status::kSuccess)
    {
        DeviceLayer::DeviceControlServer::DeviceControlSvr().PostConnectedToOperationalNetworkEvent(
            ByteSpan(mLastNetworkID, mLastNetworkIDLen));
        mLastConnectErrorValue.SetNull();
    }
    else
    {
        response.errorValue.SetNonNull(interfaceStatus);
        mLastConnectErrorValue.SetNonNull(interfaceStatus);
    }

    mLastNetworkIDLen = mConnectingNetworkIDLen;
    memcpy(mLastNetworkID, mConnectingNetworkID, mLastNetworkIDLen);
    mLastNetworkingStatusValue.SetNonNull(commissioningError);

    commandHandle->AddResponse(mPath, response);
    if (commissioningError == NetworkCommissioningStatus::kSuccess)
    {
        CommitSavedBreadcrumb();
    }
}

void Instance::OnFinished(Status status, CharSpan debugText, ThreadScanResponseIterator * networks)
{
    CHIP_ERROR err        = CHIP_NO_ERROR;
    auto commandHandleRef = std::move(mAsyncCommandHandle);
    auto commandHandle    = commandHandleRef.Get();
    if (commandHandle == nullptr)
    {
        // When the platform shutted down, interaction model engine will invalidate all commandHandle to avoid dangling references.
        // We may receive the callback after it and should make it noop.
        return;
    }

    mLastNetworkingStatusValue.SetNonNull(status);
    mLastConnectErrorValue.SetNull();
    mLastNetworkIDLen = 0;

    TLV::TLVWriter * writer;
    TLV::TLVType listContainerType;
    ThreadScanResponse scanResponse;
    chip::Platform::ScopedMemoryBuffer<ThreadScanResponse> scanResponseArray;
    size_t scanResponseArrayLength = 0;
    uint8_t extendedAddressBuffer[Thread::kSizeExtendedPanId];

    SuccessOrExit(err = commandHandle->PrepareCommand(
                      ConcreteCommandPath(mPath.mEndpointId, NetworkCommissioning::Id, Commands::ScanNetworksResponse::Id)));
    VerifyOrExit((writer = commandHandle->GetCommandDataIBTLVWriter()) != nullptr, err = CHIP_ERROR_INCORRECT_STATE);

    SuccessOrExit(
        err = writer->Put(TLV::ContextTag(to_underlying(Commands::ScanNetworksResponse::Fields::kNetworkingStatus)), status));
    if (debugText.size() != 0)
    {
        SuccessOrExit(err = DataModel::Encode(
                          *writer, TLV::ContextTag(to_underlying(Commands::ScanNetworksResponse::Fields::kDebugText)), debugText));
    }
    SuccessOrExit(
        err = writer->StartContainer(TLV::ContextTag(to_underlying(Commands::ScanNetworksResponse::Fields::kThreadScanResults)),
                                     TLV::TLVType::kTLVType_Array, listContainerType));

    VerifyOrExit(scanResponseArray.Alloc(chip::min(networks->Count(), kMaxNetworksInScanResponse)), err = CHIP_ERROR_NO_MEMORY);
    for (; networks != nullptr && networks->Next(scanResponse);)
    {
        if ((scanResponseArrayLength == kMaxNetworksInScanResponse) &&
            (scanResponseArray[scanResponseArrayLength - 1].rssi > scanResponse.rssi))
        {
            continue;
        }

        bool isDuplicated = false;

        for (size_t i = 0; i < scanResponseArrayLength; i++)
        {
            if ((scanResponseArray[i].panId == scanResponse.panId) &&
                (scanResponseArray[i].extendedPanId == scanResponse.extendedPanId))
            {
                if (scanResponseArray[i].rssi < scanResponse.rssi)
                {
                    scanResponseArray[i] = scanResponseArray[--scanResponseArrayLength];
                }
                else
                {
                    isDuplicated = true;
                }
                break;
            }
        }

        if (isDuplicated)
        {
            continue;
        }

        if (scanResponseArrayLength < kMaxNetworksInScanResponse)
        {
            scanResponseArrayLength++;
        }
        scanResponseArray[scanResponseArrayLength - 1] = scanResponse;
        Sorting::InsertionSort(scanResponseArray.Get(), scanResponseArrayLength,
                               [](const ThreadScanResponse & a, const ThreadScanResponse & b) -> bool { return a.rssi > b.rssi; });
    }

    for (size_t i = 0; i < scanResponseArrayLength; i++)
    {
        Structs::ThreadInterfaceScanResult::Type result;
        Encoding::BigEndian::Put64(extendedAddressBuffer, scanResponseArray[i].extendedAddress);
        result.panId           = scanResponseArray[i].panId;
        result.extendedPanId   = scanResponseArray[i].extendedPanId;
        result.networkName     = CharSpan(scanResponseArray[i].networkName, scanResponseArray[i].networkNameLen);
        result.channel         = scanResponseArray[i].channel;
        result.version         = scanResponseArray[i].version;
        result.extendedAddress = ByteSpan(extendedAddressBuffer);
        result.rssi            = scanResponseArray[i].rssi;
        result.lqi             = scanResponseArray[i].lqi;

        SuccessOrExit(err = DataModel::Encode(*writer, TLV::AnonymousTag(), result));
    }

    SuccessOrExit(err = writer->EndContainer(listContainerType));
    SuccessOrExit(err = commandHandle->FinishCommand());

exit:
    if (err != CHIP_NO_ERROR)
    {
        ChipLogError(Zcl, "Failed to encode response: %s", err.AsString());
    }
    if (status == NetworkCommissioningStatus::kSuccess)
    {
        CommitSavedBreadcrumb();
    }
    networks->Release();
}

void Instance::OnFinished(Status status, CharSpan debugText, WiFiScanResponseIterator * networks)
{
    CHIP_ERROR err        = CHIP_NO_ERROR;
    auto commandHandleRef = std::move(mAsyncCommandHandle);
    auto commandHandle    = commandHandleRef.Get();
    if (commandHandle == nullptr)
    {
        // When the platform shutted down, interaction model engine will invalidate all commandHandle to avoid dangling references.
        // We may receive the callback after it and should make it noop.
        return;
    }

    mLastNetworkingStatusValue.SetNonNull(status);
    mLastConnectErrorValue.SetNull();
    mLastNetworkIDLen = 0;

    TLV::TLVWriter * writer;
    TLV::TLVType listContainerType;
    WiFiScanResponse scanResponse;
    size_t networksEncoded = 0;

    SuccessOrExit(err = commandHandle->PrepareCommand(
                      ConcreteCommandPath(mPath.mEndpointId, NetworkCommissioning::Id, Commands::ScanNetworksResponse::Id)));
    VerifyOrExit((writer = commandHandle->GetCommandDataIBTLVWriter()) != nullptr, err = CHIP_ERROR_INCORRECT_STATE);

    SuccessOrExit(
        err = writer->Put(TLV::ContextTag(to_underlying(Commands::ScanNetworksResponse::Fields::kNetworkingStatus)), status));
    if (debugText.size() != 0)
    {
        SuccessOrExit(err = DataModel::Encode(
                          *writer, TLV::ContextTag(to_underlying(Commands::ScanNetworksResponse::Fields::kDebugText)), debugText));
    }
    SuccessOrExit(
        err = writer->StartContainer(TLV::ContextTag(to_underlying(Commands::ScanNetworksResponse::Fields::kWiFiScanResults)),
                                     TLV::TLVType::kTLVType_Array, listContainerType));

    for (; networks != nullptr && networks->Next(scanResponse) && networksEncoded < kMaxNetworksInScanResponse; networksEncoded++)
    {
        Structs::WiFiInterfaceScanResult::Type result;
        result.security = scanResponse.security;
        result.ssid     = ByteSpan(scanResponse.ssid, scanResponse.ssidLen);
        result.bssid    = ByteSpan(scanResponse.bssid, sizeof(scanResponse.bssid));
        result.channel  = scanResponse.channel;
        result.wiFiBand = scanResponse.wiFiBand;
        result.rssi     = scanResponse.rssi;
        SuccessOrExit(err = DataModel::Encode(*writer, TLV::AnonymousTag(), result));
    }

    SuccessOrExit(err = writer->EndContainer(listContainerType));
    SuccessOrExit(err = commandHandle->FinishCommand());

exit:
    if (err != CHIP_NO_ERROR)
    {
        ChipLogError(Zcl, "Failed to encode response: %s", err.AsString());
    }
    if (status == NetworkCommissioningStatus::kSuccess)
    {
        CommitSavedBreadcrumb();
    }
    if (networks != nullptr)
    {
        networks->Release();
    }
}

void Instance::OnPlatformEventHandler(const DeviceLayer::ChipDeviceEvent * event, intptr_t arg)
{
    Instance * this_ = reinterpret_cast<Instance *>(arg);

    if (event->Type == DeviceLayer::DeviceEventType::kCommissioningComplete)
    {
        this_->OnCommissioningComplete();
    }
    else if (event->Type == DeviceLayer::DeviceEventType::kFailSafeTimerExpired)
    {
        this_->OnFailSafeTimerExpired();
    }
}

void Instance::OnCommissioningComplete()
{
    VerifyOrReturn(mpWirelessDriver != nullptr);

    ChipLogDetail(Zcl, "Commissioning complete, notify platform driver to persist network credentials.");
    mpWirelessDriver->CommitConfiguration();
}

void Instance::OnFailSafeTimerExpired()
{
    VerifyOrReturn(mpWirelessDriver != nullptr);

    ChipLogDetail(Zcl, "Failsafe timeout, tell platform driver to revert network credentials.");
    mpWirelessDriver->RevertConfiguration();
    mAsyncCommandHandle.Release();
}

CHIP_ERROR Instance::EnumerateAcceptedCommands(const ConcreteClusterPath & cluster, CommandIdCallback callback, void * context)
{
    using namespace Clusters::NetworkCommissioning::Commands;

    constexpr CommandId acceptedCommandsListWiFi[] = {
        ScanNetworks::Id, AddOrUpdateWiFiNetwork::Id, RemoveNetwork::Id, ConnectNetwork::Id, ReorderNetwork::Id,
    };
    constexpr CommandId acceptedCommandsListThread[] = {
        ScanNetworks::Id, AddOrUpdateThreadNetwork::Id, RemoveNetwork::Id, ConnectNetwork::Id, ReorderNetwork::Id,
    };

    if (mFeatureFlags.Has(NetworkCommissioningFeature::kThreadNetworkInterface))
    {
        for (const auto & cmd : acceptedCommandsListThread)
        {
            if (callback(cmd, context) != Loop::Continue)
            {
                break;
            }
        }

        return CHIP_NO_ERROR;
    }

    if (mFeatureFlags.Has(NetworkCommissioningFeature::kWiFiNetworkInterface))
    {
        for (const auto & cmd : acceptedCommandsListWiFi)
        {
            if (callback(cmd, context) != Loop::Continue)
            {
                break;
            }
        }

        return CHIP_NO_ERROR;
    }

    return CHIP_NO_ERROR;
}

CHIP_ERROR Instance::EnumerateGeneratedCommands(const ConcreteClusterPath & cluster, CommandIdCallback callback, void * context)
{
    using namespace Clusters::NetworkCommissioning::Commands;

    constexpr CommandId generatedCommandsListWireless[] = { ScanNetworksResponse::Id, NetworkConfigResponse::Id,
                                                            ConnectNetworkResponse::Id };

    if (mFeatureFlags.HasAny(NetworkCommissioningFeature::kWiFiNetworkInterface,
                             NetworkCommissioningFeature::kThreadNetworkInterface))
    {
        for (const auto & cmd : generatedCommandsListWireless)
        {
            if (callback(cmd, context) != Loop::Continue)
            {
                break;
            }
        }
    }

    return CHIP_NO_ERROR;
}

bool NullNetworkDriver::GetEnabled()
{
    // Disable the interface and it cannot be enabled since there are no physical interfaces.
    return false;
}

uint8_t NullNetworkDriver::GetMaxNetworks()
{
    // The minimal value of MaxNetworks should be 1 per spec.
    return 1;
}

DeviceLayer::NetworkCommissioning::NetworkIterator * NullNetworkDriver::GetNetworks()
{
    // Instance::Read accepts nullptr as an empty NetworkIterator.
    return nullptr;
}

} // namespace NetworkCommissioning
} // namespace Clusters
} // namespace app
} // namespace chip

// These functions are ember interfaces, they should never be implemented since all network commissioning cluster functions are
// implemented in NetworkCommissioning::Instance.
bool emberAfNetworkCommissioningClusterAddOrUpdateThreadNetworkCallback(
    CommandHandler * commandObj, const ConcreteCommandPath & commandPath,
    const Commands::AddOrUpdateThreadNetwork::DecodableType & commandData)
{
    return false;
}

bool emberAfNetworkCommissioningClusterAddOrUpdateWiFiNetworkCallback(
    CommandHandler * commandObj, const ConcreteCommandPath & commandPath,
    const Commands::AddOrUpdateWiFiNetwork::DecodableType & commandData)
{
    return false;
}

bool emberAfNetworkCommissioningClusterConnectNetworkCallback(CommandHandler * commandObj, const ConcreteCommandPath & commandPath,
                                                              const Commands::ConnectNetwork::DecodableType & commandData)
{
    return false;
}

bool emberAfNetworkCommissioningClusterRemoveNetworkCallback(CommandHandler * commandObj, const ConcreteCommandPath & commandPath,
                                                             const Commands::RemoveNetwork::DecodableType & commandData)
{
    return false;
}

bool emberAfNetworkCommissioningClusterScanNetworksCallback(CommandHandler * commandObj, const ConcreteCommandPath & commandPath,
                                                            const Commands::ScanNetworks::DecodableType & commandData)
{
    return false;
}

bool emberAfNetworkCommissioningClusterReorderNetworkCallback(CommandHandler * commandObj, const ConcreteCommandPath & commandPath,
                                                              const Commands::ReorderNetwork::DecodableType & commandData)
{
    return false;
}

void MatterNetworkCommissioningPluginServerInitCallback()
{
    // Nothing to do, the server init routine will be done in Instance::Init()
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.apache.jena.atlas.json.io.parserjavacc.javacc (Apache Jena ARQ)</title>
<meta name="date" content="2015-12-08">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">

org.apache.jena.atlas.json.io.parserjavacc.javacc

Interfaces

JSON_ParserConstants

Classes

JavaCharStream

JSON_Parser

JSON_ParserBase

JSON_ParserTokenManager

Token

Exceptions

ParseException

Errors

TokenMgrError


text:
<?xml version="1.0"?>
<package>
  <name>kinect2_bridge</name>
  <version>0.0.1</version>
  <description>The kinect2_bridge package</description>

  <maintainer email="wiedemeyer@informatik.uni-bremen.de">Thiemo Wiedemeyer</maintainer>

  <license>Apache 2.0</license>

  <buildtool_depend>catkin</buildtool_depend>

  <build_depend>roscpp</build_depend>
  <build_depend>rostime</build_depend>
  <build_depend>std_msgs</build_depend>
  <build_depend>sensor_msgs</build_depend>
  <build_depend>message_filters</build_depend>
  <build_depend>compressed_depth_image_transport</build_depend>
  <build_depend>kinect2_depth_registration</build_depend>
  <build_depend>nodelet</build_depend>
  <build_depend>cv_bridge</build_depend><!-- Depend on cv_bridge instead of libopencv-dev to support ROS Hydro.-->

  <run_depend>message_runtime</run_depend>
  <run_depend>roscpp</run_depend>
  <run_depend>rostime</run_depend>
  <run_depend>std_msgs</run_depend>
  <run_depend>sensor_msgs</run_depend>
  <run_depend>compressed_depth_image_transport</run_depend>
  <run_depend>kinect2_depth_registration</run_depend>
  <run_depend>nodelet</run_depend>
  <run_depend>cv_bridge</run_depend><!-- Depend on cv_bridge instead of libopencv-dev to support ROS Hydro.-->

  <export>
    <nodelet plugin="${prefix}/nodelet_plugins.xml" />
  </export>
</package>


text:
require 'rack/builder'
require 'rack/mock'
require 'rack/showexceptions'
require 'rack/urlmap'

class NothingMiddleware
  def initialize(app)
    @app = app
  end
  def call(env)
    @@env = env
    response = @app.call(env)
    response
  end
  def self.env
    @@env
  end
end

describe Rack::Builder do
  it "supports mapping" do
    app = Rack::Builder.new do
      map '/' do |outer_env|
        run lambda { |inner_env| [200, {}, ['root']] }
      end
      map '/sub' do
        run lambda { |inner_env| [200, {}, ['sub']] }
      end
    end.to_app
    Rack::MockRequest.new(app).get("/").body.to_s.should.equal 'root'
    Rack::MockRequest.new(app).get("/sub").body.to_s.should.equal 'sub'
  end

  it "doesn't dupe env even when mapping" do
    app = Rack::Builder.new do
      use NothingMiddleware
      map '/' do |outer_env|
        run lambda { |inner_env|
          inner_env['new_key'] = 'new_value'
          [200, {}, ['root']]
        }
      end
    end.to_app
    Rack::MockRequest.new(app).get("/").body.to_s.should.equal 'root'
    NothingMiddleware.env['new_key'].should.equal 'new_value'
  end

  it "chains apps by default" do
    app = Rack::Builder.new do
      use Rack::ShowExceptions
      run lambda { |env| raise "bzzzt" }
    end.to_app

    Rack::MockRequest.new(app).get("/").should.be.server_error
    Rack::MockRequest.new(app).get("/").should.be.server_error
    Rack::MockRequest.new(app).get("/").should.be.server_error
  end

  it "has implicit #to_app" do
    app = Rack::Builder.new do
      use Rack::ShowExceptions
      run lambda { |env| raise "bzzzt" }
    end

    Rack::MockRequest.new(app).get("/").should.be.server_error
    Rack::MockRequest.new(app).get("/").should.be.server_error
    Rack::MockRequest.new(app).get("/").should.be.server_error
  end

  it "supports blocks on use" do
    app = Rack::Builder.new do
      use Rack::ShowExceptions
      use Rack::Auth::Basic do |username, password|
        'secret' == password
      end

      run lambda { |env| [200, {}, ['Hi Boss']] }
    end

    response = Rack::MockRequest.new(app).get("/")
    response.should.be.client_error
    response.status.should.equal 401

    # with auth...
    response = Rack::MockRequest.new(app).get("/",
        'HTTP_AUTHORIZATION' => 'Basic ' + ["joe:secret"].pack("m*"))
    response.status.should.equal 200
    response.body.to_s.should.equal 'Hi Boss'
  end

  it "has explicit #to_app" do
    app = Rack::Builder.app do
      use Rack::ShowExceptions
      run lambda { |env| raise "bzzzt" }
    end

    Rack::MockRequest.new(app).get("/").should.be.server_error
    Rack::MockRequest.new(app).get("/").should.be.server_error
    Rack::MockRequest.new(app).get("/").should.be.server_error
  end

  should "initialize apps once" do
    app = Rack::Builder.new do
      class AppClass
        def initialize
          @called = 0
        end
        def call(env)
          raise "bzzzt"  if @called > 0
        @called += 1
          [200, {'Content-Type' => 'text/plain'}, ['OK']]
        end
      end

      use Rack::ShowExceptions
      run AppClass.new
    end

    Rack::MockRequest.new(app).get("/").status.should.equal 200
    Rack::MockRequest.new(app).get("/").should.be.server_error
  end

  describe "parse_file" do
    def config_file(name)
      File.join(File.dirname(__FILE__), 'builder', name)
    end

    it "parses commented options" do
      app, options = Rack::Builder.parse_file config_file('options.ru')
      options[:debug].should.be.true
      Rack::MockRequest.new(app).get("/").body.to_s.should.equal 'OK'
    end

    it "removes __END__ before evaluating app" do
      app, options = Rack::Builder.parse_file config_file('end.ru')
      Rack::MockRequest.new(app).get("/").body.to_s.should.equal 'OK'
    end

    it "supports multi-line comments" do
      lambda {
        Rack::Builder.parse_file config_file('comment.ru')
      }.should.not.raise(SyntaxError)
    end

    it "requires anything not ending in .ru" do
      $: << File.dirname(__FILE__)
      app, options = Rack::Builder.parse_file 'builder/anything'
      Rack::MockRequest.new(app).get("/").body.to_s.should.equal 'OK'
      $:.pop
    end
  end
end


text:
"""Unit test for Treadmill server trace printer module.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import unittest
import io

import mock

from treadmill.trace.server import events
from treadmill.trace.server import printer

class ServerTracePrinterTest(unittest.TestCase):
    """Test printing trace events.
    """

    def setUp(self):
        self.trace_printer = printer.ServerTracePrinter()

    @mock.patch('sys.stdout', new_callable=io.StringIO)
    def test_server_state(self, stdout_mock):
        """Test printing ServerState event.
        """
        event = events.ServerStateTraceEvent(
            timestamp=1,
            source='tests',
            servername='test.xx.com',
            state='up',
            payload={'foo': 'bar'}
        )

        self.trace_printer.process(event)

        self.assertEqual(
            stdout_mock.getvalue(),
            'Thu, 01 Jan 1970 00:00:01+0000 - '
            'test.xx.com up\n'
        )

    @mock.patch('sys.stdout', new_callable=io.StringIO)
    def test_server_blackout(self, stdout_mock):
        """Test printing ServerBlackout event.
        """
        event = events.ServerBlackoutTraceEvent(
            timestamp=2,
            source='tests',
            servername='test.xx.com',
            payload={'foo': 'bar'}
        )

        self.trace_printer.process(event)

        self.assertEqual(
            stdout_mock.getvalue(),
            'Thu, 01 Jan 1970 00:00:02+0000 - '
            'test.xx.com blackout\n'
        )

    @mock.patch('sys.stdout', new_callable=io.StringIO)
    def test_server_blackout_cleared(self, stdout_mock):
        """Test printing ServerBlackoutCleared event.
        """
        event = events.ServerBlackoutClearedTraceEvent(
            timestamp=3,
            source='tests',
            servername='test.xx.com',
            payload={'foo': 'bar'}
        )

        self.trace_printer.process(event)

        self.assertEqual(
            stdout_mock.getvalue(),
            'Thu, 01 Jan 1970 00:00:03+0000 - '
            'test.xx.com cleared\n'
        )

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


text:
require_relative "helper"

class TestCommandMap < Test::Unit::TestCase

  include Helper::Client

  def test_override_existing_commands
    r.set("counter", 1)

    assert_equal 2, r.incr("counter")

    r._client.command_map[:incr] = :decr

    assert_equal 1, r.incr("counter")
  end

  def test_override_non_existing_commands
    r.set("key", "value")

    assert_raise Redis::CommandError do
      r.idontexist("key")
    end

    r._client.command_map[:idontexist] = :get

    assert_equal "value", r.idontexist("key")
  end
end


text:
layout:     post
title:      memo#0
date:       2013-10-28
tags: innoDB mySQL
---

В ```mySQL``` создавая таблицу в процессе транзакции нельзя будет ее удалить при роллбэке.

<!--more-->

Это связанно с тем, что ```CREATE TABLE``` в ```InnoDB``` обрабатывается как отдельная транзакция. Это означает что ```ROLLBACK```, инизиализируемый пользователем, не отменит ```CREATE TABLE``` сделанный в процессе транзакции.

[MySQL Reference Manual](http://dev.mysql.com/doc/refman/5.1/en/implicit-commit.html)


text:
chrome.devtools.panels.create( "Shader Editor",
    "icon.png",
    "panel.html",
    function(panel) {

       // code invoked on panel creation

    }
);

    var backgroundPageConnection = chrome.runtime.connect({
      name: 'panel'
    });

    backgroundPageConnection.postMessage({
      name: 'init',
      tabId: chrome.devtools.inspectedWindow.tabId
    });
    console.log(chrome.devtools.inspectedWindow);

    backgroundPageConnection.onMessage.addListener(function(msg) {
        //console.log( 'devtools.js', msg );
    });


text:
import json
import os
import random

from addict import Dict
from jsonmerge import merge

from lemonyellow.data.moves import moves
from lemonyellow.core.experience import exp

__all__ = ["pokemon"]

Traded = "Not Implemented Yet"

# Special Evolutions
Eeveelution = "Eeveelution"  # because I have no idea how to handle this yet
Eeveelutions = "Eeveelutions"  # determining which pokemon to evolve into

move_translations = {
    "absorb": moves.absorb,
    "acid": moves.acid,
    "acid_armor": moves.acid_armor,
    "agility": moves.agility,
    "amnesia": moves.amnesia,
    "aurora_beam": moves.aurora_beam,
    "barrage": moves.barrage,
    "barrier": moves.barrier,
    "bide": moves.bide,
    "bind": moves.bind,
    "bite": moves.bite,
    "blizzard": moves.blizzard,
    "body_slam": moves.body_slam,
    "bone_club": moves.bone_club,
    "bonemerang": moves.bonemerang,
    "bubble": moves.bubble,
    "bubble_beam": moves.bubble_beam,
    "clamp": moves.clamp,
    "comet_punch": moves.comet_punch,
    "confuse_ray": moves.confuse_ray,
    "confusion": moves.confusion,
    "constrict": moves.constrict,
    "conversion": moves.conversion,
    "counter": moves.counter,
    "crabhammer": moves.crabhammer,
    "cut": moves.cut,
    "defense_curl": moves.defense_curl,
    "dig": moves.dig,
    "disable": moves.disable,
    "dizzy_punch": moves.dizzy_punch,
    "double_kick": moves.double_kick,
    "double_team": moves.double_team,
    "double_edge": moves.double_edge,
    "doubleslap": moves.doubleslap,
    "dragon_rage": moves.dragon_rage,
    "dream_eater": moves.dream_eater,
    "drill_peck": moves.drill_peck,
    "earthquake": moves.earthquake,
    "egg_bomb": moves.egg_bomb,
    "ember": moves.ember,
    "explosion": moves.explosion,
    "fire_blast": moves.fire_blast,
    "fire_punch": moves.fire_punch,
    "fire_spin": moves.fire_spin,
    "fissure": moves.fissure,
    "flamethrower": moves.flamethrower,
    "flash": moves.flash,
    "fly": moves.fly,
    "focus_energy": moves.focus_energy,
    "fury_attack": moves.fury_attack,
    "fury_swipes": moves.fury_swipes,
    "glare": moves.glare,
    "growl": moves.growl,
    "growth": moves.growth,
    "guillotine": moves.guillotine,
    "gust": moves.gust,
    "harden": moves.harden,
    "haze": moves.haze,
    "headbutt": moves.headbutt,
    "hi_jump_kick": moves.hi_jump_kick,
    "horn_attack": moves.horn_attack,
    "horn_drill": moves.horn_drill,
    "hydro_pump": moves.hydro_pump,
    "hyper_beam": moves.hyper_beam,
    "hyper_fang": moves.hyper_fang,
    "hypnosis": moves.hypnosis,
    "ice_beam": moves.ice_beam,
    "ice_punch": moves.ice_punch,
    "jump_kick": moves.jump_kick,
    "karate_chop": moves.karate_chop,
    "kinesis": moves.kinesis,
    "leech_life": moves.leech_life,
    "leech_seed": moves.leech_seed,
    "leer": moves.leer,
    "lick": moves.lick,
    "light_screen": moves.light_screen,
    "lovely_kiss": moves.lovely_kiss,
    "low_kick": moves.low_kick,
    "meditate": moves.meditate,
    "mega_drain": moves.mega_drain,
    "mega_kick": moves.mega_kick,
    "mega_punch": moves.mega_punch,
    "metronome": moves.metronome,
    "mimic": moves.mimic,
    "minimize": moves.minimize,
    "mirror_move": moves.mirror_move,
    "mist": moves.mist,
    "night_shade": moves.night_shade,
    "pay_day": moves.pay_day,
    "peck": moves.peck,
    "petal_dance": moves.petal_dance,
    "pin_missile": moves.pin_missile,
    "poison_gas": moves.poison_gas,
    "poison_sting": moves.poison_sting,
    "poisonpowder": moves.poisonpowder,
    "pound": moves.pound,
    "psybeam": moves.psybeam,
    "psychic": moves.psychic,
    "psywave": moves.psywave,
    "quick_attack": moves.quick_attack,
    "rage": moves.rage,
    "razor_leaf": moves.razor_leaf,
    "razor_wind": moves.razor_wind,
    "recover": moves.recover,
    "reflect": moves.reflect,
    "rest": moves.rest,
    "roar": moves.roar,
    "rock_slide": moves.rock_slide,
    "rock_throw": moves.rock_throw,
    "rolling_kick": moves.rolling_kick,
    "sand_attack": moves.sand_attack,
    "scratch": moves.scratch,
    "screech": moves.screech,
    "seismic_toss": moves.seismic_toss,
    "selfdestruct": moves.selfdestruct,
    "sharpen": moves.sharpen,
    "sing": moves.sing,
    "skull_bash": moves.skull_bash,
    "sky_attack": moves.sky_attack,
    "slam": moves.slam,
    "slash": moves.slash,
    "sleep_powder": moves.sleep_powder,
    "sludge": moves.sludge,
    "smog": moves.smog,
    "smokescreen": moves.smokescreen,
    "softboiled": moves.softboiled,
    "solarbeam": moves.solarbeam,
    "sonicboom": moves.sonicboom,
    "spike_cannon": moves.spike_cannon,
    "splash": moves.splash,
    "spore": moves.spore,
    "stomp": moves.stomp,
    "strength": moves.strength,
    "string_shot": moves.string_shot,
    "struggle": moves.struggle,
    "stun_spore": moves.stun_spore,
    "submission": moves.submission,
    "substitute": moves.substitute,
    "super_fang": moves.super_fang,
    "supersonic": moves.supersonic,
    "surf": moves.surf,
    "swift": moves.swift,
    "swords_dance": moves.swords_dance,
    "tackle": moves.tackle,
    "tail_whip": moves.tail_whip,
    "take_down": moves.take_down,
    "teleport": moves.teleport,
    "thrash": moves.thrash,
    "thunder": moves.thunder,
    "thunder_wave": moves.thunder_wave,
    "thunderpunch": moves.thunderpunch,
    "thundershock": moves.thundershock,
    "thunderbolt": moves.thunderbolt,
    "toxic": moves.toxic,
    "transform": moves.transform,
    "triattack": moves.triattack,
    "twineedle": moves.twineedle,
    "vicegrip": moves.vicegrip,
    "vine_whip": moves.vine_whip,
    "water_gun": moves.water_gun,
    "waterfall": moves.waterfall,
    "whirlwind": moves.whirlwind,
    "wing_attack": moves.wing_attack,
    "withdraw": moves.withdraw,
    "wrap": moves.wrap,
}

exp_translation = {
    "fast": exp.fast_chart,
    "medium_fast": exp.mediumfast_chart,
    "medium_slow": exp.mediumslow_chart,
    "slow": exp.slow_chart,
    "erratic": exp.erratic_chart,
    "fluctuating": exp.fluctuating_chart,
}

pokemon_data_base = json.load(
    open(os.path.join(os.path.dirname(__file__), "poke_base.json"))
)

pokemon_data_full = json.load(
    open(os.path.join(os.path.dirname(__file__), "poke_data_full.json"))
)

def entry_create(pokemon):
    poke = Dict()
    poke.update(merge(pokemon_data_base, pokemon_data_full[pokemon]))
    poke.hatch_time = random.randint(poke.hatch_time[0], poke.hatch_time[1])
    poke.leveling_rate = exp_translation[poke.leveling_rate]
    poke.moves_starting = [move_translations[x] for x in poke.moves_starting]
    poke.moves_tms = [move_translations[x] for x in poke.moves_tms]
    poke.moves_evolved = {
        x: move_translations[poke.moves_evolved[x]] for x in poke.moves_evolved
    }
    return poke

pokemon = Dict()

for poke in pokemon_data_full.keys():
    pokemon[poke] = entry_create(poke)


text:
import React       from "react";
import { connect } from "react-redux";
import Cell        from "./cell";
import descriptors from "../descriptors.json";
import {
	addResultToParent,
	removeResult,
	updateResult,
	copyResult,
	getResultTree,
} from "../reducers/results";

const mapStateToProps = (state, ownProps) => ({
	root: getResultTree(state.results, ownProps.root),
	context: descriptors,
});

const clickDecorator = e => action => {
	e.preventDefault();

	action.click_coords = {
		x: e.clientX,
		y: e.clientY,
	};

	return action;
};

const mapDispatchToProps = (dispatch) => ({
	onCopyClick: id => _ => {
		return dispatch(copyResult(id));
	},
	onLabelClick: parent => (e, label) => {
		return dispatch(clickDecorator(e)(addResultToParent(parent, label)));
	},
	onRemoveClick: (e, id) => {
		return dispatch(clickDecorator(e)(removeResult(id)));
	},
	onCellChange: id => state => {
		return dispatch(updateResult(id, state));
	},
});

let offsets = [];

const register_offset_for_parent = parent_id => dom => {
	if (!dom)
		return;

	const bounds = dom.getBoundingClientRect();
	offsets[parent_id] = {
		x: bounds.left,
		y: bounds.top,
	};
};

const transform_origin = child => ({
	transformOrigin: offsets[child.parent] ? `${0 - Math.round(offsets[child.parent].x - child.origin.x)}px ${0 - Math.round(offsets[child.parent].y - child.origin.y)}px` : "0 0",
});

const Set = ({ root, context, onLabelClick, onRemoveClick, onCellChange, onCopyClick, giveInstructions, ...props }) =>
	<section {...props} className="mt-set">
		<Cell {...root} context={context} giveInstructions={giveInstructions && root.children.length === 0}
			onLabelClick={onLabelClick(root.id)} onRemoveClick={onRemoveClick}
			onCopyClick={onCopyClick(root.id)} onChange={onCellChange(root.id)} />
		<div ref={register_offset_for_parent(root.id)} className="mt-children">
			{root.children.map(child =>
				<Set key={child.id} root={child} context={context[child.title]}
					onLabelClick={onLabelClick} onCopyClick={onCopyClick}
					onRemoveClick={onRemoveClick} onCellChange={onCellChange}
					style={transform_origin(child)} />)}
		</div>
	</section>;

Set.propTypes = {
	root:             React.PropTypes.object.isRequired,
	context:          React.PropTypes.object.isRequired,
	onLabelClick:     React.PropTypes.func.isRequired,
	onRemoveClick:    React.PropTypes.func.isRequired,
	onCopyClick:      React.PropTypes.func.isRequired,
	onCellChange:     React.PropTypes.func.isRequired,
	giveInstructions: React.PropTypes.bool,
};

export default connect(mapStateToProps, mapDispatchToProps)(Set);


text:
namespace chromeos {
namespace system {

class CHROMEOS_EXPORT MockStatisticsProvider : public StatisticsProvider {
 public:
  MockStatisticsProvider();
  virtual ~MockStatisticsProvider();

  MOCK_METHOD2(StartLoadingMachineStatistics, void(
      const scoped_refptr<base::TaskRunner>&,
      bool));
  MOCK_METHOD2(GetMachineStatistic, bool(const std::string& name,
                                         std::string* result));
  MOCK_METHOD2(GetMachineFlag, bool(const std::string& name,
                                    bool* result));
  MOCK_METHOD0(Shutdown, void());

 private:
  DISALLOW_COPY_AND_ASSIGN(MockStatisticsProvider);
};

}  // namespace system
}  // namespace chromeos

#endif  // CHROMEOS_SYSTEM_MOCK_STATISTICS_PROVIDER_H_


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

		<Token>
			<TokenIdentifier>//apple_ref/occ/intf/CCRenderCommand</TokenIdentifier>
			<Abstract type="html">Describes the behaviour for an command object that can be submitted to the queue of a
CCRenderer in order to perform some drawing operations.</Abstract>
			<DeclaredIn>CCRenderer_private.h</DeclaredIn>

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

		<Token>
			<TokenIdentifier>//apple_ref/occ/intfm/CCRenderCommand/invokeOnRenderer:</TokenIdentifier>
			<Abstract type="html">Invokes this command on the specified renderer.</Abstract>
			<DeclaredIn>CCRenderer_private.h</DeclaredIn>

			<Declaration>- (void)invokeOnRenderer:(CCRenderer *)renderer</Declaration>

			<Anchor>//api/name/invokeOnRenderer:</Anchor>
            <NodeRef refid="130"/>
		</Token>

	</File>
</Tokens>


text:
<!DOCTYPE HTML>

    <title>Saxy</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen,print" href="saxy.css">

First Line

One Level Deep

Deeper


text:
package com.example.http4s.blaze

import org.http4s._
import org.http4s.dsl._
import org.http4s.client._
import org.http4s.client.blaze.{defaultClient => client}

object ClientPostExample extends App {
  val req = POST(uri("https://duckduckgo.com/"), UrlForm("q" -> "http4s"))
  val responseBody = client.expect[String](req)
  println(responseBody.run)
}


text:
namespace Ioke.Lang {
    using System;
    using System.Collections.Generic;
    using System.IO;
    using Ioke.Lang.Parser;
    using Ioke.Lang.Parser.Functional;
    using Ioke.Lang.Util;

    public class IokeMain {
        private const string HELP =
            "Usage: ioke [switches] -- [programfile] [arguments]\n" +
            " -Cdirectory     execute with directory as CWD\n" +
            " -d              debug, set debug flag\n" +
            " -e script       execute the script. if provided, no program file is necessary.\n" +
            "                 there can be many of these provided on the same command line.\n" +
            " -h, --help      help, this message\n" +
            " -Idir           add directory to 'System loadPath'. May be used more than once\n" +
            " --copyright     print the copyright\n" +
            " --version       print current version\n";

        public static void Main(string[] args) {
            string current = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string iokeHome = new FileInfo(current).Directory.Parent.FullName;
            string iokeLib = Path.Combine(iokeHome, "lib");

            Runtime r = new Runtime(new FunctionalOperatorShufflerFactory());
            r.Init();

            IokeObject context = r.Ground;
            Message mx = new Message(r, ".", null, true);
            mx.Line = 0;
            mx.Position = 0;
            IokeObject message = r.CreateMessage(mx);

            string cwd = null;

            var scripts = new SaneList<string>();
            var loadDirs = new SaneList<string>();
            bool debug = false;

            try {
                int start = 0;
                bool done = false;
                bool readStdin = false;
                bool printedSomething = false;

                for(;!done && start<args.Length;start++) {
                    string arg = args[start];
                    if(arg.Length > 0) {
                        if(arg[0] != '-') {
                            done = true;
                            break;
                        } else {
                            if(arg.Equals("--")) {
                                done = true;
                            } else if(arg.Equals("-d")) {
                                debug = true;
                                r.Debug = true;
                            } else if(arg.StartsWith("-e")) {
                                if(arg.Length == 2) {
                                    scripts.Add(args[++start]);
                                } else {
                                    scripts.Add(arg.Substring(2));
                                }
                            } else if(arg.StartsWith("-I")) {
                                if(arg.Length == 2) {
                                    loadDirs.Add(args[++start]);
                                } else {
                                    loadDirs.Add(arg.Substring(2));
                                }
                            } else if(arg.Equals("-h") || arg.Equals("--help")) {
                                Console.Error.Write(HELP);
                                return;
                            } else if(arg.Equals("--version")) {
                                Console.Error.WriteLine(getVersion());
                                printedSomething = true;
                            } else if(arg.Equals("--copyright")) {
                                Console.Error.Write(COPYRIGHT);
                                printedSomething = true;
                            } else if(arg.Equals("-")) {
                                readStdin = true;
                            } else if(arg[1] == 'C') {
                                if(arg.Length == 2) {
                                    cwd = args[++start];
                                } else {
                                    cwd = arg.Substring(2);
                                }
                            } else {
                                IokeObject condition = IokeObject.As(IokeObject.GetCellChain(r.Condition,
                                                                                message,
                                                                                context,
                                                                                "Error",
                                                                                "CommandLine",
                                                                                "DontUnderstandOption"), null).Mimic(message, context);
                                condition.SetCell("message", message);
                                condition.SetCell("context", context);
                                condition.SetCell("receiver", context);
                                condition.SetCell("option", r.NewText(arg));
                                r.ErrorCondition(condition);
                            }
                        }
                    }
                }

                if(cwd != null) {
                    r.CurrentWorkingDirectory = cwd;
                }

                ((IokeSystem)IokeObject.dataOf(r.System)).CurrentProgram = "-e";

                string lib = Environment.GetEnvironmentVariable("ioke.lib");
                if(lib == null) {
                    lib = iokeLib;
                }
                ((IokeSystem)IokeObject.dataOf(r.System)).AddLoadPath(lib + "/ioke");
                ((IokeSystem)IokeObject.dataOf(r.System)).AddLoadPath("lib/ioke");

                foreach(string ss in loadDirs) {
                    ((IokeSystem)IokeObject.dataOf(r.System)).AddLoadPath(ss);
                }

                foreach(string script in scripts) {
                    r.EvaluateStream("-e", new StringReader(script), message, context);
                }

                if(readStdin) {
                    ((IokeSystem)IokeObject.dataOf(r.System)).CurrentProgram = "<stdin>";
                    r.EvaluateStream("<stdin>", Console.In, message, context);
                }

                if(args.Length > start) {
                    if(args.Length > (start+1)) {
                        for(int i=start+1,j=args.Length; i<j; i++) {
                            r.AddArgument(args[i]);
                        }
                    }
                    string file = args[start];
                    if(file.StartsWith("\"")) {
                        file = file.Substring(1, file.Length-1);
                    }

                    if(file.Length > 1 && file[file.Length-1] == '"') {
                        file = file.Substring(0, file.Length-1);
                    }

                    ((IokeSystem)IokeObject.dataOf(r.System)).CurrentProgram = file;
                    r.EvaluateFile(file, message, context);
                } else {
                    if(!readStdin && scripts.Count == 0 && !printedSomething) {
                        r.EvaluateString("use(\"builtin/iik\"). IIk mainLoop", message, context);
                    }
                }

                r.TearDown();

            } catch(ControlFlow.Exit e) {
                int exitVal = e.ExitValue;
                try {
                    r.TearDown();
                } catch(ControlFlow.Exit e2) {
                    exitVal = e2.ExitValue;
                }
                Environment.Exit(exitVal);
            } catch(ControlFlow e) {
                string name = e.GetType().FullName;
                System.Console.Error.WriteLine("unexpected control flow: " + name.Substring(name.LastIndexOf(".") + 1).ToLower());
                if(debug) {
                    System.Console.Error.WriteLine(e);
                }
                Environment.Exit(1);
            }
        }

        public static string getVersion() {
            try {
                using(Stream s = typeof(IokeSystem).Assembly.GetManifestResourceStream("Ioke.Lang.version.properties")) {
                    using(StreamReader sr = new StreamReader(s, System.Text.Encoding.UTF8)) {
                        var result = new Dictionary<string, string>();
                        while(!sr.EndOfStream) {
                            string ss = sr.ReadLine();
                            if(ss.IndexOf('=') != -1) {
                                string[] parts = ss.Split('=');
                                result[parts[0].Trim()] = parts[1].Trim();
                            }
                        }

                        string version = result["ioke.build.versionString"];
                        string date = result["ioke.build.date"];
                        string commit = result["ioke.build.commit"];

                        return version + " [" + date + " -- " + commit + "]";
                    }
                }
            } catch(System.Exception) {
            }

            return "";
        }

        private const string COPYRIGHT =
            "Copyright (c) 2009 Ola Bini, ola.bini@gmail.com\n"+
            "\n"+
            "Permission is hereby granted, free of charge, to any person obtaining a copy\n"+
            "of this software and associated documentation files (the \"Software\"), to deal\n"+
            "in the Software without restriction, including without limitation the rights\n"+
            "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n"+
            "copies of the Software, and to permit persons to whom the Software is\n"+
            "furnished to do so, subject to the following conditions:\n"+
            "\n"+
            "The above copyright notice and this permission notice shall be included in\n"+
            "all copies or substantial portions of the Software.\n"+
            "\n"+
            "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n"+
            "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n"+
            "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n"+
            "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n"+
            "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n"+
            "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n"+
            "THE SOFTWARE.\n";
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

Implementation of Personal Eventing via Pubsub (XEP-0163).


text:
import { combineReducers } from 'redux';
import world, { tick as worldTick } from './world';
import game from './game/game';
import {App, GameState} from "../types";
import {Dispatch} from "react-redux";

export default combineReducers({
  world,
  game
})

export function tick(): any {
  return (dispatch: Dispatch<any>, getState: () => App) => {
    const appState = getState();
    if (appState.game.state !== GameState.Active) return;

    dispatch(worldTick());
  };
}


text:
"""Tests of standard AuthMetadataPlugins."""

import collections
import logging
import threading
import unittest

from grpc import _auth

class MockGoogleCreds(object):

    def get_access_token(self):
        token = collections.namedtuple('MockAccessTokenInfo',
                                       ('access_token', 'expires_in'))
        token.access_token = 'token'
        return token

class MockExceptionGoogleCreds(object):

    def get_access_token(self):
        raise Exception()

class GoogleCallCredentialsTest(unittest.TestCase):

    def test_google_call_credentials_success(self):
        callback_event = threading.Event()

        def mock_callback(metadata, error):
            self.assertEqual(metadata, (('authorization', 'Bearer token'),))
            self.assertIsNone(error)
            callback_event.set()

        call_creds = _auth.GoogleCallCredentials(MockGoogleCreds())
        call_creds(None, mock_callback)
        self.assertTrue(callback_event.wait(1.0))

    def test_google_call_credentials_error(self):
        callback_event = threading.Event()

        def mock_callback(metadata, error):
            self.assertIsNotNone(error)
            callback_event.set()

        call_creds = _auth.GoogleCallCredentials(MockExceptionGoogleCreds())
        call_creds(None, mock_callback)
        self.assertTrue(callback_event.wait(1.0))

class AccessTokenAuthMetadataPluginTest(unittest.TestCase):

    def test_google_call_credentials_success(self):
        callback_event = threading.Event()

        def mock_callback(metadata, error):
            self.assertEqual(metadata, (('authorization', 'Bearer token'),))
            self.assertIsNone(error)
            callback_event.set()

        metadata_plugin = _auth.AccessTokenAuthMetadataPlugin('token')
        metadata_plugin(None, mock_callback)
        self.assertTrue(callback_event.wait(1.0))

if __name__ == '__main__':
    logging.basicConfig()
    unittest.main(verbosity=2)


text:
package app.controllers.api.masterdata;

import app.models.MdTerusanTbl;
import core.controllers.CRUDController;

public class MdTerusanTblController extends CRUDController<MdTerusanTbl>{

}


text:
package org.onosproject.vtnrsc.cli.floatingip;

import java.util.Set;

import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.Option;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.vtnrsc.FloatingIp;
import org.onosproject.vtnrsc.FloatingIpId;
import org.onosproject.vtnrsc.floatingip.FloatingIpService;

import com.google.common.collect.Sets;

/**
 * Supports for remove a floating IP.
 */
@Service
@Command(scope = "onos", name = "floatingip-remove", description = "Supports for removing a floating IP")
public class FloatingIpRemoveCommand extends AbstractShellCommand {
    @Option(name = "-I", aliases = "--id", description = "The floating IP identifier",
            required = false, multiValued = false)
    String id = null;

    @Option(name = "-i", aliases = "--fixedIp", description = "The fixed IP of floating IP",
            required = false, multiValued = false)
    String fixedIp = null;

    @Option(name = "-l", aliases = "--floatingIp", description = "The floating IP of floating IP",
            required = false, multiValued = false)
    String floatingIp = null;

    @Override
    protected void doExecute() {
        FloatingIpService service = get(FloatingIpService.class);
        if (id == null && fixedIp == null && floatingIp == null) {
            print(null, "one of id, fixedIp, floatingIp should not be null");
        }
        try {
            Set<FloatingIpId> floatingIpSet = Sets.newHashSet();
            if (id != null) {
                floatingIpSet.add(FloatingIpId.of(id));
                service.removeFloatingIps(floatingIpSet);
            } else {
                Iterable<FloatingIp> floatingIps = service.getFloatingIps();
                if (floatingIps == null) {
                    return;
                }
                if (fixedIp != null) {
                    for (FloatingIp floatingIp : floatingIps) {
                        if (floatingIp.fixedIp().toString().equals(fixedIp)) {
                            floatingIpSet.add(floatingIp.id());
                            service.removeFloatingIps(floatingIpSet);
                            return;
                        }
                    }
                    print(null, "The fixedIp is not existed");
                    return;
                }
                if (floatingIp != null) {
                    for (FloatingIp floatingIpObj : floatingIps) {
                        if (floatingIpObj.fixedIp().toString()
                                .equals(floatingIp)) {
                            floatingIpSet.add(floatingIpObj.id());
                            service.removeFloatingIps(floatingIpSet);
                            return;
                        }
                    }
                    print(null, "The floatingIp is not existed");
                    return;
                }
            }
        } catch (Exception e) {
            print(null, e.getMessage());
        }
    }
}


text:
local ev = require "libev"
local ffi = require "ffi"
local upipe = require "upipe"

require "upump-ev"
require "upipe-modules"

ffi.cdef [[ FILE *stderr; ]]

local UPROBE_LOG_LEVEL = UPROBE_LOG_DEBUG
local UMEM_POOL = 512
local UDICT_POOL_DEPTH = 500
local UREF_POOL_DEPTH = 500
local UBUF_POOL_DEPTH = 3000
local UBUF_SHARED_POOL_DEPTH = 50
local UPUMP_POOL = 10
local UPUMP_BLOCKER_POOL = 10

if #arg ~= 2 then
    io.stderr:write("Usage: ", arg[0], " <input> <output>\n")
    os.exit(1)
end

local input, output = arg[1], arg[2]
local loop = ffi.gc(ev_default_loop(0), ev_loop_destroy)

-- managers
local upump_mgr = upump.ev(loop, UPUMP_POOL, UPUMP_BLOCKER_POOL)
local umem_mgr = umem.pool_simple(UMEM_POOL)
local udict_mgr = udict.inline(UDICT_POOL_DEPTH, umem_mgr, -1, -1)
local uref_mgr = uref.std(UREF_POOL_DEPTH, udict_mgr, 0)

local upipe_xor_mgr = upipe {
    -- use upipe_helper_output
    output = true,

    input = function (pipe, ref, pump)
	-- get size
	local size = ffi.new("size_t[1]")
	assert(ubase_check(ref:block_size(size)))
	size = tonumber(size[0])

	local offset = 0
	local size_p = ffi.new("int[1]")
	local buffer_p = ffi.new("uint8_t *[1]")
	while offset < size do
	    size_p[0] = size - offset
	    assert(ubase_check(ref:block_write(offset, size_p, buffer_p)))

	    -- xor buffer content
	    local buf = buffer_p[0]
	    for i = 0, size_p[0] - 1 do
		buf[i] = bit.bxor(buf[i], 0x42)
	    end

	    assert(ubase_check(ref:block_unmap(offset)))
	    offset = offset + size_p[0]
	end

	-- output uref
	pipe:helper_output(ref, pump)
    end,

    control = {
	set_flow_def = function (pipe, flow_def)
	    if not ubase_check(flow_def:flow_match_def("block.")) then
		return "invalid"
	    end
	    pipe:helper_store_flow_def(flow_def:dup())
	end
    }
}

-- probes
local probe =
    uprobe.ubuf_mem(umem_mgr, UBUF_POOL_DEPTH, UBUF_SHARED_POOL_DEPTH) ..
    uprobe.upump_mgr(upump_mgr) ..
    uprobe.uref_mgr(uref_mgr) ..
    uprobe.stdio_color(ffi.C.stderr, UPROBE_LOG_LEVEL)

local function pfx(tag)
    return uprobe.pfx(UPROBE_LOG_LEVEL, tag)
end

-- pipes
local src = upipe.fsrc():new(pfx("src") .. probe)
local xor = upipe_xor_mgr:new(pfx("xor") .. probe)
local sink = upipe.fsink():new(pfx("sink") .. probe)

src.uri = input
assert(ubase_check(sink:fsink_set_path(output, "UPIPE_FSINK_CREATE")))
src.output = xor .. sink

-- main loop
ev_run(loop, 0)


text:
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.

namespace PInvoke
{
    using System.Runtime.InteropServices;

    /// <content>
    /// Contains the <see cref="SERVICE_STATUS"/> nested type.
    /// </content>
    public partial class AdvApi32
    {
        /// <summary>
        /// Contains status information for a service.
        /// The ControlService, EnumDependentServices, EnumServicesStatus, and QueryServiceStatus functions use this structure.
        /// A service uses this structure in the <see cref="SetServiceStatus"/> function to report its current status to the service control manager.
        /// </summary>
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct SERVICE_STATUS
        {
            /// <summary>
            /// The type of service. <see cref="ServiceType"/>
            /// </summary>
            public ServiceType dwServiceType;

            /// <summary>
            /// The current state of the service.
            /// </summary>
            public ServiceState dwCurrentState;

            /// <summary>
            /// The control codes the service accepts and processes in its handler function (see Handler and HandlerEx).
            /// A user interface process can control a service by specifying a control command in the <see cref="ControlService"/> or ControlServiceEx function.
            /// By default, all services accept the <see cref="ServiceControl.SERVICE_CONTROL_INTERROGATE"/> value.
            /// To accept the <see cref="ServiceControl.SERVICE_CONTROL_DEVICEEVENT"/> value, the service must register to receive device events by using the RegisterDeviceNotification function.
            /// </summary>
            public int dwControlsAccepted;

            /// <summary>
            /// The error code the service uses to report an error that occurs when it is starting or stopping.
            /// To return an error code specific to the service, the service must set this value to <see cref="Win32ErrorCode.ERROR_SERVICE_SPECIFIC_ERROR"/> to indicate that the <see cref="dwServiceSpecificExitCode"/> member contains the error code.
            /// The service should set this value to NO_ERROR when it is running and on normal termination.
            /// </summary>
            public int dwWin32ExitCode;

            /// <summary>
            /// A service-specific error code that the service returns when an error occurs while the service is starting or stopping.
            /// This value is ignored unless the <see cref="dwWin32ExitCode"/> member is set to <see cref="Win32ErrorCode.ERROR_SERVICE_SPECIFIC_ERROR"/>.
            /// </summary>
            public int dwServiceSpecificExitCode;

            /// <summary>
            /// The check-point value the service increments periodically to report its progress during a lengthy start, stop, pause, or continue operation.
            /// For example, the service should increment this value as it completes each step of its initialization when it is starting up.
            /// The user interface program that invoked the operation on the service uses this value to track the progress of the service during a lengthy operation.
            /// This value is not valid and should be zero when the service does not have a start, stop, pause, or continue operation pending.
            /// </summary>
            public int dwCheckPoint;

            /// <summary>
            /// The estimated time required for a pending start, stop, pause, or continue operation, in milliseconds.
            /// Before the specified amount of time has elapsed, the service should make its next call to the <see cref="SetServiceStatus"/> function with either an incremented <see cref="dwCheckPoint"/> value or a change in dwCurrentState.
            /// If the amount of time specified by <see cref="dwWaitHint"/> passes, and <see cref="dwCheckPoint"/> has not been incremented or <see cref="dwCurrentState"/> has not changed,
            /// the service control manager or service control program can assume that an error has occurred and the service should be stopped.
            /// However, if the service shares a process with other services, the service control manager cannot terminate the service application because it would have to terminate the other services sharing the process as well.
            /// </summary>
            public int dwWaitHint;
        }
    }
}


text:
import argparse
import json
import os
from pyhocon import ConfigFactory
import sys
from catdb import open_output_file, open_input_file
from catdb.db import DbManager

def main():
    parent_parser = argparse.ArgumentParser(add_help=False)
    parent_parser.add_argument('-d', '--database', help='database', required=True, action='store')
    parent_parser.add_argument('-s', '--schema', help='schema', required=False, action='store', default=None)
    parent_parser.add_argument('-t', '--table', help='table filter (using % as a wildcard)', required=False,
                               action='store')
    parent_parser.add_argument('-dr', '--dry-run', dest='dry_run', help='dry run', required=False, action='store_true')

    argparser = argparse.ArgumentParser(description='export')
    subparsers = argparser.add_subparsers(help='sub-command help', dest='subparser_name')
    ddl_parser = subparsers.add_parser('ddl', help='ddl', parents=[parent_parser])
    ddl_parser.add_argument('-e', '--export', dest='export_file', help='export', required=False, action='store')
    ddl_parser.add_argument('-i', '--import', dest='import_file', help='import', required=False)
    data_parser = subparsers.add_parser('data', help='data', parents=[parent_parser])
    data_parser.add_argument('-e', '--export', dest='export_file', help='export', required=False, action='store')
    data_parser.add_argument('-i', '--import', dest='import_file', help='import', required=False)
    subparsers.add_parser('list', help='list', parents=[parent_parser])

    args = argparser.parse_args()
    home_dir = os.environ['HOME']
    config_path = os.path.join(home_dir, '.catdb')
    if not os.path.exists(config_path):
        sys.stderr.write(
            'File {config_path} not found. Go to https://github.com/chimpler/catdb for more details\n'.format(
                config_path=config_path))
        sys.exit(1)

    config = ConfigFactory.parse_file(config_path)
    db_config = config['databases.' + args.database]

    db = DbManager.get_db(db_config['type'], db_config)
    if args.subparser_name == 'list':
        print '\n'.join(db.list_tables(args.table, args.schema))
    elif args.subparser_name == 'ddl':
        if args.export_file:
            ddl_str = json.dumps(db.get_ddl(args.table, args.schema), sort_keys=True,
                                 indent=config['ddl-format.indent'], separators=(',', ': '))
            with open_output_file(args.export_file) as fd:
                fd.write(ddl_str)
        elif args.import_file:
            with open_input_file(args.import_file) as fd:
                ddl = json.loads(fd.read())
                table_statement = db.create_database_statement(ddl, args.database, args.schema)
                if args.dry_run:
                    print table_statement
                else:
                    db.execute(table_statement)
    elif args.subparser_name == 'data':
        if args.export_file:
            db.export_to_file(args.export_file, args.table, args.schema, config['data-format.delimiter'],
                              config['data-format.null'])

        elif args.import_file:
            db.import_from_file(args.import_fileport_file, args.table, args.schema, config['data-format.delimiter'],
                                config['data-format.null'])

if __name__ == '__main__':
    main()