text:
namespace rocksdb {

static const int kValueSize = 1000;
static const int kMaxNumValues = 2000;
static const size_t kNumIterations = 3;

class FaultInjectionTest : public testing::Test,
                           public testing::WithParamInterface<bool> {
 protected:
  enum OptionConfig {
    kDefault,
    kDifferentDataDir,
    kWalDir,
    kSyncWal,
    kWalDirSyncWal,
    kMultiLevels,
    kEnd,
  };
  int option_config_;
  // When need to make sure data is persistent, sync WAL
  bool sync_use_wal_;
  // When need to make sure data is persistent, call DB::CompactRange()
  bool sync_use_compact_;

  bool sequential_order_;

 protected:
 public:
  enum ExpectedVerifResult { kValExpectFound, kValExpectNoError };
  enum ResetMethod {
    kResetDropUnsyncedData,
    kResetDropRandomUnsyncedData,
    kResetDeleteUnsyncedFiles,
    kResetDropAndDeleteUnsynced
  };

  std::unique_ptr<Env> base_env_;
  FaultInjectionTestEnv* env_;
  std::string dbname_;
  shared_ptr<Cache> tiny_cache_;
  Options options_;
  DB* db_;

  FaultInjectionTest()
      : option_config_(kDefault),
        sync_use_wal_(false),
        sync_use_compact_(true),
        base_env_(nullptr),
        env_(NULL),
        db_(NULL) {
  }

  ~FaultInjectionTest() {
    rocksdb::SyncPoint::GetInstance()->DisableProcessing();
    rocksdb::SyncPoint::GetInstance()->ClearAllCallBacks();
  }

  bool ChangeOptions() {
    option_config_++;
    if (option_config_ >= kEnd) {
      return false;
    } else {
      if (option_config_ == kMultiLevels) {
        base_env_.reset(new MockEnv(Env::Default()));
      }
      return true;
    }
  }

  // Return the current option configuration.
  Options CurrentOptions() {
    sync_use_wal_ = false;
    sync_use_compact_ = true;
    Options options;
    switch (option_config_) {
      case kWalDir:
        options.wal_dir = test::TmpDir(env_) + "/fault_test_wal";
        break;
      case kDifferentDataDir:
        options.db_paths.emplace_back(test::TmpDir(env_) + "/fault_test_data",
                                      1000000U);
        break;
      case kSyncWal:
        sync_use_wal_ = true;
        sync_use_compact_ = false;
        break;
      case kWalDirSyncWal:
        options.wal_dir = test::TmpDir(env_) + "/fault_test_wal";
        sync_use_wal_ = true;
        sync_use_compact_ = false;
        break;
      case kMultiLevels:
        options.write_buffer_size = 64 * 1024;
        options.target_file_size_base = 64 * 1024;
        options.level0_file_num_compaction_trigger = 2;
        options.level0_slowdown_writes_trigger = 2;
        options.level0_stop_writes_trigger = 4;
        options.max_bytes_for_level_base = 128 * 1024;
        options.max_write_buffer_number = 2;
        options.max_background_compactions = 8;
        options.max_background_flushes = 8;
        sync_use_wal_ = true;
        sync_use_compact_ = false;
        break;
      default:
        break;
    }
    return options;
  }

  Status NewDB() {
    assert(db_ == NULL);
    assert(tiny_cache_ == nullptr);
    assert(env_ == NULL);

    env_ =
        new FaultInjectionTestEnv(base_env_ ? base_env_.get() : Env::Default());

    options_ = CurrentOptions();
    options_.env = env_;
    options_.paranoid_checks = true;

    BlockBasedTableOptions table_options;
    tiny_cache_ = NewLRUCache(100);
    table_options.block_cache = tiny_cache_;
    options_.table_factory.reset(NewBlockBasedTableFactory(table_options));

    dbname_ = test::TmpDir() + "/fault_test";

    EXPECT_OK(DestroyDB(dbname_, options_));

    options_.create_if_missing = true;
    Status s = OpenDB();
    options_.create_if_missing = false;
    return s;
  }

  void SetUp() override {
    sequential_order_ = GetParam();
    ASSERT_OK(NewDB());
  }

  void TearDown() override {
    CloseDB();

    Status s = DestroyDB(dbname_, options_);

    delete env_;
    env_ = NULL;

    tiny_cache_.reset();

    ASSERT_OK(s);
  }

  void Build(const WriteOptions& write_options, int start_idx, int num_vals) {
    std::string key_space, value_space;
    WriteBatch batch;
    for (int i = start_idx; i < start_idx + num_vals; i++) {
      Slice key = Key(i, &key_space);
      batch.Clear();
      batch.Put(key, Value(i, &value_space));
      ASSERT_OK(db_->Write(write_options, &batch));
    }
  }

  Status ReadValue(int i, std::string* val) const {
    std::string key_space, value_space;
    Slice key = Key(i, &key_space);
    Value(i, &value_space);
    ReadOptions options;
    return db_->Get(options, key, val);
  }

  Status Verify(int start_idx, int num_vals,
                ExpectedVerifResult expected) const {
    std::string val;
    std::string value_space;
    Status s;
    for (int i = start_idx; i < start_idx + num_vals && s.ok(); i++) {
      Value(i, &value_space);
      s = ReadValue(i, &val);
      if (s.ok()) {
        EXPECT_EQ(value_space, val);
      }
      if (expected == kValExpectFound) {
        if (!s.ok()) {
          fprintf(stderr, "Error when read %dth record (expect found): %s\n", i,
                  s.ToString().c_str());
          return s;
        }
      } else if (!s.ok() && !s.IsNotFound()) {
        fprintf(stderr, "Error when read %dth record: %s\n", i,
                s.ToString().c_str());
        return s;
      }
    }
    return Status::OK();
  }

#if __clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >= 9)
__attribute__((__no_sanitize__("undefined")))
#elif __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9)
__attribute__((__no_sanitize_undefined__))
#endif
  // Return the ith key
  Slice Key(int i, std::string* storage) const {
    int num = i;
    if (!sequential_order_) {
      // random transfer
      const int m = 0x5bd1e995;
      num *= m;
      num ^= num << 24;
    }
    char buf[100];
    snprintf(buf, sizeof(buf), "%016d", num);
    storage->assign(buf, strlen(buf));
    return Slice(*storage);
  }

  // Return the value to associate with the specified key
  Slice Value(int k, std::string* storage) const {
    Random r(k);
    return test::RandomString(&r, kValueSize, storage);
  }

  void CloseDB() {
    delete db_;
    db_ = NULL;
  }

  Status OpenDB() {
    CloseDB();
    env_->ResetState();
    return DB::Open(options_, dbname_, &db_);
  }

  void DeleteAllData() {
    Iterator* iter = db_->NewIterator(ReadOptions());
    WriteOptions options;
    for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
      ASSERT_OK(db_->Delete(WriteOptions(), iter->key()));
    }

    delete iter;

    FlushOptions flush_options;
    flush_options.wait = true;
    db_->Flush(flush_options);
  }

  // rnd cannot be null for kResetDropRandomUnsyncedData
  void ResetDBState(ResetMethod reset_method, Random* rnd = nullptr) {
    env_->AssertNoOpenFile();
    switch (reset_method) {
      case kResetDropUnsyncedData:
        ASSERT_OK(env_->DropUnsyncedFileData());
        break;
      case kResetDropRandomUnsyncedData:
        ASSERT_OK(env_->DropRandomUnsyncedFileData(rnd));
        break;
      case kResetDeleteUnsyncedFiles:
        ASSERT_OK(env_->DeleteFilesCreatedAfterLastDirSync());
        break;
      case kResetDropAndDeleteUnsynced:
        ASSERT_OK(env_->DropUnsyncedFileData());
        ASSERT_OK(env_->DeleteFilesCreatedAfterLastDirSync());
        break;
      default:
        assert(false);
    }
  }

  void PartialCompactTestPreFault(int num_pre_sync, int num_post_sync) {
    DeleteAllData();

    WriteOptions write_options;
    write_options.sync = sync_use_wal_;

    Build(write_options, 0, num_pre_sync);
    if (sync_use_compact_) {
      db_->CompactRange(CompactRangeOptions(), nullptr, nullptr);
    }
    write_options.sync = false;
    Build(write_options, num_pre_sync, num_post_sync);
  }

  void PartialCompactTestReopenWithFault(ResetMethod reset_method,
                                         int num_pre_sync, int num_post_sync,
                                         Random* rnd = nullptr) {
    env_->SetFilesystemActive(false);
    CloseDB();
    ResetDBState(reset_method, rnd);
    ASSERT_OK(OpenDB());
    ASSERT_OK(Verify(0, num_pre_sync, FaultInjectionTest::kValExpectFound));
    ASSERT_OK(Verify(num_pre_sync, num_post_sync,
                     FaultInjectionTest::kValExpectNoError));
    WaitCompactionFinish();
    ASSERT_OK(Verify(0, num_pre_sync, FaultInjectionTest::kValExpectFound));
    ASSERT_OK(Verify(num_pre_sync, num_post_sync,
                     FaultInjectionTest::kValExpectNoError));
  }

  void NoWriteTestPreFault() {
  }

  void NoWriteTestReopenWithFault(ResetMethod reset_method) {
    CloseDB();
    ResetDBState(reset_method);
    ASSERT_OK(OpenDB());
  }

  void WaitCompactionFinish() {
    static_cast<DBImpl*>(db_->GetRootDB())->TEST_WaitForCompact();
    ASSERT_OK(db_->Put(WriteOptions(), "", ""));
  }
};

TEST_P(FaultInjectionTest, FaultTest) {
  do {
    Random rnd(301);

    for (size_t idx = 0; idx < kNumIterations; idx++) {
      int num_pre_sync = rnd.Uniform(kMaxNumValues);
      int num_post_sync = rnd.Uniform(kMaxNumValues);

      PartialCompactTestPreFault(num_pre_sync, num_post_sync);
      PartialCompactTestReopenWithFault(kResetDropUnsyncedData, num_pre_sync,
                                        num_post_sync);
      NoWriteTestPreFault();
      NoWriteTestReopenWithFault(kResetDropUnsyncedData);

      PartialCompactTestPreFault(num_pre_sync, num_post_sync);
      PartialCompactTestReopenWithFault(kResetDropRandomUnsyncedData,
                                        num_pre_sync, num_post_sync, &rnd);
      NoWriteTestPreFault();
      NoWriteTestReopenWithFault(kResetDropUnsyncedData);

      // Setting a separate data path won't pass the test as we don't sync
      // it after creating new files,
      PartialCompactTestPreFault(num_pre_sync, num_post_sync);
      PartialCompactTestReopenWithFault(kResetDropAndDeleteUnsynced,
                                        num_pre_sync, num_post_sync);
      NoWriteTestPreFault();
      NoWriteTestReopenWithFault(kResetDropAndDeleteUnsynced);

      PartialCompactTestPreFault(num_pre_sync, num_post_sync);
      // No new files created so we expect all values since no files will be
      // dropped.
      PartialCompactTestReopenWithFault(kResetDeleteUnsyncedFiles, num_pre_sync,
                                        num_post_sync);
      NoWriteTestPreFault();
      NoWriteTestReopenWithFault(kResetDeleteUnsyncedFiles);
    }
  } while (ChangeOptions());
}

// Previous log file is not fsynced if sync is forced after log rolling.
TEST_P(FaultInjectionTest, WriteOptionSyncTest) {
  test::SleepingBackgroundTask sleeping_task_low;
  env_->SetBackgroundThreads(1, Env::HIGH);
  // Block the job queue to prevent flush job from running.
  env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low,
                 Env::Priority::HIGH);
  sleeping_task_low.WaitUntilSleeping();

  WriteOptions write_options;
  write_options.sync = false;

  std::string key_space, value_space;
  ASSERT_OK(
      db_->Put(write_options, Key(1, &key_space), Value(1, &value_space)));
  FlushOptions flush_options;
  flush_options.wait = false;
  ASSERT_OK(db_->Flush(flush_options));
  write_options.sync = true;
  ASSERT_OK(
      db_->Put(write_options, Key(2, &key_space), Value(2, &value_space)));

  env_->SetFilesystemActive(false);
  NoWriteTestReopenWithFault(kResetDropAndDeleteUnsynced);
  sleeping_task_low.WakeUp();
  sleeping_task_low.WaitUntilDone();

  ASSERT_OK(OpenDB());
  std::string val;
  Value(2, &value_space);
  ASSERT_OK(ReadValue(2, &val));
  ASSERT_EQ(value_space, val);

  Value(1, &value_space);
  ASSERT_OK(ReadValue(1, &val));
  ASSERT_EQ(value_space, val);
}

TEST_P(FaultInjectionTest, UninstalledCompaction) {
  options_.target_file_size_base = 32 * 1024;
  options_.write_buffer_size = 100 << 10;  // 100KB
  options_.level0_file_num_compaction_trigger = 6;
  options_.level0_stop_writes_trigger = 1 << 10;
  options_.level0_slowdown_writes_trigger = 1 << 10;
  options_.max_background_compactions = 1;
  OpenDB();

  if (!sequential_order_) {
    rocksdb::SyncPoint::GetInstance()->LoadDependency({
        {"FaultInjectionTest::FaultTest:0", "DBImpl::BGWorkCompaction"},
        {"CompactionJob::Run():End", "FaultInjectionTest::FaultTest:1"},
        {"FaultInjectionTest::FaultTest:2",
         "DBImpl::BackgroundCompaction:NonTrivial:AfterRun"},
    });
  }
  rocksdb::SyncPoint::GetInstance()->EnableProcessing();

  int kNumKeys = 1000;
  Build(WriteOptions(), 0, kNumKeys);
  FlushOptions flush_options;
  flush_options.wait = true;
  db_->Flush(flush_options);
  ASSERT_OK(db_->Put(WriteOptions(), "", ""));
  TEST_SYNC_POINT("FaultInjectionTest::FaultTest:0");
  TEST_SYNC_POINT("FaultInjectionTest::FaultTest:1");
  env_->SetFilesystemActive(false);
  TEST_SYNC_POINT("FaultInjectionTest::FaultTest:2");
  CloseDB();
  rocksdb::SyncPoint::GetInstance()->DisableProcessing();
  ResetDBState(kResetDropUnsyncedData);

  std::atomic<bool> opened(false);
  rocksdb::SyncPoint::GetInstance()->SetCallBack(
      "DBImpl::Open:Opened", [&](void* arg) { opened.store(true); });
  rocksdb::SyncPoint::GetInstance()->SetCallBack(
      "DBImpl::BGWorkCompaction",
      [&](void* arg) { ASSERT_TRUE(opened.load()); });
  rocksdb::SyncPoint::GetInstance()->EnableProcessing();
  ASSERT_OK(OpenDB());
  ASSERT_OK(Verify(0, kNumKeys, FaultInjectionTest::kValExpectFound));
  WaitCompactionFinish();
  ASSERT_OK(Verify(0, kNumKeys, FaultInjectionTest::kValExpectFound));
  rocksdb::SyncPoint::GetInstance()->DisableProcessing();
  rocksdb::SyncPoint::GetInstance()->ClearAllCallBacks();
}

TEST_P(FaultInjectionTest, ManualLogSyncTest) {
  test::SleepingBackgroundTask sleeping_task_low;
  env_->SetBackgroundThreads(1, Env::HIGH);
  // Block the job queue to prevent flush job from running.
  env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low,
                 Env::Priority::HIGH);
  sleeping_task_low.WaitUntilSleeping();

  WriteOptions write_options;
  write_options.sync = false;

  std::string key_space, value_space;
  ASSERT_OK(
      db_->Put(write_options, Key(1, &key_space), Value(1, &value_space)));
  FlushOptions flush_options;
  flush_options.wait = false;
  ASSERT_OK(db_->Flush(flush_options));
  ASSERT_OK(
      db_->Put(write_options, Key(2, &key_space), Value(2, &value_space)));
  ASSERT_OK(db_->SyncWAL());

  env_->SetFilesystemActive(false);
  NoWriteTestReopenWithFault(kResetDropAndDeleteUnsynced);
  sleeping_task_low.WakeUp();
  sleeping_task_low.WaitUntilDone();

  ASSERT_OK(OpenDB());
  std::string val;
  Value(2, &value_space);
  ASSERT_OK(ReadValue(2, &val));
  ASSERT_EQ(value_space, val);

  Value(1, &value_space);
  ASSERT_OK(ReadValue(1, &val));
  ASSERT_EQ(value_space, val);
}

TEST_P(FaultInjectionTest, WriteBatchWalTerminationTest) {
  ReadOptions ro;
  Options options = CurrentOptions();
  options.env = env_;

  WriteOptions wo;
  wo.sync = true;
  wo.disableWAL = false;
  WriteBatch batch;
  batch.Put("cats", "dogs");
  batch.MarkWalTerminationPoint();
  batch.Put("boys", "girls");
  ASSERT_OK(db_->Write(wo, &batch));

  env_->SetFilesystemActive(false);
  NoWriteTestReopenWithFault(kResetDropAndDeleteUnsynced);
  ASSERT_OK(OpenDB());

  std::string val;
  ASSERT_OK(db_->Get(ro, "cats", &val));
  ASSERT_EQ("dogs", val);
  ASSERT_EQ(db_->Get(ro, "boys", &val), Status::NotFound());
}

INSTANTIATE_TEST_CASE_P(FaultTest, FaultInjectionTest, ::testing::Bool());

}  // namespace rocksdb

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text:
/*
Package csvrecord reads a CSV file into a a slice of Record. A Record represents a row in the CSV,
with each key corresponding to a column header from the first line.
*/
package csvrecord

// TODO: add unit tests.

import (
	"encoding/csv"
	"errors"
	"io"
)

type Record map[string]string

func Read(r io.Reader) ([]Record, error) {
	reader := csv.NewReader(r)
	reader.TrailingComma = true
	reader.LazyQuotes = true
	header, err := reader.Read()
	if err != nil {
		return nil, err
	}
	var records []Record
	for {
		row, err := reader.Read()
		if err != nil {
			if err == io.EOF {
				break
			}
			return nil, err
		}
		if len(row) != len(header) {
			return nil, errors.New("csv contains rows with different row numbers")
		}
		rec := make(map[string]string)
		for i, key := range header {
			rec[key] = row[i]
		}
		records = append(records, rec)
	}
	return records, nil
}

redpajama_set_name: RedPajamaGithub


text:
Experimental project for AI binary graph.

![test-sin-screenshot0.jpg](https://raw.githubusercontent.com/sea-kg/bna/master/contrib/test-sin-screenshot0.jpg)

## Build and run

### Ubuntu/Debian

Requirements:
```
$ sudo apt install g++ cmake libsdl2-dev libsdl2-ttf-dev
```

Build
```
$ ./build_simple.sh
```

Run:
```
$ ./bna test-sin
```

### MacOS

Install requirements:
```
% brew install cmake sdl2 sdl2_mixer
```

Build:
```
% ./build_simple.sh
```

Run:
```
% ./bna test-sin
```


text:
document.addEventListener('DOMContentLoaded', function() {

  if (localStorage.tpw_tabDialogForms) {
    var item = JSON.parse(localStorage.tpw_tabDialogForms);
    console.log(item);
    document.getElementById('siteDialogURL').value = item.host || '';
    document.getElementById('siteDialogName').value = '';
    document.getElementById('siteDialogId').value = item.id || '';
    document.getElementById('siteDialogGroup').value = item.identify || '';
    document.getElementById('siteDialogUsername').value = item.userName || '';
    document.getElementById('siteDialogPassword').value = item.passWord || '';
    document.getElementById('siteDialogNotes').value = '';
    document.getElementById('dialogInput1').value = item.inputId1 || '';
    document.getElementById('dialogInput2').value = item.inputId2 || '';
    localStorage.removeItem('tpw_tabDialogForms');
  } else if (localStorage.tpw_tabDialogId) {
    var port = chrome.runtime.connect({
      name: "getItem"
    });
    port.postMessage({
      id: localStorage.tpw_tabDialogId
    });
    port.onMessage.addListener(function(result) {
      document.getElementById('siteDialogURL').value = result.item.host || '';
      document.getElementById('siteDialogName').value = result.item.name || '';
      document.getElementById('siteDialogId').value = result.item.id || '';
      document.getElementById('siteDialogGroup').value = result.item.identify || '';
      document.getElementById('siteDialogUsername').value = result.item.userName || '';
      document.getElementById('siteDialogPassword').value = result.item.passWord || '';
      document.getElementById('siteDialogNotes').value = result.item.other || '';
      document.getElementById('dialogInput1').value = result.item.inputId1 || '';
      document.getElementById('dialogInput2').value = result.item.inputId2 || '';
    });
    localStorage.removeItem('tpw_tabDialogId');
  }

  document.querySelector('.showPassword').addEventListener('click', function() {
    if (document.querySelector('.showPassword').className.indexOf('selected') >= 0) {
      document.querySelector('.showPassword').className = document.querySelector('.showPassword').className.replace(/selected/, '');
      document.getElementById('siteDialogPassword').type = 'password';
    } else {
      document.querySelector('.showPassword').className = document.querySelector('.showPassword').className + ' selected';
      document.getElementById('siteDialogPassword').type = 'text';
    }
  });

  document.getElementById('cancel').addEventListener('click', function() {
    window.close();
  });

  document.getElementById('delete').addEventListener('click', function() {
    if (!document.getElementById('siteDialogId').value) {
      alert('表单不可用');
      return;
    }
    document.getElementById('_loading').style.display = "block";

    var port = chrome.runtime.connect({
      name: "deleteItem"
    });
    port.postMessage({
      id: document.getElementById('siteDialogId').value
    });
    port.onMessage.addListener(function(result) {
      if (result.msg == 'ok') {
        window.close();
      } else {
        document.getElementById('_loading').style.display = "none";
        alert(result.msg);
      }
    });
  });
  document.getElementById('save').addEventListener('click', function() {
    if (!document.getElementById('siteDialogId').value) {
      alert('表单不可用');
      return;
    }
    // 增加一个item
    var newItem = {
      id: document.getElementById('siteDialogId').value || '',
      name: document.getElementById('siteDialogName').value || '',
      userName: document.getElementById('siteDialogUsername').value || '',
      passWord: document.getElementById('siteDialogPassword').value || '',
      other: document.getElementById('siteDialogNotes').value || '',
      host: document.getElementById('siteDialogURL').value || '',
      identify: document.getElementById('siteDialogGroup').value || '',
      inputId1: document.getElementById('dialogInput1').value || '',
      inputId2: document.getElementById('dialogInput2').value || '',
    };

    var port = chrome.runtime.connect({
      name: "addItem"
    });
    port.postMessage({
      newItem: newItem
    });
    document.getElementById('_loading').style.display = "block";
    port.onMessage.addListener(function(result) {
      if (result.msg == 'ok') {
        document.getElementById('_loading').style.display = "none";
        window.close();

      } else {
        document.getElementById('_loading').style.display = "none";
        alert(result.msg);
      }
    });

  });

});


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Letter_Grade__c</name>
    <help>Si la vostra escola utilitza qualificacions de lletra, introduïu la qualificació de la lletra obtinguda per l'alumne, per exemple, A, B, C, etc.</help>
    <label>Qualificació amb lletres</label>
</CustomFieldTranslation>


text:
//!
//! \file MergedSeriesInterface.cpp
//! \brief The MergedSeriesInterface.cpp file contains the definition of
//!        non-inline methods of the MergedSeriesInterface class.
//!
//! \author Quentin Smetz
//!

#include "MergedSeriesInterface.h"
using namespace std;
using namespace customwidget;

// Constructor
MergedSeriesInterface::MergedSeriesInterface(QString const& title, QWidget* parent)
    : DisplayInterface(parent), m_seriesInterfaces()
{
    cout << "Building merged series interface... " << flush;

    m_title = title;
    setWindowTitle(m_title);

    m_seriesSelector = new ComboBox();
    m_seriesSelector->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    m_toolBar->addWidget(m_seriesSelector);
    m_lastSelectedSeriesIndex = -1;

    m_opacitySlider = new DoubleSlider(Qt::Horizontal);
    m_opacitySlider->setDoubleRange(Range(0, 1), 0.05);
    m_opacitySlider->setMaximumWidth(100);
    m_opacitySlider->setEnabled(false);
    m_toolBar->addWidget(m_opacitySlider);

    m_subInterface[VOLUME] = new VolumeSubInterface(new MergedSeriesVolumeViewer());
    m_subInterface[SAGITTAL_SLICE] = new SliceSubInterface(
                new MergedSeriesSliceViewer(SAGITTAL));
    m_subInterface[FRONTAL_SLICE] = new SliceSubInterface(
                new MergedSeriesSliceViewer(FRONTAL));
    m_subInterface[TRANSVERSE_SLICE] = new SliceSubInterface(
                new MergedSeriesSliceViewer(TRANSVERSE));

    setLayoutStyle(DisplayInterface::MODE1);

    for(unsigned int i = 0 ; i < 4 ; i++)
        connect(m_subInterface[i], SIGNAL(doubleClicked(SubInterface*)), this, SLOT(setSubInterfaceMaximized(SubInterface*)));

    connect(m_seriesSelector, SIGNAL(currentIndexChanged(int)), this, SLOT(updateToolBarForSeries(int)));
    connect(m_opacitySlider, SIGNAL(doubleValueChanged(double)), this, SLOT(changeCurrentSeriesOpacity(double)));

    cout << "done." << endl;
}

// Destructor
MergedSeriesInterface::~MergedSeriesInterface()
{
     cout << "Merged series interface freed." << endl;
}

// The 'addSeriesInterface' method
void MergedSeriesInterface::addSeriesInterface(SeriesInterface* interface)
{
    if(containsSeriesInterface(interface))
        return;

    m_seriesInterfaces.push_back(interface);

    interface->allowFusion(true);
    m_seriesSelector->addItem(interface->title());
    connect(interface, SIGNAL(viewConfigurationChanged(ViewConfiguration const&, ViewConfiguration::ViewParam)),
            this, SLOT(updateViewConfiguration(ViewConfiguration const&, ViewConfiguration::ViewParam)));

    for(unsigned int i = 0 ; i < 4 ; i++)
    {
        MergedSeriesViewer* msv = 0;
        msv = dynamic_cast<MergedSeriesViewer*>(m_subInterface[i]->viewer());

        SeriesViewer* sv = dynamic_cast<SeriesViewer*>(interface->viewer(i));
        msv->linkSeriesViewer(sv);
    }

    dynamic_cast<SliceSubInterface*>(m_subInterface[SAGITTAL_SLICE])->updateSliceRange();
    dynamic_cast<SliceSubInterface*>(m_subInterface[FRONTAL_SLICE])->updateSliceRange();
    dynamic_cast<SliceSubInterface*>(m_subInterface[TRANSVERSE_SLICE])->updateSliceRange();

    if(m_seriesInterfaces.size() == 1)
        m_opacitySlider->setDoubleValue(1.0);
}

// The 'removeSeriesInterface' method
void MergedSeriesInterface::removeSeriesInterface(SeriesInterface* interface, bool checkIfContains)
{
    if(checkIfContains && !containsSeriesInterface(interface))
        return;

    for(unsigned int i = 0 ; i < 4 ; i++)
    {
        MergedSeriesViewer* msv = 0;
        msv = dynamic_cast<MergedSeriesViewer*>(m_subInterface[i]->viewer());

        SeriesViewer* sv = dynamic_cast<SeriesViewer*>(interface->viewer(i));
        msv->unlinkSeriesViewer(sv);
    }

    disconnect(interface, SIGNAL(viewConfigurationChanged(ViewConfiguration const&, ViewConfiguration::ViewParam)),
               this, SLOT(updateViewConfiguration(ViewConfiguration const&, ViewConfiguration::ViewParam)));
    QList<QAction*> actions = interface->getCustomActions();
    for(int i = 0 ; i < actions.size() ; i++)
        m_toolBar->removeAction(actions.at(i));

    interface->allowFusion(false);

    unsigned int pos = 0;
    vector<SeriesInterface*>::iterator iter = m_seriesInterfaces.begin();
    while(iter != m_seriesInterfaces.end())
    {
        if(interface == *iter)
            break;

        pos++;
        iter++;
    }
    updateToolBarForSeries(-1);
    m_seriesSelector->blockSignals(true);
    m_seriesSelector->removeItem(pos);
    m_seriesInterfaces.erase(iter);
    m_seriesSelector->blockSignals(false);
    if(m_seriesSelector->count() > 0)
    {
        m_seriesSelector->setCurrentIndex(0);
        updateToolBarForSeries(0);
    }

    dynamic_cast<SliceSubInterface*>(m_subInterface[SAGITTAL_SLICE])->updateSliceRange();
    dynamic_cast<SliceSubInterface*>(m_subInterface[FRONTAL_SLICE])->updateSliceRange();
    dynamic_cast<SliceSubInterface*>(m_subInterface[TRANSVERSE_SLICE])->updateSliceRange();

    if(m_seriesInterfaces.size() == 1)
        m_opacitySlider->setDoubleValue(1.0);
}

// The 'removeAllSeriesInterface' method
void MergedSeriesInterface::removeAllSeriesInterface()
{
    while(m_seriesInterfaces.size() > 0)
        removeSeriesInterface(m_seriesInterfaces.at(0));
}

// The 'containsSeriesInterface' method
bool MergedSeriesInterface::containsSeriesInterface(SeriesInterface const* interface) const
{
    for(vector<SeriesInterface*>::const_iterator iter = m_seriesInterfaces.begin()
         ; iter != m_seriesInterfaces.end() ; iter++)
    {
        if(*iter == interface)
            return true;
    }

    return false;
}

// The 'updateToolBarForSeries' slot
void MergedSeriesInterface::updateToolBarForSeries(int index)
{
    // Opacity
    if(index >= 0)
    {
        m_opacitySlider->setEnabled(true);
        SeriesInterface* interface = m_seriesInterfaces.at(m_seriesSelector->currentIndex());
        m_opacitySlider->setDoubleValue(interface->getPropsOpacity());
    }
    else
        m_opacitySlider->setEnabled(false);

    // Actions
    if(m_lastSelectedSeriesIndex >= 0)
    {
        QList<QAction*> actions = m_seriesInterfaces.at(m_lastSelectedSeriesIndex)->getCustomActions();
        for(int i = 0 ; i < actions.size() ; i++)
            m_toolBar->removeAction(actions.at(i));
    }

    if(index >= 0)
        m_toolBar->addActions(m_seriesInterfaces.at(index)->getCustomActions());

    m_lastSelectedSeriesIndex = index;
}

// The 'changeCurrentSeriesOpacity' slot
void MergedSeriesInterface::changeCurrentSeriesOpacity(double opacity)
{
    if(m_seriesInterfaces.size() == 0)
        return;

    SeriesInterface* interface = m_seriesInterfaces.at(m_seriesSelector->currentIndex());
    interface->setPropsOpacity(opacity);
    for(unsigned int i = 0 ; i < 4 ; i++)
        viewer(i)->repaint();
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using bv.model.BLToolkit;
using bv.model.Model.Core;
using bv.model.Helpers;
using bv.common.Core;
using eidss.model.Enums;

namespace eidss.model.Schema
{
    public partial class HumanCase
    {
        /*
        partial void Created(bv.model.BLToolkit.DbManagerProxy manager)
        {
            SetParent();
        }
        partial void Loaded(bv.model.BLToolkit.DbManagerProxy manager)
        {
            SetParent();
        }

        private void SetParent()
        {
            Patient.HCase = this;
            Patient.CurrentResidenceAddress.HCase = this;
            Patient.EmployerAddress.HCase = this;
            Patient.RegistrationAddress.HCase = this;
            RegistrationAddress.HCase = this;
        }
        private void ClearParent()
        {
            Patient.HCase = null;
            Patient.CurrentResidenceAddress.HCase = null;
            Patient.EmployerAddress.HCase = null;
            Patient.RegistrationAddress.HCase = null;
            RegistrationAddress.HCase = null;
        }
        */
        /*
        public override object Clone()
        {
            ClearParent();
            HumanCase ret = base.Clone() as HumanCase;
            SetParent();
            ret.SetParent();
            return ret;
        }

        partial void Cloned(bv.model.BLToolkit.DbManagerProxy manager, IObject clone)
        {
            var ret = clone as HumanCase;
            Accessor acc = Accessor.Instance(null);
            acc._SetupLoad(manager, ret);
            Samples.ForEach(c => ret.Samples.Add(c.DeepClone(manager)));
            CaseTests.ForEach(c => ret.CaseTests.Add(c.DeepClone(manager)));
        }
        */
        /*public HumanCase DeepClone()
        {
            HumanCase ret = base.Clone() as HumanCase;
            ret.m_IsNew = this.IsNew;
            ret.m_ObjectName = this.m_ObjectName;
            Accessor acc = Accessor.Instance(null);
            ret.Patient = Patient.DeepClone();
            ret.PointGeoLocation = PointGeoLocation.DeepClone();
            using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance))
            {
                acc._SetupLoad(manager, ret);
            }
            return ret;
        }*/

        public int? CalcPatientAge()
        {
            int _intPatientAge = 0;
            long _idfsHumanAgeType = 0;
            if (GetDOBandAge(ref _intPatientAge, ref _idfsHumanAgeType))
                return _intPatientAge;
            return this.Patient.intPatientAgeFromCase;
        }

        public long? CalcPatientAgeType()
        {
            int _intPatientAge = 0;
            long _idfsHumanAgeType = 0;
            if (GetDOBandAge(ref _intPatientAge, ref _idfsHumanAgeType))
                return _idfsHumanAgeType;
            return this.Patient.idfsHumanAgeTypeFromCase;
        }

        private bool GetDOBandAge(ref int _intPatientAge, ref long _idfsHumanAgeType)
        {
            double ddAge = -1;
            DateTime? datUp = null;
            if (this.Patient.datDateofBirth.HasValue && this.datD.HasValue)
            {
                datUp = this.datD;
                ddAge = - this.Patient.datDateofBirth.Value.Date.Subtract(this.datD.Value.Date).TotalDays;

                if (ddAge > -1)
                {
                    long yyAge = DateHelper.DateDifference(DateInterval.Year, this.Patient.datDateofBirth.Value.Date, datUp.Value);
                    if (yyAge > 0)
                    {
                        //'Years
                        _intPatientAge = (int)yyAge;
                        _idfsHumanAgeType = (long)HumanAgeTypeEnum.Years;
                        return true;
                    }
                    else
                    {
                        long mmAge = DateHelper.DateDifference(DateInterval.Month, this.Patient.datDateofBirth.Value.Date, datUp.Value);
                        if (mmAge > 0)
                        {
                            //'Months
                            _intPatientAge = (int)mmAge;
                            _idfsHumanAgeType = (long)HumanAgeTypeEnum.Month;
                            return true;
                        }
                        else
                        {
                            //'Days
                            _intPatientAge = (int)ddAge;
                            _idfsHumanAgeType = (long)HumanAgeTypeEnum.Days;
                            return true;
                        }
                    }
                }
            }
            return false;
        }

    }
}


text:
<?php

/* @var $this yii\web\View */
/* @var $name string */
/* @var $message string */
/* @var $exception Exception */

use yii\helpers\Html;

$this->title = $name;
?>

<?= Html::encode($message) ?>

        <form action="<?= url(['/search']) ?>" method="get">

                <input type="text" class="form-control" name="q" placeholder="全站搜索">

                    <button type="submit" class="btn btn-default">

                    </button>

        </form>


text:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-v","--verbose", help="increase output verbose", action="store_true")
args = parser.parse_args()

if args.verbose:
    print("verbose turned on")


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/***********
Developed by
	Bijender Antil
Ajax Pagination
**************/

class Admin_pagination{

	################ pagination function #########################################
	public function paginate_function($item_per_page, $current_page, $total_records, $total_pages)
	{
		$pagination = '';

		if($total_pages > 0 && $total_pages != 1 && $current_page <= $total_pages){ //verify total pages and current page number
			$pagination .= '

';

			$right_links    = $current_page + 3;
			$previous       = $current_page - 3; //previous link
			$next           = $current_page + 1; //next link
			$first_link     = true; //boolean var to decide our first link

			if($current_page > 1){
				$previous_link = ($previous==0)?1:$previous;
				$pagination .= '
«
'; //first link
				$pagination .= '
Prev
'; //previous link
					for($i = ($current_page-2); $i < $current_page; $i++){ //Create left-hand side links
						if($i > 0){
							$pagination .= '
'.$i.'
';
						}
					}
				$first_link = false; //set first link to false
			}

			if($first_link){ //if current active page is first link
				$pagination .= '
'.$current_page.'
';
			}elseif($current_page == $total_pages){ //if it's the last active link
				$pagination .= '
'.$current_page.'
';
			}else{ //regular current link
				$pagination .= '
'.$current_page.'
';
			}

			for($i = $current_page+1; $i < $right_links ; $i++){ //create right-hand side links
				if($i<=$total_pages){
					$pagination .= '
'.$i.'
';
				}
			}
			if($current_page < $total_pages){
					$next_link = ($i > $total_pages)? $total_pages : $i;
					$pagination .= '
Next
'; //next link
					$pagination .= '
»
'; //last link
			}

			$pagination .= '
';
		}

		return $pagination; //return pagination links
	}
}
/* End of file admin_pagination.php */


text:
        <?php echo __('Change password'); ?>

                    <?php echo __('Old password'); ?>

                    <input type="password"  id="old-password" class="form-control search-query" placeholder="<?php echo __('Type the current password'); ?>">

                    <?php echo __('New password'); ?>

                    <input type="password"  id="password" class="form-control search-query" placeholder="<?php echo __('Type new password'); ?>">

                    <?php echo __('Confirm password'); ?>

                    <input type="password"  id="cpassword" class="form-control search-query" placeholder="<?php echo __('Confirm password'); ?>">

                    <button type="button" id="change-pass" class="btn btn-purple btn-sm btn-fix" style="margin-top: 2px !important;">
                        <?php echo __('Change'); ?>

                    </button>


text:
import java.util.List;

interface ExampleInterface {
    public List exampleMethod();
}

class ExampleSuperClass {
    public List<String> exampleMethod() {
        return null;
    }
}

class  ExampleSubClass extends ExampleSuperClass implements ExampleInterface {
}


text:
<?php

class dmConfigForm extends dmForm
{

  public function configure()
  {
  }

  public function save()
  {
    foreach($this->widgetSchema->getFields() as $name => $field)
    {
      dmConfig::set($name, $this->getValue($name));
    }
  }

  public function addSettings(array $settings)
  {
    foreach($settings as $setting)
    {
      $this->addSetting($setting);
    }
  }

  public function addSetting(DmSetting $setting)
  {
    $settingName = $setting->get('name');

    $this->widgetSchema[$settingName] = $this->getSettingWidget($setting);

//    $this->widgetSchema[$settingName]->setDefault($setting->get('value'));

    $this->widgetSchema->setHelp($settingName, $setting->get('description'));

    $this->validatorSchema[$settingName] = $this->getSettingValidator($setting)->setOption('required', false);
  }

  public function removeSetting($settingName)
  {
    unset($this[$settingName]);
  }

  public function getSettingWidget(DmSetting $setting)
  {
    $method = 'get'.dmString::camelize($setting->type).'SettingWidget';

    return $this->$method($setting);
  }

  public function getSettingValidator(DmSetting $setting)
  {
    $method = 'get'.dmString::camelize($setting->type).'SettingValidator';

    return $this->$method($setting);
  }

  //Type Textarea
  protected function getTextSettingWidget(DmSetting $setting)
  {
    $widget = new sfWidgetFormInputText(array(), $setting->getParamsArray());

    return $widget->setDefault($setting->get('value'));
  }

  protected function getTextSettingValidator(DmSetting $setting)
  {
    return new sfValidatorString();
  }

  //Type Textarea
  protected function getTextareaSettingWidget(DmSetting $setting)
  {
    $widget = new sfWidgetFormTextarea(array(), $setting->getParamsArray());

    return $widget->setDefault($setting->get('value'));
  }

  protected function getTextareaSettingValidator(DmSetting $setting)
  {
    return new sfValidatorString();
  }

  // Type Number
  protected function getNumberSettingWidget(DmSetting $setting)
  {
    $widget = new sfWidgetFormInputText(array(), $setting->getParamsArray());

    return $widget->setDefault($setting->get('value'));
  }

  protected function getNumberSettingValidator(DmSetting $setting)
  {
    return new sfValidatorNumber();
  }

  // Type Boolean
  protected function getBooleanSettingWidget(DmSetting $setting)
  {
    $widget = new sfWidgetFormInputCheckbox(array(), $setting->getParamsArray());

    return $widget->setDefault(1 == $setting->get('value') ? true : false);
  }

  protected function getBooleanSettingValidator(DmSetting $setting)
  {
    return new sfValidatorBoolean();
  }

  //Type Select List
  protected function getSelectSettingWidget(DmSetting $setting)
  {
    $widget = new sfWidgetFormSelect(array('choices' => $setting->getParamsArray()));

    return $widget->setDefault($setting->get('value'));
  }

  protected function getSelectSettingValidator(DmSetting $setting)
  {
    return new sfValidatorChoice(array('choices' => array_keys($setting->getParamsArray())));
  }

}


text:
/**
 * File game.js
 * implemented by Adelino Lobão
 * 20/01/2012
 * modified by Niccolò Perego, Leonardo Riva, Tomas Abbondi, Riccardo Merlo, Enrico Biella, Davide Atzeni.
 * 23/10/2016
 */

/**
 * Draw the window game
 */
/**
 * File colision.js
 * implemented by Adelino Lobão
 * 20/01/2012
 * modified by Niccolò Perego, Leonardo Riva, Tomas Abbondi, Riccardo Merlo, Enrico Biella
 * 23/10/2016
 */
var drawWindow = function () {
    context.fillStyle = '#000';
    context.clearRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
    context.beginPath();
    context.rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
    context.closePath();
    context.fill();
}

/**
 * Create an horde of enemies, the horde is divided in columns and rows
 * @param numRows - indicate the number of rows
 * @param numCols - indicate the number of columns
 */
var createEnemies = function (numRows, numCols) {
    //reference position xx
    var refPosX = (WINDOW_WIDTH / 2);
    //reference position yy
    var refPosY = (WINDOW_HEIGHT / 10);
    //add enemies horde
    for (var x = 0; x < numRows; ++x) {
        for (var y = 0; y < numCols; ++y) {
            //position xx
            var posX = refPosX + (40 * x);
            //position yy
            var posY = refPosY + (40 * y);
            //add an enemy to the array
            enemies[enemies.length] = new Enemy(posX, posY);
        }
    }
}

/**
 * Animate elements
 */
var animate = function () {
    var currentAction = '';

    if (player.movingLeft)    player.moveLeft();
    else if (player.movingRight)    player.moveRight();

    //iterate through all the lasers
    for (index in lasers) {
        //draw laser
        lasers[index].draw();
        //simulate one step
        if (lasers[index].step()) {
            lasers.splice(index, 1);
        }
    }

	//check the movement of the enemies
	for(index in enemies) {
		currentAction = enemies[index].checkStep();
		if(currentAction != previousAction){
			break;
		}
	}

    //iterate through all the enemies
    for (index in enemies) {
        //draw enemy
        enemies[index].draw();
        //jump enemy
        if (currentAction != previousAction) {
            enemies[index].jump();
        } else {
            //simulate step
            enemies[index].step();
        }
    }
    previousAction = currentAction;
}

/**
 * Detect colisions between the lasers and enemies
 */
var detectColisions = function() {
	for(indexLaser in lasers) {
		for(indexEnemy in enemies) {
			if(colisionHandler.detectColisionBetweenObjects(lasers[indexLaser], enemies[indexEnemy])) {
				lasers.splice(indexLaser, 1);
				enemies.splice(indexEnemy, 1);
                player.incrementScore();
                score = player.getScore();

                if (player.getScore() != TOTAL_SCORE) {
                    setText("SCORE = " + score);
                    playSound('script/sounds/kill_sound.mp3');

                } else {
                    setText("GAME OVER!");
                    playSound('script/sounds/finish_sound.mp3');
                }

				break;
			}
		}
	}
}

/**
 * Display some text on the screen
 * @param t text
 */
var setText = function(t) {
    span = document.getElementById("textelement");
    txt = document.createTextNode(t);
    span.innerText = txt.textContent;
}

/**
 * Play a sound
 * @param s sound path
 */
var playSound = function(s) {
    var audio = new Audio(s);
    audio.play();
}

/**
 * Run the game
 */
var runGame = function () {
    //draw the window game
    drawWindow();
    //draw the player
    player.draw();
    //animate all the elements
    animate();
    //check collisions
    detectColisions();
    //set timeout function
    gameLoop = setTimeout(runGame, intervalTime);
}

//window width
const WINDOW_WIDTH = 600;
//window height
const WINDOW_HEIGHT = 600;
//frame rate
const FRAME_RATE = 50;

//game loop
var gameLoop;
//interval time
var intervalTime = 1000 / FRAME_RATE;

//previous action of enemies
var previousAction = 'left';

//get frame window
var frameWindow = document.getElementById("content");
//frame window width
frameWindow.width = WINDOW_WIDTH;
//frame window height
frameWindow.height = WINDOW_HEIGHT;
//get context
var context = frameWindow.getContext("2d");

//keyhandler object
var keyHandler = new KeyHandler();
//colisionhandler object
var colisionHandler = new ColisionHandler();
//player object
var player = new Player();
//array that store the lasers
var lasers = new Array();
//array that store the enemies
var enemies = new Array();

const enemies_row = 6;
const enemies_height = 6;

//add enemies
createEnemies(enemies_row, enemies_height);

//handle events when the a key is pressed
document.onkeydown = function(e) {
	keyHandler.keyPress(e);
}

//handle events when the key is released
document.onkeyup = function(e) {
	keyHandler.keyUp(e);
}

const TOTAL_SCORE = enemies_row * enemies_height * player.getSingleScore();

//run the game
runGame();


text:
title: "Intern"
place: "Walt Disney Co."
year: " Jan-Jul 2012"
---
During my time as an intern for the Disney College Program, I was responsible for maintaining optimal stock levels as well as training vendors in best practices. I also completed a course in enviromental sustainability.


text:
<?php
namespace spec\watoki\boxes;

use spec\watoki\boxes\fixtures\BoxFixture;
use watoki\scrut\Specification;

/**
 * @property BoxFixture box <-
 */
class WrapRedirectsTest extends Specification {

    function testAbsolutePath() {
        $this->box->givenTheBoxContainer('o');
        $this->box->givenTheBoxContainer_WithBody('a', '
            public function doGet() {
                return \watoki\curir\responder\Redirecter::fromString("/some/where/b?foo=baz");
            }');

        $this->box->given_Contains('o', 'a');

        $this->box->givenTheContextIs("/some/where");
        $this->box->givenTheRequestArgument_Is('_a/foo', 'bar');

        $this->box->whenIGetTheResponseFrom('o');
        $this->box->thenTheResponseShouldBeARedirectionTo('/some/where?_a[!]=b&_a[foo]=baz&_=a');
    }

    function testWithState() {
        $this->box->givenTheBoxContainer('o');
        $this->box->givenTheBoxContainer_WithBody('a', '
            public function doGet() {
                return \watoki\curir\responder\Redirecter::fromString("b?foo=baz");
            }');
        $this->box->givenTheBoxContainer('b');
        $this->box->givenTheBoxContainer('c');
        $this->box->givenTheBoxContainer('d');

        $this->box->given_Contains('o', 'a');
        $this->box->given_Contains('o', 'b');
        $this->box->given_Contains('b', 'c');

        $this->box->givenTheRequestArgument_Is('foo', 'O');
        $this->box->givenTheRequestArgument_Is('_a/foo', 'A');
        $this->box->givenTheRequestArgument_Is('_a/me', 'you');
        $this->box->givenTheRequestArgument_Is('_b/foo', 'B');
        $this->box->givenTheRequestArgument_Is('_b/_c/foo', 'C');

        $this->box->whenIGetTheResponseFrom('o');
        $this->box->thenTheResponseShouldBeARedirectionTo('?foo=O&_b[foo]=B&_b[_c][foo]=C&_a[!]=b&_a[foo]=baz&_=a');
    }

    function testEmptyPath() {
        $this->box->givenTheBoxContainer('o');
        $this->box->givenTheBoxContainer_WithBody('a', '
            public function doGet() {
                return \watoki\curir\responder\Redirecter::fromString("?foo=baz");
            }');

        $this->box->given_Contains('o', 'a');

        $this->box->whenIGetTheResponseFrom('o');
        $this->box->thenTheResponseShouldBeARedirectionTo('?_a[!]=a&_a[foo]=baz&_=a');
    }

    function testEdgeCaseChangedContext() {
        $this->box->givenTheBoxContainer('o');
        $this->box->givenTheBoxContainer_WithBody('a', '
            public function doGet() {
                return \watoki\curir\responder\Redirecter::fromString("?foo=bar");
            }');

        $this->box->given_Contains('o', 'a');

        $this->box->givenTheContextIs('http://foo');

        $this->box->whenIGetTheResponseFrom('o');
        $this->box->thenTheResponseShouldBeARedirectionTo('http://foo?_a[!]=a&_a[foo]=bar&_=a');
    }
}


text:
//---------------------------------------------------------------------------
#include "checkuninitvar.h"
#include "astutils.h"
#include "mathlib.h"
#include "checknullpointer.h"   // CheckNullPointer::parseFunctionCall
#include "symboldatabase.h"
#include <algorithm>
#include <map>
#include <cassert>
#include <stack>
//---------------------------------------------------------------------------

// Register this check class (by creating a static instance of it)
namespace {
    CheckUninitVar instance;
}

//---------------------------------------------------------------------------

void CheckUninitVar::check()
{
    const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase();
    std::list<Scope>::const_iterator scope;

    // check every executable scope
    for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) {
        if (scope->isExecutable()) {
            checkScope(&*scope);
        }
    }
}

void CheckUninitVar::checkScope(const Scope* scope)
{
    for (std::list<Variable>::const_iterator i = scope->varlist.begin(); i != scope->varlist.end(); ++i) {
        if ((_tokenizer->isCPP() && i->type() && !i->isPointer() && i->type()->needInitialization != Type::True) ||
            i->isStatic() || i->isExtern() || i->isReference())
            continue;

        // don't warn for try/catch exception variable
        if (i->isThrow())
            continue;

        if (i->nameToken()->strAt(1) == "(" || i->nameToken()->strAt(1) == "{"  || i->nameToken()->strAt(1) == ":")
            continue;

        if (Token::Match(i->nameToken(), "%name% =")) { // Variable is initialized, but Rhs might be not
            checkRhs(i->nameToken(), *i, NO_ALLOC, 0U, "");
            continue;
        }
        if (Token::Match(i->nameToken(), "%name% ) (") && Token::simpleMatch(i->nameToken()->linkAt(2), ") =")) { // Function pointer is initialized, but Rhs might be not
            checkRhs(i->nameToken()->linkAt(2)->next(), *i, NO_ALLOC, 0U, "");
            continue;
        }

        if (i->isArray() || i->isPointerToArray()) {
            const Token *tok = i->nameToken()->next();
            if (i->isPointerToArray())
                tok = tok->next();
            while (Token::simpleMatch(tok->link(), "] ["))
                tok = tok->link()->next();
            if (Token::Match(tok->link(), "] =|{"))
                continue;
        }

        bool stdtype = _tokenizer->isC();
        const Token* tok = i->typeStartToken();
        for (; tok != i->nameToken() && tok->str() != "<"; tok = tok->next()) {
            if (tok->isStandardType())
                stdtype = true;
        }
        if (i->isArray() && !stdtype)
            continue;

        while (tok && tok->str() != ";")
            tok = tok->next();
        if (!tok)
            continue;

        if (i->isArray()) {
            Alloc alloc = ARRAY;
            checkScopeForVariable(tok, *i, nullptr, nullptr, &alloc, "");
            continue;
        }
        if (stdtype || i->isPointer()) {
            Alloc alloc = NO_ALLOC;
            checkScopeForVariable(tok, *i, nullptr, nullptr, &alloc, "");
        }
        if (i->type())
            checkStruct(tok, *i);
    }

    if (scope->function) {
        for (unsigned int i = 0; i < scope->function->argCount(); i++) {
            const Variable *arg = scope->function->getArgumentVar(i);
            if (arg && arg->declarationId() && Token::Match(arg->typeStartToken(), "struct| %type% * %name% [,)]")) {
                // Treat the pointer as initialized until it is assigned by malloc
                for (const Token *tok = scope->classStart; tok != scope->classEnd; tok = tok->next()) {
                    if (Token::Match(tok, "[;{}] %varid% = %name% (", arg->declarationId()) &&
                        _settings->library.returnuninitdata.count(tok->strAt(3)) == 1U) {
                        if (arg->typeStartToken()->str() == "struct")
                            checkStruct(tok, *arg);
                        else if (arg->typeStartToken()->isStandardType()) {
                            Alloc alloc = NO_ALLOC;
                            checkScopeForVariable(tok->next(), *arg, nullptr, nullptr, &alloc, "");
                        }
                    }
                }
            }
        }
    }
}

void CheckUninitVar::checkStruct(const Token *tok, const Variable &structvar)
{
    const Token *typeToken = structvar.typeStartToken();
    if (typeToken->str() == "struct")
        typeToken = typeToken->next();
    const SymbolDatabase * symbolDatabase = _tokenizer->getSymbolDatabase();
    for (std::size_t j = 0U; j < symbolDatabase->classAndStructScopes.size(); ++j) {
        const Scope *scope2 = symbolDatabase->classAndStructScopes[j];
        if (scope2->className == typeToken->str() && scope2->numConstructors == 0U) {
            for (std::list<Variable>::const_iterator it = scope2->varlist.begin(); it != scope2->varlist.end(); ++it) {
                const Variable &var = *it;

                if (var.hasDefault() || var.isArray() || (!_tokenizer->isC() && var.isClass() && (!var.type() || var.type()->needInitialization != Type::True)))
                    continue;

                // is the variable declared in a inner union?
                bool innerunion = false;
                for (std::list<Scope>::const_iterator it2 = symbolDatabase->scopeList.begin(); it2 != symbolDatabase->scopeList.end(); ++it2) {
                    const Scope &innerScope = *it2;
                    if (innerScope.type == Scope::eUnion && innerScope.nestedIn == scope2) {
                        if (var.typeStartToken()->linenr() >= innerScope.classStart->linenr() &&
                            var.typeStartToken()->linenr() <= innerScope.classEnd->linenr()) {
                            innerunion = true;
                            break;
                        }

                    }
                }

                if (!innerunion) {
                    Alloc alloc = NO_ALLOC;
                    const Token *tok2 = tok;
                    if (tok->str() == "}")
                        tok2 = tok2->next();
                    checkScopeForVariable(tok2, structvar, nullptr, nullptr, &alloc, var.name());
                }
            }
        }
    }
}

static void conditionAlwaysTrueOrFalse(const Token *tok, const std::map<unsigned int, int> &variableValue, bool *alwaysTrue, bool *alwaysFalse)
{
    assert(Token::simpleMatch(tok, "if ("));

    const Token *vartok = tok->tokAt(2);
    const bool NOT(vartok->str() == "!");
    if (NOT)
        vartok = vartok->next();

    while (Token::Match(vartok, "%name% . %name%"))
        vartok = vartok->tokAt(2);

    std::map<unsigned int, int>::const_iterator it = variableValue.find(vartok->varId());
    if (it == variableValue.end())
        return;

    // always true
    if (Token::Match(vartok, "%name% %oror%|)")) {
        if (NOT)
            *alwaysTrue = bool(it->second == 0);
        else
            *alwaysTrue = bool(it->second != 0);
    } else if (Token::Match(vartok, "%name% == %num% %or%|)")) {
        *alwaysTrue = bool(it->second == MathLib::toLongNumber(vartok->strAt(2)));
    } else if (Token::Match(vartok, "%name% != %num% %or%|)")) {
        *alwaysTrue = bool(it->second != MathLib::toLongNumber(vartok->strAt(2)));
    }

    // always false
    if (Token::Match(vartok, "%name% &&|)")) {
        if (NOT)
            *alwaysFalse = bool(it->second != 0);
        else
            *alwaysFalse = bool(it->second == 0);
    } else if (Token::Match(vartok, "%name% == %num% &&|)")) {
        *alwaysFalse = bool(it->second != MathLib::toLongNumber(vartok->strAt(2)));
    } else if (Token::Match(vartok, "%name% != %num% &&|)")) {
        *alwaysFalse = bool(it->second == MathLib::toLongNumber(vartok->strAt(2)));
    }
}

static bool isVariableUsed(const Token *tok, const Variable& var)
{
    if (!tok)
        return false;
    if (tok->str() == "&" && !tok->astOperand2())
        return false;
    if (tok->isConstOp())
        return isVariableUsed(tok->astOperand1(),var) || isVariableUsed(tok->astOperand2(),var);
    if (tok->varId() != var.declarationId())
        return false;
    if (!var.isArray())
        return true;

    const Token *parent = tok->astParent();
    while (Token::Match(parent, "[?:]"))
        parent = parent->astParent();
    // no dereference, then array is not "used"
    if (!Token::Match(parent, "*|["))
        return false;
    const Token *parent2 = parent->astParent();
    // TODO: handle function calls. There is a TODO assertion in TestUninitVar::uninitvar_arrays
    return !parent2 || parent2->isConstOp() || (parent2->str() == "=" && parent2->astOperand2() == parent);
}

bool CheckUninitVar::checkScopeForVariable(const Token *tok, const Variable& var, bool * const possibleInit, bool * const noreturn, Alloc* const alloc, const std::string &membervar)
{
    const bool suppressErrors(possibleInit && *possibleInit);
    const bool printDebug = _settings->debugwarnings;

    if (possibleInit)
        *possibleInit = false;

    unsigned int number_of_if = 0;

    if (var.declarationId() == 0U)
        return true;

    // variable values
    std::map<unsigned int, int> variableValue;
    static const int NOT_ZERO = (1<<30); // special variable value

    for (; tok; tok = tok->next()) {
        // End of scope..
        if (tok->str() == "}") {
            if (number_of_if && possibleInit)
                *possibleInit = true;

            // might be a noreturn function..
            if (_tokenizer->IsScopeNoReturn(tok)) {
                if (noreturn)
                    *noreturn = true;
                return false;
            }

            break;
        }

        // Unconditional inner scope or try..
        if (tok->str() == "{" && Token::Match(tok->previous(), ";|{|}|try")) {
            if (checkScopeForVariable(tok->next(), var, possibleInit, noreturn, alloc, membervar))
                return true;
            tok = tok->link();
            continue;
        }

        // assignment with nonzero constant..
        if (Token::Match(tok->previous(), "[;{}] %var% = - %name% ;"))
            variableValue[tok->varId()] = NOT_ZERO;

        // Inner scope..
        else if (Token::simpleMatch(tok, "if (")) {
            bool alwaysTrue = false;
            bool alwaysFalse = false;

            conditionAlwaysTrueOrFalse(tok, variableValue, &alwaysTrue, &alwaysFalse);

            // initialization / usage in condition..
            if (!alwaysTrue && checkIfForWhileHead(tok->next(), var, suppressErrors, bool(number_of_if == 0), *alloc, membervar))
                return true;

            // checking if a not-zero variable is zero => bail out
            unsigned int condVarId = 0, condVarValue = 0;
            const Token *condVarTok = nullptr;
            if (Token::simpleMatch(tok, "if (") &&
                astIsVariableComparison(tok->next()->astOperand2(), "!=", "0", &condVarTok)) {
                std::map<unsigned int,int>::const_iterator it = variableValue.find(condVarTok->varId());
                if (it != variableValue.end() && it->second == NOT_ZERO)
                    return true;   // this scope is not fully analysed => return true
                else {
                    condVarId = condVarTok->varId();
                    condVarValue = NOT_ZERO;
                }
            }

            // goto the {
            tok = tok->next()->link()->next();

            if (!tok)
                break;
            if (tok->str() == "{") {
                bool possibleInitIf(number_of_if > 0 || suppressErrors);
                bool noreturnIf = false;
                const bool initif = !alwaysFalse && checkScopeForVariable(tok->next(), var, &possibleInitIf, &noreturnIf, alloc, membervar);

                // bail out for such code:
                //    if (a) x=0;    // conditional initialization
                //    if (b) return; // cppcheck doesn't know if b can be false when a is false.
                //    x++;           // it's possible x is always initialized
                if (!alwaysTrue && noreturnIf && number_of_if > 0) {
                    if (printDebug) {
                        std::string condition;
                        for (const Token *tok2 = tok->linkAt(-1); tok2 != tok; tok2 = tok2->next()) {
                            condition += tok2->str();
                            if (tok2->isName() && tok2->next()->isName())
                                condition += ' ';
                        }
                        reportError(tok, Severity::debug, "debug", "bailout uninitialized variable checking for '" + var.name() + "'. can't determine if this condition can be false when previous condition is false: " + condition);
                    }
                    return true;
                }

                if (alwaysTrue && noreturnIf)
                    return true;

                std::map<unsigned int, int> varValueIf;
                if (!alwaysFalse && !initif && !noreturnIf) {
                    for (const Token *tok2 = tok; tok2 && tok2 != tok->link(); tok2 = tok2->next()) {
                        if (Token::Match(tok2, "[;{}.] %name% = - %name% ;"))
                            varValueIf[tok2->next()->varId()] = NOT_ZERO;
                        else if (Token::Match(tok2, "[;{}.] %name% = %num% ;"))
                            varValueIf[tok2->next()->varId()] = (int)MathLib::toLongNumber(tok2->strAt(3));
                    }
                }

                if (initif && condVarId > 0U)
                    variableValue[condVarId] = condVarValue ^ NOT_ZERO;

                // goto the }
                tok = tok->link();

                if (!Token::simpleMatch(tok, "} else {")) {
                    if (initif || possibleInitIf) {
                        ++number_of_if;
                        if (number_of_if >= 2)
                            return true;
                    }
                } else {
                    // goto the {
                    tok = tok->tokAt(2);

                    bool possibleInitElse(number_of_if > 0 || suppressErrors);
                    bool noreturnElse = false;
                    const bool initelse = !alwaysTrue && checkScopeForVariable(tok->next(), var, &possibleInitElse, &noreturnElse, alloc, membervar);

                    std::map<unsigned int, int> varValueElse;
                    if (!alwaysTrue && !initelse && !noreturnElse) {
                        for (const Token *tok2 = tok; tok2 && tok2 != tok->link(); tok2 = tok2->next()) {
                            if (Token::Match(tok2, "[;{}.] %var% = - %name% ;"))
                                varValueElse[tok2->next()->varId()] = NOT_ZERO;
                            else if (Token::Match(tok2, "[;{}.] %var% = %num% ;"))
                                varValueElse[tok2->next()->varId()] = (int)MathLib::toLongNumber(tok2->strAt(3));
                        }
                    }

                    if (initelse && condVarId > 0U && !noreturnIf && !noreturnElse)
                        variableValue[condVarId] = condVarValue;

                    // goto the }
                    tok = tok->link();

                    if ((alwaysFalse || initif || noreturnIf) &&
                        (alwaysTrue || initelse || noreturnElse))
                        return true;

                    if (initif || initelse || possibleInitElse)
                        ++number_of_if;
                    if (!initif && !noreturnIf)
                        variableValue.insert(varValueIf.begin(), varValueIf.end());
                    if (!initelse && !noreturnElse)
                        variableValue.insert(varValueElse.begin(), varValueElse.end());
                }
            }
        }

        // = { .. }
        else if (Token::simpleMatch(tok, "= {")) {
            // end token
            const Token *end = tok->next()->link();

            // If address of variable is taken in the block then bail out
            if (Token::findmatch(tok->tokAt(2), "& %varid%", end, var.declarationId()))
                return true;

            // Skip block
            tok = end;
            continue;
        }

        // skip sizeof / offsetof
        if (Token::Match(tok, "sizeof|typeof|offsetof|decltype ("))
            tok = tok->next()->link();

        // for/while..
        else if (Token::Match(tok, "for|while (") || Token::simpleMatch(tok, "do {")) {
            const bool forwhile = Token::Match(tok, "for|while (");

            // is variable initialized in for-head (don't report errors yet)?
            if (forwhile && checkIfForWhileHead(tok->next(), var, true, false, *alloc, membervar))
                return true;

            // goto the {
            const Token *tok2 = forwhile ? tok->next()->link()->next() : tok->next();

            if (tok2 && tok2->str() == "{") {
                bool init = checkLoopBody(tok2, var, *alloc, membervar, (number_of_if > 0) || suppressErrors);

                // variable is initialized in the loop..
                if (init)
                    return true;

                // is variable used in for-head?
                bool initcond = false;
                if (!suppressErrors) {
                    const Token *startCond = forwhile ? tok->next() : tok->next()->link()->tokAt(2);
                    initcond = checkIfForWhileHead(startCond, var, false, bool(number_of_if == 0), *alloc, membervar);
                }

                // goto "}"
                tok = tok2->link();

                // do-while => goto ")"
                if (!forwhile) {
                    // Assert that the tokens are '} while ('
                    if (!Token::simpleMatch(tok, "} while (")) {
                        if (printDebug)
                            reportError(tok,Severity::debug,"","assertion failed '} while ('");
                        break;
                    }

                    // Goto ')'
                    tok = tok->linkAt(2);

                    if (!tok)
                        // bailout : invalid code / bad tokenizer
                        break;

                    if (initcond)
                        // variable is initialized in while-condition
                        return true;
                }
            }
        }

        // Unknown or unhandled inner scope
        else if (Token::simpleMatch(tok, ") {") || (Token::Match(tok, "%name% {") && tok->str() != "try")) {
            if (tok->str() == "struct" || tok->str() == "union") {
                tok = tok->linkAt(1);
                continue;
            }
            return true;
        }

        // bailout if there is ({
        if (Token::simpleMatch(tok, "( {")) {
            return true;
        }

        // bailout if there is assembler code or setjmp
        if (Token::Match(tok, "asm|setjmp (")) {
            return true;
        }

        // bailout if there is a goto label
        if (Token::Match(tok, "[;{}] %name% :")) {
            return true;
        }

        if (tok->str() == "?") {
            if (!tok->astOperand2())
                return true;
            const bool used1 = isVariableUsed(tok->astOperand2()->astOperand1(), var);
            const bool used0 = isVariableUsed(tok->astOperand2()->astOperand2(), var);
            const bool err = (number_of_if == 0) ? (used1 || used0) : (used1 && used0);
            if (err)
                uninitvarError(tok, var.nameToken()->str(), *alloc);

            // Todo: skip expression if there is no error
            return true;
        }

        if (Token::Match(tok, "return|break|continue|throw|goto")) {
            if (noreturn)
                *noreturn = true;

            tok = tok->next();
            while (tok && tok->str() != ";") {
                // variable is seen..
                if (tok->varId() == var.declarationId()) {
                    if (!membervar.empty()) {
                        if (Token::Match(tok, "%name% . %name% ;|%cop%") && tok->strAt(2) == membervar)
                            uninitStructMemberError(tok, tok->str() + "." + membervar);
                        else
                            return true;
                    }

                    // Use variable
                    else if (!suppressErrors && isVariableUsage(tok, var.isPointer(), *alloc))
                        uninitvarError(tok, tok->str(), *alloc);

                    else
                        // assume that variable is assigned
                        return true;
                }

                else if (Token::Match(tok, "sizeof|typeof|offsetof|decltype ("))
                    tok = tok->linkAt(1);

                else if (tok->str() == "?") {
                    if (!tok->astOperand2())
                        return true;
                    const bool used1 = isVariableUsed(tok->astOperand2()->astOperand1(), var);
                    const bool used0 = isVariableUsed(tok->astOperand2()->astOperand2(), var);
                    const bool err = (number_of_if == 0) ? (used1 || used0) : (used1 && used0);
                    if (err)
                        uninitvarError(tok, var.nameToken()->str(), *alloc);
                    return true;
                }

                tok = tok->next();
            }

            return bool(noreturn==nullptr);
        }

        // variable is seen..
        if (tok->varId() == var.declarationId()) {
            // calling function that returns uninit data through pointer..
            if (var.isPointer() &&
                Token::Match(tok->next(), "= %name% (") &&
                Token::simpleMatch(tok->linkAt(3), ") ;") &&
                _settings->library.returnuninitdata.count(tok->strAt(2)) > 0U) {
                *alloc = NO_CTOR_CALL;
                continue;
            }
            if (var.isPointer() && (var.typeStartToken()->isStandardType() || (var.type() && var.type()->needInitialization == Type::True)) && Token::simpleMatch(tok->next(), "= new")) {
                *alloc = CTOR_CALL;
                if (var.typeScope() && var.typeScope()->numConstructors > 0)
                    return true;
                continue;
            }

            if (!membervar.empty()) {
                if (isMemberVariableAssignment(tok, membervar)) {
                    checkRhs(tok, var, *alloc, number_of_if, membervar);
                    return true;
                }

                if (isMemberVariableUsage(tok, var.isPointer(), *alloc, membervar))
                    uninitStructMemberError(tok, tok->str() + "." + membervar);

                else if (Token::Match(tok->previous(), "[(,] %name% [,)]"))
                    return true;

            } else {
                // Use variable
                if (!suppressErrors && isVariableUsage(tok, var.isPointer(), *alloc))
                    uninitvarError(tok, tok->str(), *alloc);

                else {
                    if (tok->strAt(1) == "=")
                        checkRhs(tok, var, *alloc, number_of_if, "");

                    // assume that variable is assigned
                    return true;
                }
            }
        }
    }

    return false;
}

bool CheckUninitVar::checkIfForWhileHead(const Token *startparentheses, const Variable& var, bool suppressErrors, bool isuninit, Alloc alloc, const std::string &membervar)
{
    const Token * const endpar = startparentheses->link();
    if (Token::Match(startparentheses, "( ! %name% %oror%") && startparentheses->tokAt(2)->getValue(0))
        suppressErrors = true;
    for (const Token *tok = startparentheses->next(); tok && tok != endpar; tok = tok->next()) {
        if (tok->varId() == var.declarationId()) {
            if (Token::Match(tok, "%name% . %name%")) {
                if (tok->strAt(2) == membervar) {
                    if (isMemberVariableAssignment(tok, membervar))
                        return true;

                    if (!suppressErrors && isMemberVariableUsage(tok, var.isPointer(), alloc, membervar))
                        uninitStructMemberError(tok, tok->str() + "." + membervar);
                }
                continue;
            }

            if (isVariableUsage(tok, var.isPointer(), alloc)) {
                if (suppressErrors)
                    continue;
                uninitvarError(tok, tok->str(), alloc);
            }
            return true;
        }
        if (Token::Match(tok, "sizeof|decltype|offsetof ("))
            tok = tok->next()->link();
        if ((!isuninit || !membervar.empty()) && tok->str() == "&&")
            suppressErrors = true;
    }
    return false;
}

bool CheckUninitVar::checkLoopBody(const Token *tok, const Variable& var, const Alloc alloc, const std::string &membervar, const bool suppressErrors)
{
    const Token *usetok = nullptr;

    assert(tok->str() == "{");

    for (const Token * const end = tok->link(); tok != end; tok = tok->next()) {
        if (tok->varId() == var.declarationId()) {
            if (!membervar.empty()) {
                if (isMemberVariableAssignment(tok, membervar)) {
                    bool assign = true;
                    bool rhs = false;
                    for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) {
                        if (tok2->str() == "=")
                            rhs = true;
                        if (tok2->str() == ";")
                            break;
                        if (rhs && tok2->varId() == var.declarationId() && isMemberVariableUsage(tok2, var.isPointer(), alloc, membervar)) {
                            assign = false;
                            break;
                        }
                    }
                    if (assign)
                        return true;
                }

                if (Token::Match(tok, "%name% ="))
                    return true;

                if (isMemberVariableUsage(tok, var.isPointer(), alloc, membervar))
                    usetok = tok;
                else if (Token::Match(tok->previous(), "[(,] %name% [,)]"))
                    return true;
            } else {
                if (isVariableUsage(tok, var.isPointer(), alloc))
                    usetok = tok;
                else if (tok->strAt(1) == "=") {
                    // Is var used in rhs?
                    bool rhs = false;
                    std::stack<const Token *> tokens;
                    tokens.push(tok->next()->astOperand2());
                    while (!tokens.empty()) {
                        const Token *t = tokens.top();
                        tokens.pop();
                        if (!t)
                            continue;
                        if (t->varId() == var.declarationId()) {
                            // var is used in rhs
                            rhs = true;
                            break;
                        }
                        if (Token::simpleMatch(t->previous(),"sizeof ("))
                            continue;
                        tokens.push(t->astOperand1());
                        tokens.push(t->astOperand2());
                    }
                    if (!rhs)
                        return true;
                } else {
                    return true;
                }
            }
        }

        if (Token::Match(tok, "sizeof|typeof ("))
            tok = tok->next()->link();

        if (Token::Match(tok, "asm ( %str% ) ;"))
            return true;
    }

    if (!suppressErrors && usetok) {
        if (membervar.empty())
            uninitvarError(usetok, usetok->str(), alloc);
        else
            uninitStructMemberError(usetok, usetok->str() + "." + membervar);
        return true;
    }

    return false;
}

void CheckUninitVar::checkRhs(const Token *tok, const Variable &var, Alloc alloc, unsigned int number_of_if, const std::string &membervar)
{
    bool rhs = false;
    unsigned int indent = 0;
    while (nullptr != (tok = tok->next())) {
        if (tok->str() == "=")
            rhs = true;
        else if (rhs && tok->varId() == var.declarationId()) {
            if (membervar.empty() && isVariableUsage(tok, var.isPointer(), alloc))
                uninitvarError(tok, tok->str(), alloc);
            else if (!membervar.empty() && isMemberVariableUsage(tok, var.isPointer(), alloc, membervar))
                uninitStructMemberError(tok, tok->str() + "." + membervar);

        } else if (tok->str() == ";" || (indent==0 && tok->str() == ","))
            break;
        else if (tok->str() == "(")
            ++indent;
        else if (tok->str() == ")") {
            if (indent == 0)
                break;
            --indent;
        } else if (tok->str() == "?" && tok->astOperand2()) {
            const bool used1 = isVariableUsed(tok->astOperand2()->astOperand1(), var);
            const bool used0 = isVariableUsed(tok->astOperand2()->astOperand2(), var);
            const bool err = (number_of_if == 0) ? (used1 || used0) : (used1 && used0);
            if (err)
                uninitvarError(tok, var.nameToken()->str(), alloc);
            break;
        } else if (Token::simpleMatch(tok, "sizeof ("))
            tok = tok->next()->link();
    }
}

bool CheckUninitVar::isVariableUsage(const Token *vartok, bool pointer, Alloc alloc) const
{
    if (alloc == NO_ALLOC && ((Token::Match(vartok->previous(), "return|delete") && vartok->strAt(1) != "=") || (vartok->strAt(-1) == "]" && vartok->linkAt(-1)->strAt(-1) == "delete")))
        return true;

    // Passing variable to typeof/__alignof__
    if (Token::Match(vartok->tokAt(-3), "typeof|__alignof__ ( * %name%"))
        return false;

    // Accessing Rvalue member using "." or "->"
    if (vartok->strAt(1) == "." && vartok->strAt(-1) != "&") {
        // Is struct member passed to function?
        if (!pointer && Token::Match(vartok->previous(), "[,(] %name% . %name%")) {
            // TODO: there are FN currently:
            // - should only return false if struct member is (or might be) array.
            // - should only return false if function argument is (or might be) non-const pointer or reference
            const Token *tok2 = vartok->next();
            do {
                tok2 = tok2->tokAt(2);
            } while (Token::Match(tok2, ". %name%"));
            if (Token::Match(tok2, "[,)]"))
                return false;
        } else if (pointer && alloc != CTOR_CALL && Token::Match(vartok, "%name% . %name% (")) {
            return true;
        }

        bool assignment = false;
        const Token* parent = vartok->astParent();
        while (parent) {
            if (parent->str() == "=") {
                assignment = true;
                break;
            }
            if (alloc != NO_ALLOC && parent->str() == "(") {
                if (_settings->library.functionpure.find(parent->strAt(-1)) == _settings->library.functionpure.end()) {
                    assignment = true;
                    break;
                }
            }
            parent = parent->astParent();
        }
        if (!assignment)
            return true;
    }

    // Passing variable to function..
    if (Token::Match(vartok->previous(), "[(,] %name% [,)]") || Token::Match(vartok->tokAt(-2), "[(,] & %name% [,)]")) {
        const int use = isFunctionParUsage(vartok, pointer, alloc);
        if (use >= 0)
            return (use>0);
    }

    if (Token::Match(vartok->previous(), "++|--|%cop%")) {
        if (_tokenizer->isCPP() && alloc == ARRAY && Token::Match(vartok->tokAt(-4), "& %var% =|( *"))
            return false;

        if (_tokenizer->isCPP() && Token::Match(vartok->previous(), ">>|<<")) {
            const Token* tok2 = vartok->previous();
            if (Token::simpleMatch(tok2->astOperand1(), ">>"))
                return false; // Looks like stream operator, initializes the variable
            if (Token::simpleMatch(tok2, "<<")) {
                // Looks like stream operator, but could also initialize the variable. Check lhs.
                do {
                    tok2 = tok2->astOperand1();
                } while (Token::simpleMatch(tok2, "<<"));
                if (tok2 && tok2->strAt(-1) == "::")
                    tok2 = tok2->previous();
                if (tok2 && (Token::simpleMatch(tok2->previous(), "std ::") || (tok2->variable() && tok2->variable()->isStlType()) || tok2->isStandardType()))
                    return true;
            }
            const Variable *var = vartok->tokAt(-2)->variable();
            return (var && var->typeStartToken()->isStandardType());
        }

        // is there something like: ; "*((&var ..expr.. ="  => the variable is assigned
        if (vartok->previous()->str() == "&" && !vartok->previous()->astOperand2())
            return false;

        // bailout to avoid fp for 'int x = 2 + x();' where 'x()' is a unseen preprocessor macro (seen in linux)
        if (!pointer && vartok->next() && vartok->next()->str() == "(")
            return false;

        if (vartok->previous()->str() != "&" || !Token::Match(vartok->tokAt(-2), "[(,=?:]")) {
            if (alloc != NO_ALLOC && vartok->previous()->str() == "*") {
                const Token *parent = vartok->previous()->astParent();
                if (parent && parent->str() == "=" && parent->astOperand1() == vartok->previous())
                    return false;
                return true;
            }
            return alloc == NO_ALLOC;
        }
    }

    if (alloc == NO_ALLOC && Token::Match(vartok->previous(), "= %name% ;|%cop%")) {
        // taking reference?
        const Token *prev = vartok->tokAt(-2);
        while (Token::Match(prev, "%name%|*"))
            prev = prev->previous();
        if (!Token::simpleMatch(prev, "&"))
            return true;
    }

    bool unknown = false;
    if (pointer && alloc == NO_ALLOC && CheckNullPointer::isPointerDeRef(vartok, unknown)) {
        // function parameter?
        bool functionParameter = false;
        if (Token::Match(vartok->tokAt(-2), "%name% (") || vartok->previous()->str() == ",")
            functionParameter = true;

        // if this is not a function parameter report this dereference as variable usage
        if (!functionParameter)
            return true;
    } else if (alloc != NO_ALLOC && Token::Match(vartok, "%var% [")) {
        const Token *parent = vartok->next()->astParent();
        while (Token::Match(parent, "[|."))
            parent = parent->astParent();
        if (Token::simpleMatch(parent, "&") && !parent->astOperand2())
            return false;
        if (parent && Token::Match(parent->previous(), "if|while|switch ("))
            return true;
        if (Token::Match(parent, "[=,(]"))
            return false;
        return true;
    }

    if (_tokenizer->isCPP() && Token::Match(vartok->next(), "<<|>>")) {
        // Is this calculation done in rhs?
        const Token *tok = vartok;
        while (tok && Token::Match(tok, "%name%|.|::"))
            tok = tok->previous();
        if (Token::Match(tok, "[;{}]"))
            return false;

        // Is variable a known POD type then this is a variable usage,
        // otherwise we assume it's not.
        const Variable *var = vartok->variable();
        return (var && var->typeStartToken()->isStandardType());
    }

    if (alloc == NO_ALLOC && vartok->next() && vartok->next()->isOp() && !vartok->next()->isAssignmentOp())
        return true;

    if (vartok->strAt(1) == "]")
        return true;

    return false;
}

/***
 * Is function parameter "used" so a "usage of uninitialized variable" can
 * be written? If parameter is passed "by value" then it is "used". If it
 * is passed "by reference" then it is not necessarily "used".
 * @return  -1 => unknown   0 => not used   1 => used
 */
int CheckUninitVar::isFunctionParUsage(const Token *vartok, bool pointer, Alloc alloc) const
{
    if (!Token::Match(vartok->previous(), "[(,]") && !Token::Match(vartok->tokAt(-2), "[(,] &"))
        return -1;

    // locate start parentheses in function call..
    unsigned int argumentNumber = 0;
    const Token *start = vartok;
    while (start && !Token::Match(start, "[;{}(]")) {
        if (start->str() == ")")
            start = start->link();
        else if (start->str() == ",")
            ++argumentNumber;
        start = start->previous();
    }

    // is this a function call?
    if (start && Token::Match(start->previous(), "%name% (")) {
        const bool address(vartok->previous()->str() == "&");
        const bool array(vartok->variable() && vartok->variable()->isArray());
        // check how function handle uninitialized data arguments..
        const Function *func = start->previous()->function();
        if (func) {
            const Variable *arg = func->getArgumentVar(argumentNumber);
            if (arg) {
                const Token *argStart = arg->typeStartToken();
                if (!address && !array && Token::Match(argStart, "struct| %type% %name%| [,)]"))
                    return 1;
                if (pointer && !address && alloc == NO_ALLOC && Token::Match(argStart, "struct| %type% * %name% [,)]"))
                    return 1;
                while (argStart->previous() && argStart->previous()->isName())
                    argStart = argStart->previous();
                if (Token::Match(argStart, "const %type% & %name% [,)]"))
                    return 1;
                if ((pointer || address) && alloc == NO_ALLOC && Token::Match(argStart, "const struct| %type% * %name% [,)]"))
                    return 1;
                if ((pointer || address) && Token::Match(argStart, "const %type% %name% [") && Token::Match(argStart->linkAt(3), "] [,)]"))
                    return 1;
            }

        } else if (Token::Match(start->previous(), "if|while|for")) {
            // control-flow statement reading the variable "by value"
            return alloc == NO_ALLOC;
        } else {
            const bool isnullbad = _settings->library.isnullargbad(start->previous(), argumentNumber + 1);
            if (pointer && !address && isnullbad && alloc == NO_ALLOC)
                return true;
            const bool isuninitbad = _settings->library.isuninitargbad(start->previous(), argumentNumber + 1);
            if (alloc != NO_ALLOC)
                return isnullbad && isuninitbad;
            return isuninitbad && (!address || isnullbad);
        }
    }

    // unknown
    return -1;
}

bool CheckUninitVar::isMemberVariableAssignment(const Token *tok, const std::string &membervar) const
{
    if (Token::Match(tok, "%name% . %name%") && tok->strAt(2) == membervar) {
        if (Token::Match(tok->tokAt(3), "[=.[]"))
            return true;
        else if (Token::Match(tok->tokAt(-2), "[(,=] &"))
            return true;
        else if (Token::Match(tok->tokAt(-2), "%name% >>") && Token::Match(tok->tokAt(3), ";|>>")) // #6680
            return true;
        else if ((tok->previous() && tok->previous()->isConstOp()) || Token::Match(tok->previous(), "[|="))
            ; // member variable usage
        else if (tok->tokAt(3)->isConstOp())
            ; // member variable usage
        else if (Token::Match(tok->previous(), "[(,] %name% . %name% [,)]") &&
                 1 == isFunctionParUsage(tok, false, NO_ALLOC)) {
            return false;
        } else
            return true;
    } else if (tok->strAt(1) == "=")
        return true;
    else if (tok->strAt(-1) == "&") {
        if (Token::Match(tok->tokAt(-2), "[(,] & %name%")) {
            // locate start parentheses in function call..
            unsigned int argumentNumber = 0;
            const Token *ftok = tok;
            while (ftok && !Token::Match(ftok, "[;{}(]")) {
                if (ftok->str() == ")")
                    ftok = ftok->link();
                else if (ftok->str() == ",")
                    ++argumentNumber;
                ftok = ftok->previous();
            }

            // is this a function call?
            ftok = ftok ? ftok->previous() : NULL;
            if (Token::Match(ftok, "%name% (")) {
                // check how function handle uninitialized data arguments..
                const Function *function = ftok->function();
                const Variable *arg      = function ? function->getArgumentVar(argumentNumber) : NULL;
                const Token *argStart    = arg ? arg->typeStartToken() : NULL;
                while (argStart && argStart->previous() && argStart->previous()->isName())
                    argStart = argStart->previous();
                if (Token::Match(argStart, "const struct| %type% * const| %name% [,)]"))
                    return false;
            }

            else if (ftok && Token::simpleMatch(ftok->previous(), "= * ("))
                return false;
        }
        return true;
    }
    return false;
}

bool CheckUninitVar::isMemberVariableUsage(const Token *tok, bool isPointer, Alloc alloc, const std::string &membervar) const
{
    if (Token::Match(tok->previous(), "[(,] %name% . %name% [,)]") &&
        tok->strAt(2) == membervar) {
        int use = isFunctionParUsage(tok, isPointer, alloc);
        if (use == 1)
            return true;
    }

    if (isMemberVariableAssignment(tok, membervar))
        return false;

    if (Token::Match(tok, "%name% . %name%") && tok->strAt(2) == membervar && !(tok->tokAt(-2)->variable() && tok->tokAt(-2)->variable()->isReference()))
        return true;
    else if (!isPointer && Token::Match(tok->previous(), "[(,] %name% [,)]") && isVariableUsage(tok, isPointer, alloc))
        return true;

    else if (!isPointer && Token::Match(tok->previous(), "= %name% ;"))
        return true;

    // = *(&var);
    else if (!isPointer &&
             Token::simpleMatch(tok->astParent(),"&") &&
             Token::simpleMatch(tok->astParent()->astParent(),"*") &&
             Token::Match(tok->astParent()->astParent()->astParent(), "= * (| &") &&
             tok->astParent()->astParent()->astParent()->astOperand2() == tok->astParent()->astParent())
        return true;

    else if (_settings->experimental &&
             !isPointer &&
             Token::Match(tok->tokAt(-2), "[(,] & %name% [,)]") &&
             isVariableUsage(tok, isPointer, alloc))
        return true;

    return false;
}

void CheckUninitVar::uninitstringError(const Token *tok, const std::string &varname, bool strncpy_)
{
    reportError(tok, Severity::error, "uninitstring", "Dangerous usage of '" + varname + "'" + (strncpy_ ? " (strncpy doesn't always null-terminate it)." : " (not null-terminated)."));
}

void CheckUninitVar::uninitdataError(const Token *tok, const std::string &varname)
{
    reportError(tok, Severity::error, "uninitdata", "Memory is allocated but not initialized: " + varname);
}

void CheckUninitVar::uninitvarError(const Token *tok, const std::string &varname)
{
    reportError(tok, Severity::error, "uninitvar", "Uninitialized variable: " + varname);
}

void CheckUninitVar::uninitStructMemberError(const Token *tok, const std::string &membername)
{
    reportError(tok,
                Severity::error,
                "uninitStructMember",
                "Uninitialized struct member: " + membername);
}

void CheckUninitVar::deadPointer()
{
    const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase();
    std::list<Scope>::const_iterator scope;

    // check every executable scope
    for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) {
        if (!scope->isExecutable())
            continue;
        // Dead pointers..
        for (const Token* tok = scope->classStart; tok != scope->classEnd; tok = tok->next()) {
            if (tok->variable() &&
                tok->variable()->isPointer() &&
                isVariableUsage(tok, true, NO_ALLOC)) {
                const Token *alias = tok->getValueTokenDeadPointer();
                if (alias) {
                    deadPointerError(tok,alias);
                }
            }
        }
    }
}

void CheckUninitVar::deadPointerError(const Token *pointer, const Token *alias)
{
    const std::string strpointer(pointer ? pointer->str() : std::string("pointer"));
    const std::string stralias(alias ? alias->expressionString() : std::string("&x"));

    reportError(pointer,
                Severity::error,
                "deadpointer",
                "Dead pointer usage. Pointer '" + strpointer + "' is dead if it has been assigned '" + stralias + "' at line " + MathLib::toString(alias ? alias->linenr() : 0U) + ".");
}


text:
using Implem.DefinitionAccessor;
using System.Collections.Generic;
using System.Linq;
namespace Implem.CodeDefiner.Functions.AspNetMvc.CSharp.Parts
{
    internal static class BaseItemModel
    {
        internal static void SetCodeCollection(
            CodeDefinition codeDefinition,
            List<string> codeCollection,
            DataContainer dataContainer)
        {
            var code = string.Empty;
            Def.BaseItemColumnDefinitionCollection(order: codeDefinition.Order)
                .Where(o => Column.CheckExclude(codeDefinition, o) == false)
                .Where(o => !o.EachModel)
                .ForEach(columnDefinition =>
                {
                    dataContainer.TableName = "_BaseItems";
                    dataContainer.ColumnName = columnDefinition.ColumnName;
                    Creators.SetCodeCollection(
                        ref code,
                        codeCollection,
                        codeDefinition,
                        dataContainer,
                        () => Column.ReplaceCode(
                            ref code,
                            codeDefinition,
                            columnDefinition));
                    dataContainer.TableName = string.Empty;
                    dataContainer.ColumnName = string.Empty;
                });
        }
    }
}


text:
using Plugin.Connectivity;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

[assembly: XamlCompilationAttribute(XamlCompilationOptions.Compile)]

namespace eXam
{
    public class App : Application
    {
        public static Game CurrentGame { get; private set; }

        public App()
        {
            // The root page of your application
            MainPage = new NavigationPage ( new HomePage() );
        }

        protected override async void OnStart()
        {
            var fileHelper = DependencyService.Get<IFileHelper>();

            var questionsText = await fileHelper.LoadLocalFileAsync("cachedquestions.xml");

            if (string.IsNullOrWhiteSpace(questionsText))
            {
                var assembly = typeof(App).GetTypeInfo().Assembly;

                using (var stream = assembly.GetManifestResourceStream("eXam.Data.questions.xml"))
                {
                    questionsText = new StreamReader(stream).ReadToEnd();
                }

                await fileHelper.SaveLocalFileAsync("cachedquestions.xml", questionsText);
            }

            var questions = QuizQuestionXmlSerializer.Deserialize(questionsText);
            CurrentGame = new Game(questions);

            if (CrossConnectivity.Current.IsConnected)
                Debug.WriteLine("Connected");
            else
                Debug.WriteLine("Not connected");
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}


text:
.documentationPanel {
    width: 100%;
    min-width: 800px;
    overflow: auto;
}

.printButton {
    float: right;
    width: 120px;
    vertical-align: middle;
}

.documentationContent {
    width: 80%;
    max-width: 1920px;
    margin-left: auto;
    margin-right: auto;
    display: block;
}


text:
module Ebay # :nodoc:
  module Types # :nodoc:
    class GiftIconCode
      extend Enumerable
      extend Enumeration
      Enabled = 'Enabled'
      Disabled = 'Disabled'
    end
  end
end