text:
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).

#ifndef ROCKSDB_LITE

#include "utilities/transactions/pessimistic_transaction.h"

#include <map>
#include <set>
#include <string>
#include <vector>

#include "db/column_family.h"
#include "db/db_impl/db_impl.h"
#include "rocksdb/comparator.h"
#include "rocksdb/db.h"
#include "rocksdb/snapshot.h"
#include "rocksdb/status.h"
#include "rocksdb/utilities/transaction_db.h"
#include "test_util/sync_point.h"
#include "util/cast_util.h"
#include "util/string_util.h"
#include "utilities/transactions/pessimistic_transaction_db.h"
#include "utilities/transactions/transaction_util.h"

namespace ROCKSDB_NAMESPACE {

struct WriteOptions;

std::atomic<TransactionID> PessimisticTransaction::txn_id_counter_(1);

TransactionID PessimisticTransaction::GenTxnID() {
  return txn_id_counter_.fetch_add(1);
}

PessimisticTransaction::PessimisticTransaction(
    TransactionDB* txn_db, const WriteOptions& write_options,
    const TransactionOptions& txn_options, const bool init)
    : TransactionBaseImpl(txn_db->GetRootDB(), write_options),
      txn_db_impl_(nullptr),
      expiration_time_(0),
      txn_id_(0),
      waiting_cf_id_(0),
      waiting_key_(nullptr),
      lock_timeout_(0),
      deadlock_detect_(false),
      deadlock_detect_depth_(0),
      skip_concurrency_control_(false) {
  txn_db_impl_ =
      static_cast_with_check<PessimisticTransactionDB, TransactionDB>(txn_db);
  db_impl_ = static_cast_with_check<DBImpl, DB>(db_);
  if (init) {
    Initialize(txn_options);
  }
}

void PessimisticTransaction::Initialize(const TransactionOptions& txn_options) {
  txn_id_ = GenTxnID();

  txn_state_ = STARTED;

  deadlock_detect_ = txn_options.deadlock_detect;
  deadlock_detect_depth_ = txn_options.deadlock_detect_depth;
  write_batch_.SetMaxBytes(txn_options.max_write_batch_size);
  skip_concurrency_control_ = txn_options.skip_concurrency_control;

  lock_timeout_ = txn_options.lock_timeout * 1000;
  if (lock_timeout_ < 0) {
    // Lock timeout not set, use default
    lock_timeout_ =
        txn_db_impl_->GetTxnDBOptions().transaction_lock_timeout * 1000;
  }

  if (txn_options.expiration >= 0) {
    expiration_time_ = start_time_ + txn_options.expiration * 1000;
  } else {
    expiration_time_ = 0;
  }

  if (txn_options.set_snapshot) {
    SetSnapshot();
  }

  if (expiration_time_ > 0) {
    txn_db_impl_->InsertExpirableTransaction(txn_id_, this);
  }
  use_only_the_last_commit_time_batch_for_recovery_ =
      txn_options.use_only_the_last_commit_time_batch_for_recovery;
}

PessimisticTransaction::~PessimisticTransaction() {
  txn_db_impl_->UnLock(this, &GetTrackedKeys());
  if (expiration_time_ > 0) {
    txn_db_impl_->RemoveExpirableTransaction(txn_id_);
  }
  if (!name_.empty() && txn_state_ != COMMITTED) {
    txn_db_impl_->UnregisterTransaction(this);
  }
}

void PessimisticTransaction::Clear() {
  txn_db_impl_->UnLock(this, &GetTrackedKeys());
  TransactionBaseImpl::Clear();
}

void PessimisticTransaction::Reinitialize(
    TransactionDB* txn_db, const WriteOptions& write_options,
    const TransactionOptions& txn_options) {
  if (!name_.empty() && txn_state_ != COMMITTED) {
    txn_db_impl_->UnregisterTransaction(this);
  }
  TransactionBaseImpl::Reinitialize(txn_db->GetRootDB(), write_options);
  Initialize(txn_options);
}

bool PessimisticTransaction::IsExpired() const {
  if (expiration_time_ > 0) {
    if (db_->GetEnv()->NowMicros() >= expiration_time_) {
      // Transaction is expired.
      return true;
    }
  }

  return false;
}

WriteCommittedTxn::WriteCommittedTxn(TransactionDB* txn_db,
                                     const WriteOptions& write_options,
                                     const TransactionOptions& txn_options)
    : PessimisticTransaction(txn_db, write_options, txn_options){};

Status PessimisticTransaction::CommitBatch(WriteBatch* batch) {
  TransactionKeyMap keys_to_unlock;
  Status s = LockBatch(batch, &keys_to_unlock);

  if (!s.ok()) {
    return s;
  }

  bool can_commit = false;

  if (IsExpired()) {
    s = Status::Expired();
  } else if (expiration_time_ > 0) {
    TransactionState expected = STARTED;
    can_commit = std::atomic_compare_exchange_strong(&txn_state_, &expected,
                                                     AWAITING_COMMIT);
  } else if (txn_state_ == STARTED) {
    // lock stealing is not a concern
    can_commit = true;
  }

  if (can_commit) {
    txn_state_.store(AWAITING_COMMIT);
    s = CommitBatchInternal(batch);
    if (s.ok()) {
      txn_state_.store(COMMITTED);
    }
  } else if (txn_state_ == LOCKS_STOLEN) {
    s = Status::Expired();
  } else {
    s = Status::InvalidArgument("Transaction is not in state for commit.");
  }

  txn_db_impl_->UnLock(this, &keys_to_unlock);

  return s;
}

Status PessimisticTransaction::Prepare() {
  Status s;

  if (name_.empty()) {
    return Status::InvalidArgument(
        "Cannot prepare a transaction that has not been named.");
  }

  if (IsExpired()) {
    return Status::Expired();
  }

  bool can_prepare = false;

  if (expiration_time_ > 0) {
    // must concern ourselves with expiraton and/or lock stealing
    // need to compare/exchange bc locks could be stolen under us here
    TransactionState expected = STARTED;
    can_prepare = std::atomic_compare_exchange_strong(&txn_state_, &expected,
                                                      AWAITING_PREPARE);
  } else if (txn_state_ == STARTED) {
    // expiration and lock stealing is not possible
    can_prepare = true;
  }

  if (can_prepare) {
    txn_state_.store(AWAITING_PREPARE);
    // transaction can't expire after preparation
    expiration_time_ = 0;
    assert(log_number_ == 0 ||
           txn_db_impl_->GetTxnDBOptions().write_policy == WRITE_UNPREPARED);

    s = PrepareInternal();
    if (s.ok()) {
      txn_state_.store(PREPARED);
    }
  } else if (txn_state_ == LOCKS_STOLEN) {
    s = Status::Expired();
  } else if (txn_state_ == PREPARED) {
    s = Status::InvalidArgument("Transaction has already been prepared.");
  } else if (txn_state_ == COMMITTED) {
    s = Status::InvalidArgument("Transaction has already been committed.");
  } else if (txn_state_ == ROLLEDBACK) {
    s = Status::InvalidArgument("Transaction has already been rolledback.");
  } else {
    s = Status::InvalidArgument("Transaction is not in state for commit.");
  }

  return s;
}

Status WriteCommittedTxn::PrepareInternal() {
  WriteOptions write_options = write_options_;
  write_options.disableWAL = false;
  WriteBatchInternal::MarkEndPrepare(GetWriteBatch()->GetWriteBatch(), name_);
  class MarkLogCallback : public PreReleaseCallback {
   public:
    MarkLogCallback(DBImpl* db, bool two_write_queues)
        : db_(db), two_write_queues_(two_write_queues) {
      (void)two_write_queues_;  // to silence unused private field warning
    }
    virtual Status Callback(SequenceNumber, bool is_mem_disabled,
                            uint64_t log_number, size_t /*index*/,
                            size_t /*total*/) override {
#ifdef NDEBUG
      (void)is_mem_disabled;
#endif
      assert(log_number != 0);
      assert(!two_write_queues_ || is_mem_disabled);  // implies the 2nd queue
      db_->logs_with_prep_tracker()->MarkLogAsContainingPrepSection(log_number);
      return Status::OK();
    }

   private:
    DBImpl* db_;
    bool two_write_queues_;
  } mark_log_callback(db_impl_,
                      db_impl_->immutable_db_options().two_write_queues);

  WriteCallback* const kNoWriteCallback = nullptr;
  const uint64_t kRefNoLog = 0;
  const bool kDisableMemtable = true;
  SequenceNumber* const KIgnoreSeqUsed = nullptr;
  const size_t kNoBatchCount = 0;
  Status s = db_impl_->WriteImpl(
      write_options, GetWriteBatch()->GetWriteBatch(), kNoWriteCallback,
      &log_number_, kRefNoLog, kDisableMemtable, KIgnoreSeqUsed, kNoBatchCount,
      &mark_log_callback);
  return s;
}

Status PessimisticTransaction::Commit() {
  Status s;
  bool commit_without_prepare = false;
  bool commit_prepared = false;

  if (IsExpired()) {
    return Status::Expired();
  }

  if (expiration_time_ > 0) {
    // we must atomicaly compare and exchange the state here because at
    // this state in the transaction it is possible for another thread
    // to change our state out from under us in the even that we expire and have
    // our locks stolen. In this case the only valid state is STARTED because
    // a state of PREPARED would have a cleared expiration_time_.
    TransactionState expected = STARTED;
    commit_without_prepare = std::atomic_compare_exchange_strong(
        &txn_state_, &expected, AWAITING_COMMIT);
    TEST_SYNC_POINT("TransactionTest::ExpirableTransactionDataRace:1");
  } else if (txn_state_ == PREPARED) {
    // expiration and lock stealing is not a concern
    commit_prepared = true;
  } else if (txn_state_ == STARTED) {
    // expiration and lock stealing is not a concern
    commit_without_prepare = true;
    // TODO(myabandeh): what if the user mistakenly forgets prepare? We should
    // add an option so that the user explictly express the intention of
    // skipping the prepare phase.
  }

  if (commit_without_prepare) {
    assert(!commit_prepared);
    if (WriteBatchInternal::Count(GetCommitTimeWriteBatch()) > 0) {
      s = Status::InvalidArgument(
          "Commit-time batch contains values that will not be committed.");
    } else {
      txn_state_.store(AWAITING_COMMIT);
      if (log_number_ > 0) {
        dbimpl_->logs_with_prep_tracker()->MarkLogAsHavingPrepSectionFlushed(
            log_number_);
      }
      s = CommitWithoutPrepareInternal();
      if (!name_.empty()) {
        txn_db_impl_->UnregisterTransaction(this);
      }
      Clear();
      if (s.ok()) {
        txn_state_.store(COMMITTED);
      }
    }
  } else if (commit_prepared) {
    txn_state_.store(AWAITING_COMMIT);

    s = CommitInternal();

    if (!s.ok()) {
      ROCKS_LOG_WARN(db_impl_->immutable_db_options().info_log,
                     "Commit write failed");
      return s;
    }

    // FindObsoleteFiles must now look to the memtables
    // to determine what prep logs must be kept around,
    // not the prep section heap.
    assert(log_number_ > 0);
    dbimpl_->logs_with_prep_tracker()->MarkLogAsHavingPrepSectionFlushed(
        log_number_);
    txn_db_impl_->UnregisterTransaction(this);

    Clear();
    txn_state_.store(COMMITTED);
  } else if (txn_state_ == LOCKS_STOLEN) {
    s = Status::Expired();
  } else if (txn_state_ == COMMITTED) {
    s = Status::InvalidArgument("Transaction has already been committed.");
  } else if (txn_state_ == ROLLEDBACK) {
    s = Status::InvalidArgument("Transaction has already been rolledback.");
  } else {
    s = Status::InvalidArgument("Transaction is not in state for commit.");
  }

  return s;
}

Status WriteCommittedTxn::CommitWithoutPrepareInternal() {
  uint64_t seq_used = kMaxSequenceNumber;
  auto s =
      db_impl_->WriteImpl(write_options_, GetWriteBatch()->GetWriteBatch(),
                          /*callback*/ nullptr, /*log_used*/ nullptr,
                          /*log_ref*/ 0, /*disable_memtable*/ false, &seq_used);
  assert(!s.ok() || seq_used != kMaxSequenceNumber);
  if (s.ok()) {
    SetId(seq_used);
  }
  return s;
}

Status WriteCommittedTxn::CommitBatchInternal(WriteBatch* batch, size_t) {
  uint64_t seq_used = kMaxSequenceNumber;
  auto s = db_impl_->WriteImpl(write_options_, batch, /*callback*/ nullptr,
                               /*log_used*/ nullptr, /*log_ref*/ 0,
                               /*disable_memtable*/ false, &seq_used);
  assert(!s.ok() || seq_used != kMaxSequenceNumber);
  if (s.ok()) {
    SetId(seq_used);
  }
  return s;
}

Status WriteCommittedTxn::CommitInternal() {
  // We take the commit-time batch and append the Commit marker.
  // The Memtable will ignore the Commit marker in non-recovery mode
  WriteBatch* working_batch = GetCommitTimeWriteBatch();
  WriteBatchInternal::MarkCommit(working_batch, name_);

  // any operations appended to this working_batch will be ignored from WAL
  working_batch->MarkWalTerminationPoint();

  // insert prepared batch into Memtable only skipping WAL.
  // Memtable will ignore BeginPrepare/EndPrepare markers
  // in non recovery mode and simply insert the values
  WriteBatchInternal::Append(working_batch, GetWriteBatch()->GetWriteBatch());

  uint64_t seq_used = kMaxSequenceNumber;
  auto s =
      db_impl_->WriteImpl(write_options_, working_batch, /*callback*/ nullptr,
                          /*log_used*/ nullptr, /*log_ref*/ log_number_,
                          /*disable_memtable*/ false, &seq_used);
  assert(!s.ok() || seq_used != kMaxSequenceNumber);
  if (s.ok()) {
    SetId(seq_used);
  }
  return s;
}

Status PessimisticTransaction::Rollback() {
  Status s;
  if (txn_state_ == PREPARED) {
    txn_state_.store(AWAITING_ROLLBACK);

    s = RollbackInternal();

    if (s.ok()) {
      // we do not need to keep our prepared section around
      assert(log_number_ > 0);
      dbimpl_->logs_with_prep_tracker()->MarkLogAsHavingPrepSectionFlushed(
          log_number_);
      Clear();
      txn_state_.store(ROLLEDBACK);
    }
  } else if (txn_state_ == STARTED) {
    if (log_number_ > 0) {
      assert(txn_db_impl_->GetTxnDBOptions().write_policy == WRITE_UNPREPARED);
      assert(GetId() > 0);
      s = RollbackInternal();

      if (s.ok()) {
        dbimpl_->logs_with_prep_tracker()->MarkLogAsHavingPrepSectionFlushed(
            log_number_);
      }
    }
    // prepare couldn't have taken place
    Clear();
  } else if (txn_state_ == COMMITTED) {
    s = Status::InvalidArgument("This transaction has already been committed.");
  } else {
    s = Status::InvalidArgument(
        "Two phase transaction is not in state for rollback.");
  }

  return s;
}

Status WriteCommittedTxn::RollbackInternal() {
  WriteBatch rollback_marker;
  WriteBatchInternal::MarkRollback(&rollback_marker, name_);
  auto s = db_impl_->WriteImpl(write_options_, &rollback_marker);
  return s;
}

Status PessimisticTransaction::RollbackToSavePoint() {
  if (txn_state_ != STARTED) {
    return Status::InvalidArgument("Transaction is beyond state for rollback.");
  }

  // Unlock any keys locked since last transaction
  const std::unique_ptr<TransactionKeyMap>& keys =
      GetTrackedKeysSinceSavePoint();

  if (keys) {
    txn_db_impl_->UnLock(this, keys.get());
  }

  return TransactionBaseImpl::RollbackToSavePoint();
}

// Lock all keys in this batch.
// On success, caller should unlock keys_to_unlock
Status PessimisticTransaction::LockBatch(WriteBatch* batch,
                                         TransactionKeyMap* keys_to_unlock) {
  class Handler : public WriteBatch::Handler {
   public:
    // Sorted map of column_family_id to sorted set of keys.
    // Since LockBatch() always locks keys in sorted order, it cannot deadlock
    // with itself.  We're not using a comparator here since it doesn't matter
    // what the sorting is as long as it's consistent.
    std::map<uint32_t, std::set<std::string>> keys_;

    Handler() {}

    void RecordKey(uint32_t column_family_id, const Slice& key) {
      std::string key_str = key.ToString();

      auto& cfh_keys = keys_[column_family_id];
      auto iter = cfh_keys.find(key_str);
      if (iter == cfh_keys.end()) {
        // key not yet seen, store it.
        cfh_keys.insert({std::move(key_str)});
      }
    }

    Status PutCF(uint32_t column_family_id, const Slice& key,
                 const Slice& /* unused */) override {
      RecordKey(column_family_id, key);
      return Status::OK();
    }
    Status MergeCF(uint32_t column_family_id, const Slice& key,
                   const Slice& /* unused */) override {
      RecordKey(column_family_id, key);
      return Status::OK();
    }
    Status DeleteCF(uint32_t column_family_id, const Slice& key) override {
      RecordKey(column_family_id, key);
      return Status::OK();
    }
  };

  // Iterating on this handler will add all keys in this batch into keys
  Handler handler;
  batch->Iterate(&handler);

  Status s;

  // Attempt to lock all keys
  for (const auto& cf_iter : handler.keys_) {
    uint32_t cfh_id = cf_iter.first;
    auto& cfh_keys = cf_iter.second;

    for (const auto& key_iter : cfh_keys) {
      const std::string& key = key_iter;

      s = txn_db_impl_->TryLock(this, cfh_id, key, true /* exclusive */);
      if (!s.ok()) {
        break;
      }
      TrackKey(keys_to_unlock, cfh_id, std::move(key), kMaxSequenceNumber,
               false, true /* exclusive */);
    }

    if (!s.ok()) {
      break;
    }
  }

  if (!s.ok()) {
    txn_db_impl_->UnLock(this, keys_to_unlock);
  }

  return s;
}

// Attempt to lock this key.
// Returns OK if the key has been successfully locked.  Non-ok, otherwise.
// If check_shapshot is true and this transaction has a snapshot set,
// this key will only be locked if there have been no writes to this key since
// the snapshot time.
Status PessimisticTransaction::TryLock(ColumnFamilyHandle* column_family,
                                       const Slice& key, bool read_only,
                                       bool exclusive, const bool do_validate,
                                       const bool assume_tracked) {
  assert(!assume_tracked || !do_validate);
  Status s;
  if (UNLIKELY(skip_concurrency_control_)) {
    return s;
  }
  uint32_t cfh_id = GetColumnFamilyID(column_family);
  std::string key_str = key.ToString();
  bool previously_locked;
  bool lock_upgrade = false;

  // lock this key if this transactions hasn't already locked it
  SequenceNumber tracked_at_seq = kMaxSequenceNumber;

  const auto& tracked_keys = GetTrackedKeys();
  const auto tracked_keys_cf = tracked_keys.find(cfh_id);
  if (tracked_keys_cf == tracked_keys.end()) {
    previously_locked = false;
  } else {
    auto iter = tracked_keys_cf->second.find(key_str);
    if (iter == tracked_keys_cf->second.end()) {
      previously_locked = false;
    } else {
      if (!iter->second.exclusive && exclusive) {
        lock_upgrade = true;
      }
      previously_locked = true;
      tracked_at_seq = iter->second.seq;
    }
  }

  // Lock this key if this transactions hasn't already locked it or we require
  // an upgrade.
  if (!previously_locked || lock_upgrade) {
    s = txn_db_impl_->TryLock(this, cfh_id, key_str, exclusive);
  }

  SetSnapshotIfNeeded();

  // Even though we do not care about doing conflict checking for this write,
  // we still need to take a lock to make sure we do not cause a conflict with
  // some other write.  However, we do not need to check if there have been
  // any writes since this transaction's snapshot.
  // TODO(agiardullo): could optimize by supporting shared txn locks in the
  // future
  if (!do_validate || snapshot_ == nullptr) {
    if (assume_tracked && !previously_locked) {
      s = Status::InvalidArgument(
          "assume_tracked is set but it is not tracked yet");
    }
    // Need to remember the earliest sequence number that we know that this
    // key has not been modified after.  This is useful if this same
    // transaction
    // later tries to lock this key again.
    if (tracked_at_seq == kMaxSequenceNumber) {
      // Since we haven't checked a snapshot, we only know this key has not
      // been modified since after we locked it.
      // Note: when last_seq_same_as_publish_seq_==false this is less than the
      // latest allocated seq but it is ok since i) this is just a heuristic
      // used only as a hint to avoid actual check for conflicts, ii) this would
      // cause a false positive only if the snapthot is taken right after the
      // lock, which would be an unusual sequence.
      tracked_at_seq = db_->GetLatestSequenceNumber();
    }
  } else {
    // If a snapshot is set, we need to make sure the key hasn't been modified
    // since the snapshot.  This must be done after we locked the key.
    // If we already have validated an earilier snapshot it must has been
    // reflected in tracked_at_seq and ValidateSnapshot will return OK.
    if (s.ok()) {
      s = ValidateSnapshot(column_family, key, &tracked_at_seq);

      if (!s.ok()) {
        // Failed to validate key
        if (!previously_locked) {
          // Unlock key we just locked
          if (lock_upgrade) {
            s = txn_db_impl_->TryLock(this, cfh_id, key_str,
                                      false /* exclusive */);
            assert(s.ok());
          } else {
            txn_db_impl_->UnLock(this, cfh_id, key.ToString());
          }
        }
      }
    }
  }

  if (s.ok()) {
    // We must track all the locked keys so that we can unlock them later. If
    // the key is already locked, this func will update some stats on the
    // tracked key. It could also update the tracked_at_seq if it is lower
    // than the existing tracked key seq. These stats are necessary for
    // RollbackToSavePoint to determine whether a key can be safely removed
    // from tracked_keys_. Removal can only be done if a key was only locked
    // during the current savepoint.
    //
    // Recall that if assume_tracked is true, we assume that TrackKey has been
    // called previously since the last savepoint, with the same exclusive
    // setting, and at a lower sequence number, so skipping here should be
    // safe.
    if (!assume_tracked) {
      TrackKey(cfh_id, key_str, tracked_at_seq, read_only, exclusive);
    } else {
#ifndef NDEBUG
      assert(tracked_keys_cf->second.count(key_str) > 0);
      const auto& info = tracked_keys_cf->second.find(key_str)->second;
      assert(info.seq <= tracked_at_seq);
      assert(info.exclusive == exclusive);
#endif
    }
  }

  return s;
}

// Return OK() if this key has not been modified more recently than the
// transaction snapshot_.
// tracked_at_seq is the global seq at which we either locked the key or already
// have done ValidateSnapshot.
Status PessimisticTransaction::ValidateSnapshot(
    ColumnFamilyHandle* column_family, const Slice& key,
    SequenceNumber* tracked_at_seq) {
  assert(snapshot_);

  SequenceNumber snap_seq = snapshot_->GetSequenceNumber();
  if (*tracked_at_seq <= snap_seq) {
    // If the key has been previous validated (or locked) at a sequence number
    // earlier than the current snapshot's sequence number, we already know it
    // has not been modified aftter snap_seq either.
    return Status::OK();
  }
  // Otherwise we have either
  // 1: tracked_at_seq == kMaxSequenceNumber, i.e., first time tracking the key
  // 2: snap_seq < tracked_at_seq: last time we lock the key was via
  // do_validate=false which means we had skipped ValidateSnapshot. In both
  // cases we should do ValidateSnapshot now.

  *tracked_at_seq = snap_seq;

  ColumnFamilyHandle* cfh =
      column_family ? column_family : db_impl_->DefaultColumnFamily();

  return TransactionUtil::CheckKeyForConflicts(
      db_impl_, cfh, key.ToString(), snap_seq, false /* cache_only */);
}

bool PessimisticTransaction::TryStealingLocks() {
  assert(IsExpired());
  TransactionState expected = STARTED;
  return std::atomic_compare_exchange_strong(&txn_state_, &expected,
                                             LOCKS_STOLEN);
}

void PessimisticTransaction::UnlockGetForUpdate(
    ColumnFamilyHandle* column_family, const Slice& key) {
  txn_db_impl_->UnLock(this, GetColumnFamilyID(column_family), key.ToString());
}

Status PessimisticTransaction::SetName(const TransactionName& name) {
  Status s;
  if (txn_state_ == STARTED) {
    if (name_.length()) {
      s = Status::InvalidArgument("Transaction has already been named.");
    } else if (txn_db_impl_->GetTransactionByName(name) != nullptr) {
      s = Status::InvalidArgument("Transaction name must be unique.");
    } else if (name.length() < 1 || name.length() > 512) {
      s = Status::InvalidArgument(
          "Transaction name length must be between 1 and 512 chars.");
    } else {
      name_ = name;
      txn_db_impl_->RegisterTransaction(this);
    }
  } else {
    s = Status::InvalidArgument("Transaction is beyond state for naming.");
  }
  return s;
}

}  // namespace ROCKSDB_NAMESPACE

#endif  // ROCKSDB_LITE


text:
<!--
Description: omicron
Expect:      feed['title'] == u'testing \u03bf entity'
-->
<rss>
<channel>
<title>testing ο entity</title>
</channel>
</rss>

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Cat. pl. Cub. 169. 1866

#### Original name
null

### Remarks
null


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

'use strict';

const assert = require('../../testing/assert');

const AssertionError = require('assert').AssertionError;
const assertTrue = require('assert').ok;
const assertEqual = require('assert').equal;
const assertThrows = require('assert').throws;
const fail = require('assert').fail;

describe('assert', function() {
  describe('atLeast', function() {
    it('compares subject >= value', function() {
      assert(1).atLeast(0);
      assert(1).atLeast(1);
      assertThrows(() => assert(1).atLeast(2));
    });

    it('accepts failure message', function() {
      assertThrows(
          () => assert(1).atLeast(2, 'hi there!'),
          (error) => error.message.indexOf('hi there') != -1);
    });

    it('fails if given a non-numeric subject', function() {
      assertThrows(() => assert('a').atLeast(1));
    });

    it('fails if given a non-numeric bound', function() {
      assertThrows(() => assert(1).atLeast('a'));
    });

    it('waits for promised subject', function() {
      return assert(Promise.resolve(123)).atLeast(100);
    });

    it('waits for promised subject (with failure)', function() {
      return assert(Promise.resolve(100))
          .atLeast(123)
          .then(() => fail('should have failed'), function(e) {
            assertInstanceOf(AssertionError, e);
            assertEqual('100 >= 123', e.message);
          });
    });
  });

  describe('atMost', function() {
    it('compares subject <= value', function() {
      assertThrows(() => assert(1).atMost(0));
      assert(1).atMost(1);
      assert(1).atMost(2);
    });

    it('accepts failure message', function() {
      assertThrows(
          () => assert(1).atMost(0, 'hi there!'),
          (error) => error.message.indexOf('hi there!') != -1);
    });

    it('fails if given a non-numeric subject', function() {
      assertThrows(() => assert(1).atMost('a'));
    });

    it('fails if given a non-numeric bound', function() {
      assertThrows(() => assert('a').atMost(1));
    });

    it('waits for promised subject', function() {
      return assert(Promise.resolve(100)).atMost(123);
    });

    it('waits for promised subject (with failure)', function() {
      return assert(Promise.resolve(123))
          .atMost(100)
          .then(() => fail('should have failed'), function(e) {
            assertInstanceOf(AssertionError, e);
            assertEqual('123 <= 100', e.message);
          });
    });
  });

  describe('greaterThan', function() {
    it('compares subject > value', function() {
      assertThrows(() => assert(1).greaterThan(1));
      assertThrows(() => assert(1).greaterThan(2));
      assert(2).greaterThan(1);
    });

    it('accepts failure message', function() {
      assertThrows(
          () => assert(0).greaterThan(1, 'hi there!'),
          (error) => error.message.indexOf('hi there!') != -1);
    });

    it('fails if given a non-numeric subject', function() {
      assertThrows(() => assert('a').atMost(1));
    });

    it('fails if given a non-numeric bound', function() {
      assertThrows(() => assert(1).atMost('a'));
    });

    it('waits for promised subject', function() {
      return assert(Promise.resolve(123)).greaterThan(100);
    });

    it('waits for promised subject (with failure)', function() {
      return assert(Promise.resolve(100))
          .greaterThan(123)
          .then(() => fail('should have failed'), function(e) {
            assertInstanceOf(AssertionError, e);
            assertEqual('100 > 123', e.message);
          });
    });
  });

  describe('lessThan', function() {
    it('compares subject < value', function() {
      assertThrows(() => assert(1).lessThan(0));
      assertThrows(() => assert(1).lessThan(1));
      assert(1).lessThan(2);
    });

    it('accepts failure message', function() {
      assertThrows(
          () => assert(1).lessThan(0, 'hi there!'),
          (error) => error.message.indexOf('hi there!') != -1);
    });

    it('fails if given a non-numeric subject', function() {
      assertThrows(() => assert('a').lessThan(1));
    });

    it('fails if given a non-numeric bound', function() {
      assertThrows(() => assert(1).lessThan('a'));
    });

    it('waits for promised subject', function() {
      return assert(Promise.resolve(100)).lessThan(123);
    });

    it('waits for promised subject (with failure)', function() {
      return assert(Promise.resolve(123))
          .lessThan(100)
          .then(() => fail('should have failed'), function(e) {
            assertInstanceOf(AssertionError, e);
            assertEqual('123 < 100', e.message);
          });
    });
  });

  describe('closeTo', function() {
    it('accepts values within epislon of target', function() {
      assert(123).closeTo(123, 0);
      assert(123).closeTo(124, 1);
      assert(125).closeTo(124, 1);

      assertThrows(() => assert(123).closeTo(125, .1));
      assertThrows(() => assert(1./3).closeTo(.8, .01));
    });

    it('waits for promised values', function() {
      let p = new Promise(resolve => setTimeout(() => resolve(123), 10));
      return assert(p).closeTo(124, 1);
    });
  });

  describe('instanceOf', function() {
    it('works with direct instances', function() {
      assert(Error('foo')).instanceOf(Error);
    });

    it('works with sub-types', function() {
      assert(TypeError('foo')).instanceOf(Error);
    });

    it('parent types are not instances of sub-types', function() {
      assertThrows(() => assert(Error('foo')).instanceOf(TypeError));
    });
  });

  describe('isNull', function() {
    it('normal case', function() {
      assert(null).isNull();
      assertThrows(() => assert(1).isNull());
    });

    it('handles promised values', function() {
      let p = new Promise(function(f) {
        setTimeout(() => f(null), 10);
      });
      return assert(p).isNull();
    });

    it('does not match on undefined', function() {
      assertThrows(() => assert(void(0)).isNull());
    })
  });

  describe('isUndefined', function() {
    it('normal case', function() {
      assert(void(0)).isUndefined();
      assertThrows(() => assert(1).isUndefined());
    });

    it('handles promised values', function() {
      let p = new Promise(function(f) {
        setTimeout(() => f(void(0)), 10);
      });
      return assert(p).isUndefined();
    });

    it('does not match on null', function() {
      assertThrows(() => assert(null).isUndefined());
    })
  });

  describe('contains', function() {
    it('works with strings', function() {
      assert('abc').contains('a');
      assert('abc').contains('ab');
      assert('abc').contains('abc');
      assert('abc').contains('bc');
      assert('abc').contains('c');
      assertThrows(() => assert('abc').contains('d'));
    });

    it('works with arrays', function() {
      assert([1, 2, 3]).contains(1);
      assert([1, 2, 3]).contains(2);
      assert([1, 2, 3]).contains(3);
      assertThrows(() => assert([1, 2]).contains(3));
    });

    it('works with maps', function() {
      let m = new Map;
      m.set(1, 2);
      assert(m).contains(1);
      assertThrows(() => assert(m).contains(2));
    });

    it('works with sets', function() {
      let s = new Set;
      s.add(1);
      assert(s).contains(1);
      assertThrows(() => assert(s).contains(2));
    });

    it('requires an array, string, map, or set subject', function() {
      assertThrows(() => assert(123).contains('a'));
    });
  });

  describe('endsWith', function() {
    it('works', function() {
      assert('abc').endsWith('abc');
      assert('abc').endsWith('bc');
      assert('abc').endsWith('c');
      assertThrows(() => assert('abc').endsWith('d'));
    })
  });

  describe('startsWith', function() {
    it('works', function() {
      assert('abc').startsWith('abc');
      assert('abc').startsWith('ab');
      assert('abc').startsWith('a');
      assertThrows(() => assert('abc').startsWith('d'));
    })
  });

  describe('matches', function() {
    it('requires a regex value', function() {
      assertThrows(() => assert('abc').matches(1234));
    });

    it('requires a string value', function() {
      assertThrows(() => assert(1234).matches(/abc/));
    });

    it('requires a string value (promise case)', function() {
      return assert(Promise.resolve(1234))
          .matches(/abc/)
          .then(fail, function(error) {
            assertEqual(
                'Expected a string matching /abc/, got <1234> (number)',
                error.message);
          });
    });

    it('applies regex', function() {
      assert('abc').matches(/abc/);
      assertThrows(() => assert('def').matches(/abc/));
    });
  });

  describe('isTrue', function() {
    it('only accepts booleans', function() {
      assertThrows(() => assert(123).isTrue());
    });

    it('accepts true values', function() {
      assert(true).isTrue();
      assert(Boolean('abc')).isTrue();
      return assert(Promise.resolve(true)).isTrue();
    });

    it('rejects false values', function() {
      assertThrows(() => assert(false).isTrue());
      assertThrows(() => assert(Boolean(0)).isTrue());
      return assert(Promise.resolve(false)).isTrue()
          .then(fail, function() {/*no-op, ok*/});
    });
  });

  describe('isFalse', function() {
    it('only accepts booleans', function() {
      assertThrows(() => assert(123).isFalse());
    })

    it('accepts false values', function() {
      assert(false).isFalse();
      assert(Boolean('')).isFalse();
      return assert(Promise.resolve(false)).isFalse();
    });

    it('rejects true values', function() {
      assertThrows(() => assert(true).isFalse());
      assertThrows(() => assert(Boolean(1)).isFalse());
      return assert(Promise.resolve(true)).isFalse()
          .then(fail, function() {/*no-op, ok*/});
    });
  });

  describe('isEqualTo', function() {
    it('is strict equality', function() {
      assert('abc').isEqualTo('abc');
      assert('abc').equals('abc');
      assert('abc').equalTo('abc');
      assertThrows(() => assert('1').isEqualTo(1));
    });
  });

  describe('notEqualTo', function() {
    it('tests strict equality', function() {
      assert('1').notEqualTo(1);
      assert(1).notEqualTo('1');
      assertThrows(() => assert('abc').notEqualTo('abc'));
    });
  });

  function assertInstanceOf(ctor, value) {
    assertTrue(value instanceof ctor);
  }
});


text:
var temporal;
$(document).on('ready', function(){
  $('#addempleado').modal();
  $('.addempleado').on('click', function(event){
    return false;
  });
  $('.addempleado').on('click', function(event){
    $("#contenido").load($(this).attr('href'),function(responseTxt, statusTxt, xhr){
          alert(statusTxt+"   Error: " + xhr.status + ": " + xhr.statusText);
          $('#id_tienda, #id_ciudad').material_select();
          $('#modal_add_empleado').submit(function() {
                return false;
            });
          $('#addempleado').modal('open');
          $('.datepicker').pickadate({
            selectMonths: true, // Creates a dropdown to control month
            selectYears: 15, // Creates a dropdown of 15 years to control year
            monthsFull: [ 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ],
            monthsShort: [ 'Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic' ],
            weekdaysFull: [ 'Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado' ],
            weekdaysShort: [ 'Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab' ],
            formatSubmit: 'dd/mm/yyyy',
            format: 'dd/mm/yyyy',
            onSet: function( arg ){
                if ( 'select' in arg ){
                    this.close();
                }
            }
          });
          $('select').material_select();
          $('.saveempleado').on('click',function(event){
            var options = {
                //target:        '#output2',   // target element(s) to be updated with server response
                beforeSubmit:  showRequest,  // pre-submit callback
                success:       showResponse,  // post-submit callback
                error:error,

                // other available options:
                url:       '/usuario/add/empleado/',         // override for form's 'action' attribute
                type:      'post' ,       // 'get' or 'post', override for form's 'method' attribute
                dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
                //clearForm: true        // clear all form fields after successful submit
                //resetForm: true        // reset the form after successful submit

                // $.ajax options can be used here too, for example:
                //timeout:   3000
            };
            $("#modal_add_empleado").ajaxSubmit(options);
          });
    });
  });
});

// pre-submit callback
function showRequest(formData, jqForm, options) {
    var queryString = $.param(formData);
    console.log('About to submit: \n\n' + queryString);
    return true;
}

function showResponse(responseText, statusText, xhr, $form)  {
  console.log("*********************************");
  temporal = responseText;
    console.log('status: ' + statusText + '\n\nresponseText: \n' + responseText +
        '\n\nThe output div should have already been updated with the responseText.');
  listEmpleados();
  $('#addempleado').modal('close');
}

function error(response,status,xhr){
  validadFormulario(response.responseJSON,"modal_add_empleado");
}


text:
package com.amazonaws.services.securityhub.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * An Internet Control Message Protocol (ICMP) type and code.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class IcmpTypeCode implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The ICMP code for which to deny or allow access. To deny or allow all codes, use the value -1.
     *

     */
    private Integer code;
    /**
     *

     * The ICMP type for which to deny or allow access. To deny or allow all types, use the value -1.
     *

     */
    private Integer type;

    /**
     *

     * The ICMP code for which to deny or allow access. To deny or allow all codes, use the value -1.
     *

     *
     * @param code
     *        The ICMP code for which to deny or allow access. To deny or allow all codes, use the value -1
     *        .
     */

    public void setCode(Integer code) {
        this.code = code;
    }

    /**
     *

     * The ICMP code for which to deny or allow access. To deny or allow all codes, use the value -1.
     *

     *
     * @return The ICMP code for which to deny or allow access. To deny or allow all codes, use the value
     *         -1.
     */

    public Integer getCode() {
        return this.code;
    }

    /**
     *

     * The ICMP code for which to deny or allow access. To deny or allow all codes, use the value -1.
     *

     *
     * @param code
     *        The ICMP code for which to deny or allow access. To deny or allow all codes, use the value -1
     *        .
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public IcmpTypeCode withCode(Integer code) {
        setCode(code);
        return this;
    }

    /**
     *

     * The ICMP type for which to deny or allow access. To deny or allow all types, use the value -1.
     *

     *
     * @param type
     *        The ICMP type for which to deny or allow access. To deny or allow all types, use the value -1
     *        .
     */

    public void setType(Integer type) {
        this.type = type;
    }

    /**
     *

     * The ICMP type for which to deny or allow access. To deny or allow all types, use the value -1.
     *

     *
     * @return The ICMP type for which to deny or allow access. To deny or allow all types, use the value
     *         -1.
     */

    public Integer getType() {
        return this.type;
    }

    /**
     *

     * The ICMP type for which to deny or allow access. To deny or allow all types, use the value -1.
     *

     *
     * @param type
     *        The ICMP type for which to deny or allow access. To deny or allow all types, use the value -1
     *        .
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public IcmpTypeCode withType(Integer type) {
        setType(type);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getCode() != null)
            sb.append("Code: ").append(getCode()).append(",");
        if (getType() != null)
            sb.append("Type: ").append(getType());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof IcmpTypeCode == false)
            return false;
        IcmpTypeCode other = (IcmpTypeCode) obj;
        if (other.getCode() == null ^ this.getCode() == null)
            return false;
        if (other.getCode() != null && other.getCode().equals(this.getCode()) == false)
            return false;
        if (other.getType() == null ^ this.getType() == null)
            return false;
        if (other.getType() != null && other.getType().equals(this.getType()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getCode() == null) ? 0 : getCode().hashCode());
        hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode());
        return hashCode;
    }

    @Override
    public IcmpTypeCode clone() {
        try {
            return (IcmpTypeCode) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.securityhub.model.transform.IcmpTypeCodeMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
function symbols = sym_decode(signal, efficiency)
    if efficiency == 2
        gray = [0 1 3 2];
    else
        gray = [0 1 3 2 6 7 5 4];
    end

    levels = 2^efficiency;
    signal = gray(mod(round(angle(signal) / (2 * pi / levels)), levels) + 1);

    symbols = de2bi(signal, efficiency, 'left-msb')';
    symbols = symbols(:);
end


text:
package com.firefly.tools;

import java.sql.SQLException;
import java.util.List;

import com.firefly.db.QueryHelper;

import test.usr.UserModel;

public class Test {

	public static void main(String[] args) throws SQLException {
		UserModel um=new UserModel();
		um.setAccount("vicshe");

		String sql="";//Class2Sql.createSelectSql("user", "*", um);
		System.out.println(sql);

		List<UserModel> list=QueryHelper.query(UserModel.class, sql);

		for(UserModel u:list){
			System.out.println(u.getPassword());

		}
		System.out.println(list.size());
	}
}


text:
"""
Contains all core validation functions.
"""

import os
import re
import socket
import logging

from . import utils

from .exceptions import ParamValidationError

__all__ = ('ParamValidationError', 'validate_integer', 'validate_float',
           'validate_regexp', 'validate_port', 'validate_not_empty',
           'validate_options', 'validate_multi_options', 'validate_ip',
           'validate_multi_ip', 'validate_file', 'validate_ping',
           'validate_multi_ping', 'validate_ssh', 'validate_multi_ssh',
           'validate_sshkey', 'validate_ldap_url', 'validate_ldap_dn')

def validate_integer(param, options=None):
    """
    Raises ParamValidationError if given param is not integer.
    """
    if not param:
        return
    options = options or []
    try:
        int(param)
    except ValueError:
        logging.debug('validate_integer(%s, options=%s) failed.' %
                      (param, options))
        msg = 'Given value is not an integer: %s'
        raise ParamValidationError(msg % param)

def validate_float(param, options=None):
    """
    Raises ParamValidationError if given param is not a float.
    """
    if not param:
        return
    options = options or []
    try:
        float(param)
    except ValueError:
        logging.debug('validate_float(%s, options=%s) failed.' %
                      (param, options))
        msg = 'Given value is not a float: %s'
        raise ParamValidationError(msg % param)

def validate_regexp(param, options=None):
    """
    Raises ParamValidationError if given param doesn't match at least
    one of regular expressions given in options.
    """
    if not param:
        return
    options = options or []
    for regex in options:
        if re.search(regex, param):
            break
    else:
        logging.debug('validate_regexp(%s, options=%s) failed.' %
                      (param, options))
        msg = 'Given value does not match required regular expression: %s'
        raise ParamValidationError(msg % param)

def validate_multi_regexp(param, options=None):
    """
    Raises ParamValidationError if any of the comma separated values given
    in param doesn't match one of the regular expressions given in options.
    """
    options = options or []
    for i in param.split(','):
        validate_regexp(i.strip(), options=options)

def validate_port(param, options=None):
    """
    Raises ParamValidationError if given param is not a decimal number
    in range (0, 65535).
    """
    if not param:
        return
    options = options or []
    validate_integer(param, options)
    port = int(param)
    if not (port >= 0 and port < 65535):
        logging.debug('validate_port(%s, options=%s) failed.' %
                      (param, options))
        msg = 'Given value is outside the range of (0, 65535): %s'
        raise ParamValidationError(msg % param)

def validate_not_empty(param, options=None):
    """
    Raises ParamValidationError if given param is empty.
    """
    options = options or []
    if not param and param is not False:
        logging.debug('validate_not_empty(%s, options=%s) failed.' %
                      (param, options))
        msg = 'Given value is not allowed: %s'
        raise ParamValidationError(msg % param)

def validate_options(param, options=None):
    """
    Raises ParamValidationError if given param is not member of options.
    """
    if not param:
        return

    options = options or []
    validate_not_empty(param, options)
    if param not in options:
        logging.debug('validate_options(%s, options=%s) failed.' %
                      (param, options))
        msg = 'Given value is not member of allowed values %s: %s'
        raise ParamValidationError(msg % (options, param))

def validate_multi_options(param, options=None):
    """
    Validates if comma separated values given in params are members
    of options.
    """
    if not param:
        return
    options = options or []
    for i in param.split(','):
        validate_options(i.strip(), options=options)

def validate_ip(param, options=None):
    """
    Raises ParamValidationError if given parameter value is not in IPv4
    or IPv6 address.
    """
    if not param:
        return
    for family in (socket.AF_INET, socket.AF_INET6):
        try:
            socket.inet_pton(family, param)
            return family
        except socket.error:
            continue
    else:
        logging.debug('validate_ip(%s, options=%s) failed.' %
                      (param, options))
        msg = 'Given host is not in IP address format: %s'
        raise ParamValidationError(msg % param)

def validate_multi_ip(param, options=None):
    """
    Raises ParamValidationError if comma separated IP addresses given
    parameter value are in IPv4 or IPv6 aformat.
    """
    for host in param.split(','):
        host = host.split('/', 1)[0]
        validate_ip(host.strip(), options)

def validate_file(param, options=None):
    """
    Raises ParamValidationError if provided file in param does not exist.
    """
    if not param:
        return

    options = options or []
    if not os.path.isfile(param):
        logging.debug('validate_file(%s, options=%s) failed.' %
                      (param, options))
        msg = 'Given file does not exist: %s'
        raise ParamValidationError(msg % param)

def validate_ping(param, options=None):
    """
    Raises ParamValidationError if provided host does not answer to ICMP
    echo request.
    """
    if not param:
        return
    options = options or []
    rc, out = utils.execute(['/bin/ping', '-c', '1', str(param)],
                            can_fail=False)
    if rc != 0:
        logging.debug('validate_ping(%s, options=%s) failed.' %
                      (param, options))
        msg = 'Given host is unreachable: %s'
        raise ParamValidationError(msg % param)

def validate_multi_ping(param, options=None):
    """
    Raises ParamValidationError if comma separated host given in param
    do not answer to ICMP echo request.
    """
    options = options or []
    for host in param.split(","):
        validate_ping(host.strip())

_tested_ports = []

def touch_port(host, port):
    """
    Check that provided host is listening on provided port.
    """
    key = "%s:%d" % (host, port)
    if key in _tested_ports:
        return
    s = socket.socket(validate_ip(host), socket.SOCK_STREAM)
    s.connect((host, port))
    s.shutdown(socket.SHUT_RDWR)
    s.close()
    _tested_ports.append(key)

def validate_ssh(param, options=None):
    """
    Raises ParamValidationError if provided host does not listen
    on port 22.
    """
    if not param:
        return
    options = options or []
    try:
        touch_port(param.strip(), 22)
    except socket.error:
        logging.debug('validate_ssh(%s, options=%s) failed.' %
                      (param, options))
        msg = 'Given host does not listen on port 22: %s'
        raise ParamValidationError(msg % param)

def validate_multi_ssh(param, options=None):
    """
    Raises ParamValidationError if comma separated host provided
    in param do not listen on port 22.
    """
    options = options or []
    for host in param.split(","):
        validate_ssh(host)

def validate_sshkey(param, options=None):
    """
    Raises ParamValidationError if provided sshkey file is not public key.
    """
    if not param:
        return
    with open(param) as sshkey:
        line = sshkey.readline()
    msg = None
    if not re.search('ssh-|ecdsa', line):
        msg = ('Invalid content header in %s, Public SSH key is required.'
               % param)
    if re.search('BEGIN [RD]SA PRIVATE KEY', line):
        msg = 'Public SSH key is required. You passed private key.'
    if msg:
        raise ParamValidationError(msg)

def validate_ldap_url(param, options=None):
    """
    Raises ParamValidationError if provided param is not a valid LDAP URL
    """
    if not param:
        return
    try:
        import ldapurl
    except ImportError:
        msg = (
            'The python ldap package is required to use this functionality.'
        )
        raise ParamValidationError(msg)

    try:
        ldapurl.LDAPUrl(param)
    except ValueError as ve:
        msg = ('The given string [%s] is not a valid LDAP URL: %s' %
               (param, ve))
        raise ParamValidationError(msg)

def validate_ldap_dn(param, options=None):
    """
    Raises ParamValidationError if provided param is not a valid LDAP DN
    """
    if not param:
        return
    try:
        import ldap
        import ldap.dn
    except ImportError:
        msg = (
            'The python ldap package is required to use this functionality.'
        )
        raise ParamValidationError(msg)

    try:
        ldap.dn.str2dn(param)
    except ldap.DECODING_ERROR as de:
        msg = ('The given string [%s] is not a valid LDAP DN: %s' %
               (param, de))
        raise ParamValidationError(msg)


text:
import re
from typing import Any, Dict, List, Optional
from typing.re import Match

import markdown
from markdown.preprocessors import Preprocessor

# There is a lot of duplicated code between this file and
# help_settings_links.py. So if you're making a change here consider making
# it there as well.

REGEXP = re.compile(r'\{relative\|(?P<link_type>.*?)\|(?P<key>.*?)\}')

gear_info = {
    # The pattern is key: [name, link]
    # key is from REGEXP: `{relative|gear|key}`
    # name is what the item is called in the gear menu: `Select **name**.`
    # link is used for relative links: `Select [name](link).`
    'manage-streams': ['Manage streams', '/#streams/subscribed'],
    'settings': ['Settings', '/#settings/your-account'],
    'manage-organization': ['Manage organization', '/#organization/organization-profile'],
    'integrations': ['Integrations', '/integrations'],
    'stats': ['Statistics', '/stats'],
    'plans': ['Plans and pricing', '/plans'],
    'billing': ['Billing', '/billing'],
    'invite': ['Invite users', '/#invite'],
}

gear_instructions = """
1. From your desktop, click on the **gear**
   () in the upper right corner.

1. Select {item}.
"""

def gear_handle_match(key: str) -> str:
    if relative_help_links:
        item = f'[{gear_info[key][0]}]({gear_info[key][1]})'
    else:
        item = f'**{gear_info[key][0]}**'
    return gear_instructions.format(item=item)

stream_info = {
    'all': ['All streams', '/#streams/all'],
    'subscribed': ['Your streams', '/#streams/subscribed'],
}

stream_instructions_no_link = """
1. From your desktop, click on the **gear**
   () in the upper right corner.

1. Click **Manage streams**.
"""

def stream_handle_match(key: str) -> str:
    if relative_help_links:
        return f"1. Go to [{stream_info[key][0]}]({stream_info[key][1]})."
    if key == 'all':
        return stream_instructions_no_link + "\n\n1. Click **All streams** in the upper left."
    return stream_instructions_no_link

LINK_TYPE_HANDLERS = {
    'gear': gear_handle_match,
    'stream': stream_handle_match,
}

class RelativeLinksHelpExtension(markdown.Extension):
    def extendMarkdown(self, md: markdown.Markdown, md_globals: Dict[str, Any]) -> None:
        """ Add RelativeLinksHelpExtension to the Markdown instance. """
        md.registerExtension(self)
        md.preprocessors.add('help_relative_links', RelativeLinks(), '_begin')

relative_help_links: Optional[bool] = None

def set_relative_help_links(value: bool) -> None:
    global relative_help_links
    relative_help_links = value

class RelativeLinks(Preprocessor):
    def run(self, lines: List[str]) -> List[str]:
        done = False
        while not done:
            for line in lines:
                loc = lines.index(line)
                match = REGEXP.search(line)

                if match:
                    text = [self.handleMatch(match)]
                    # The line that contains the directive to include the macro
                    # may be preceded or followed by text or tags, in that case
                    # we need to make sure that any preceding or following text
                    # stays the same.
                    line_split = REGEXP.split(line, maxsplit=0)
                    preceding = line_split[0]
                    following = line_split[-1]
                    text = [preceding] + text + [following]
                    lines = lines[:loc] + text + lines[loc+1:]
                    break
            else:
                done = True
        return lines

    def handleMatch(self, match: Match[str]) -> str:
        return LINK_TYPE_HANDLERS[match.group('link_type')](match.group('key'))

def makeExtension(*args: Any, **kwargs: Any) -> RelativeLinksHelpExtension:
    return RelativeLinksHelpExtension(*args, **kwargs)


text:
package com.github.brkr.gandalf;

import com.github.brkr.gandalf.utils.RuleTest;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * @author :  berkergucur (brkr.gcr@gmail.com) - 07/03/16.
 */
public class MaximumRuleTest extends RuleTest {

    @Test
    public void testMaximumShouldReturnTrueWhenLengthEqualValueLength() throws Exception {
        Gandalf gandalf = new Gandalf();
        String testStr = "gandalf";
        setMockText(testStr);
        gandalf.load(mEditText).max(testStr.length());
        assertEquals(gandalf.shallIPass(), true);
    }

    @Test
    public void testMaximumShouldReturnTrueWhenLessThenLength() throws Exception {
        Gandalf gandalf = new Gandalf();
        String testStr = "abc";
        setMockText(testStr);
        gandalf.load(mEditText).max(4);
        assertEquals(gandalf.shallIPass(), true);
    }

    @Test
    public void testMinimumShouldReturnFalseWhenValueLengthGreaterThanLength() throws Exception {
        Gandalf gandalf = new Gandalf();
        String testStr = "U shall not pass!";
        setMockText(testStr);
        gandalf.load(mEditText).max(4);
        assertEquals(gandalf.shallIPass(), false);
    }

}


text:
"""Camera for map scrolling."""
from math import floor

from bearlibterminal import terminal

import ui.tileset as tileset

class Camera:
    """Crop and scroll the map.

    Due to map scrolling and zooming, there are three coordinates:
        1. Map coordinates (map_x or simply x)
        2. Camera shooting range coordinates (cam_x)
        3. Screen coordinates (scr_x)
    """

    def __init__(self, zoom=2, margin=2):
        """Set initial position and size."""
        self.topleft_x = 0
        self.topleft_y = 0
        self.set_zoom(zoom)
        self.margin = margin

    def set_zoom(self, zoom=2):
        """Set zoom and update properties."""
        # cap zoom value
        if 1 <= zoom <= 4:
            self.zoom = zoom
        elif zoom < 1:
            self.zoom = 1
        elif zoom > 4:
            self.zoom = 4

        cell_w = terminal.state(terminal.TK_CELL_WIDTH)

        tileset.resize_tiles(tileset.camera_target, cell_w * self.zoom)

        self.width = int(terminal.state(terminal.TK_WIDTH) / self.zoom)
        self.height = int(terminal.state(terminal.TK_HEIGHT) / self.zoom)

    def move_camera(self, trg_x, trg_y, game_map):
        """Move camera so that the player is centered on the terminal.

        Returns boolean whether or not camera actually moves.
        """
        # new camera coordinates (top-left corner of the screen relative to the map)
        # coordinates so that the target is at the center of the screen
        new_x = trg_x - int(self.width / 2)
        new_y = trg_y - int(self.height / 2)

        # make sure the camera doesn't see outside the map
        if new_x < - self.margin:
            new_x = - self.margin
        if new_y < - self.margin:
            new_y = - self.margin
        if new_x > game_map.width - self.width + self.margin:
            new_x = game_map.width - self.width + self.margin
        if new_y > game_map.height - self.height + self.margin:
            new_y = game_map.height - self.height + self.margin

        if new_x == self.topleft_x and new_y == self.topleft_y:
            return False  # comera didn't move

        self.topleft_x, self.topleft_y = new_x, new_y
        return True  # camera moved

    def map_to_cam_coord(self, map_x, map_y):
        """Convert game map coordinates to camera shooting range coordinates."""
        cam_x = (map_x - self.topleft_x)
        cam_y = (map_y - self.topleft_y)

        if 0 <= cam_x < self.width and 0 <= cam_y < self.height:
            return (cam_x, cam_y)

        return (None, None)  # if it's outside the view, return nothing

    def map_to_term_coord(self, map_x, map_y):
        """Convert game map coordinates to terminal screen coordinates."""
        (cam_x, cam_y) = self.map_to_cam_coord(map_x, map_y)

        if cam_x is not None:
            return (cam_x * self.zoom, cam_y * self.zoom)

        return (None, None)  # if outside of the camera (or screen), return nothing

    def term_to_map_coord(self, scr_x, scr_y):
        """Convert terminal screen coordinates to game map coordinates."""
        cam_x = floor(scr_x / self.zoom)
        cam_y = floor(scr_y / self.zoom)

        map_x = self.topleft_x + cam_x
        map_y = self.topleft_y + cam_y

        return (map_x, map_y)

    def term_to_cam_coord(self, scr_x, scr_y):
        """Convert terminal screen coordinates to camera shooting range coordinates."""
        cam_x = floor(scr_x / self.zoom) * self.zoom
        cam_y = floor(scr_y / self.zoom) * self.zoom

        return (cam_x, cam_y)


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright 2012 Jan Kühle

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp">
        <!-- Mileage -->
        <android.support.design.widget.TextInputLayout
            android:id="@+id/edt_mileage_input_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_toLeftOf="@+id/spn_distance_entry_mode"
            android:layout_toStartOf="@+id/spn_distance_entry_mode"
            android:baselineAlignedChildIndex="0">
            <EditText
                android:id="@+id/edt_mileage"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="number" />
        </android.support.design.widget.TextInputLayout>
        <Spinner
            android:id="@+id/spn_distance_entry_mode"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/edt_mileage_input_layout"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_marginLeft="16dp"
            android:layout_marginStart="16dp"/>
        <!-- Volume -->
        <android.support.design.widget.TextInputLayout
            android:id="@+id/edt_volume_input_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/edt_mileage_input_layout"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_toLeftOf="@+id/spn_fuel_type"
            android:layout_toStartOf="@+id/spn_fuel_type"
            android:baselineAlignedChildIndex="0">
            <EditText
                android:id="@+id/edt_volume"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/hint_volume"
                android:inputType="number|numberDecimal" />
        </android.support.design.widget.TextInputLayout>
        <Spinner
            android:id="@+id/spn_fuel_type"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/edt_volume_input_layout"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_marginLeft="16dp"
            android:layout_marginStart="16dp"/>
        <!-- Partial -->
        <CheckBox
            android:id="@+id/chk_partial"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:layout_below="@id/edt_volume_input_layout"
            android:text="@string/label_partial" />
        <!-- Price -->
        <android.support.design.widget.TextInputLayout
            android:id="@+id/edt_price_input_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/chk_partial">
            <EditText
                android:id="@+id/edt_price"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/hint_price"
                android:inputType="number|numberDecimal"/>
        </android.support.design.widget.TextInputLayout>
        <!-- Section: Advanced -->
        <TextView
            style="@style/AppWidget.SectionHeader"
            android:id="@+id/txt_section_advanced"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/edt_price_input_layout"
            android:text="@string/section_advanced" />
        <!-- Date -->
        <android.support.design.widget.TextInputLayout
            android:id="@+id/edt_date_input_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/txt_section_advanced"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_toLeftOf="@+id/edt_time_input_layout"
            android:layout_toStartOf="@+id/edt_time_input_layout">
            <EditText
                android:id="@+id/edt_date"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/hint_date" />
        </android.support.design.widget.TextInputLayout>
        <android.support.design.widget.TextInputLayout
            android:id="@+id/edt_time_input_layout"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/edt_date_input_layout"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_marginLeft="16dp"
            android:layout_marginStart="16dp">
            <EditText
                android:id="@+id/edt_time"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/hint_time" />
        </android.support.design.widget.TextInputLayout>
        <!-- Note -->
        <android.support.design.widget.TextInputLayout
            android:id="@+id/edt_note_input_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/edt_date_input_layout">
            <EditText
                android:id="@+id/edt_note"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/hint_note_optional"
                android:inputType="text|textMultiLine" />
        </android.support.design.widget.TextInputLayout>
        <!-- Car -->
        <TextView
            style="@style/AppWidget.FloatingSpinnerLabel"
            android:id="@+id/txt_label_car"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/edt_note_input_layout"
            android:text="@string/label_car" />
        <Spinner
            android:id="@+id/spn_car"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:layout_below="@id/txt_label_car"/>
    </RelativeLayout>
</ScrollView>


text:
using System;

using FluentMigrator.Expressions;
using FluentMigrator.Runner.Conventions;
using FluentMigrator.Runner.Initialization;

using Microsoft.Extensions.Options;

namespace FluentMigrator.Runner.VersionTableInfo
{
    public class DefaultVersionTableMetaData : IVersionTableMetaData, ISchemaExpression
    {
        public DefaultVersionTableMetaData(IConventionSet conventionSet, IOptions<RunnerOptions> runnerOptions)
        {
#pragma warning disable 618
#pragma warning disable 612
            ApplicationContext = runnerOptions.Value.ApplicationContext;
#pragma warning restore 612
#pragma warning restore 618
            conventionSet.SchemaConvention?.Apply(this);
        }

        [Obsolete("Use dependency injection")]
        public DefaultVersionTableMetaData()
            : this(string.Empty)
        {
        }

        [Obsolete("Use dependency injection")]
        public DefaultVersionTableMetaData(string schemaName)
        {
            // ReSharper disable once VirtualMemberCallInConstructor
            SchemaName = schemaName ?? string.Empty;
        }

        ///
        /// Provides access to ApplicationContext object.
        ///
        /// <remarks>
        /// ApplicationContext value is set by FluentMigrator immediately after instantiation of a class
        /// implementing IVersionTableMetaData and before any of properties of IVersionTableMetaData
        /// is called. Properties can use ApplicationContext value to implement context-depending logic.
        /// </remarks>
        [Obsolete("Use dependency injection to get data using your own services")]
        public object ApplicationContext { get; set; }

        public virtual string SchemaName { get; set; }

        public virtual string TableName => "VersionInfo";

        public virtual string ColumnName => "Version";

        public virtual string UniqueIndexName => "UC_Version";

        public virtual string AppliedOnColumnName => "AppliedOn";

        public virtual string DescriptionColumnName => "Description";

        public virtual bool OwnsSchema => true;
    }
}


text:
name: � Bug Report
about: If something isn't working as expected �.
labels: "Status: Untriaged"
---

# Description

Briefly describe the issue

# ChefDK Version

Tell us which version of the ChefDK you are running. Run `chef --version` to display the version.

# Platform Version

Tell us which operating system distribution and version ChefDK is running on.

# Replication Case

Tell us what steps to take to replicate your problem. See [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) for information on how to create a good replication case.

# Stacktrace

Please include the stacktrace.out output or link to a gist of it, if there is one.

## NOTE: CHEFDK BUGS ONLY

This issue tracker is for the code contained within this repo -- `chefdk`.

- [Server issues](https://github.com/chef/chef-server/issues/new)
- [Chef-client issues](https://github.com/chef/chef/issues/new)
- Cookbook Issues (see the <https://github.com/chef-cookbooks> repos or search [Supermarket](https://supermarket.chef.io) or GitHub/Google)


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.4/15.4.4/15.4.4.20/15.4.4.20-9-c-iii-19.js
 * @description Array.prototype.filter return value of callbackfn is a Boolean object
 */

function testcase() {

        function callbackfn(val, idx, obj) {
            return new Boolean();
        }

        var newArr = [11].filter(callbackfn);
        return newArr.length === 1 && newArr[0] === 11;
    }
runTestCase(testcase);


text:
package rspactors.core

import akka.actor._
import scala.collection.mutable.Queue
import rdftools.rdf.Triple

class OutputStreamActor(maxSize:Int) extends Actor {

 val queue=new Queue[Triple]()
 val mappingQueue=new Queue[Map[String,String]]()

 def receive = {
   case Push(data) =>
     println("got this "+data)
     queue+=(data)
     if (queue.size>maxSize)
       queue.dequeue

   case PushMapping(data)=>
     mappingQueue+=(data)
     if (mappingQueue.size>maxSize)
       mappingQueue.dequeue

   case Last(n) =>
     println("asking last")

     val ddd=(mappingQueue.takeRight(n)).toIterator.mkString(",")
     println("tobias "+ddd)
     sender ! ddd

   case t:Triple=>
     println(t)

   case s:Seq[Seq[Triple]]=>
     println("dribilin "+s.size)
     println(s.map{ss=>ss.mkString(",")}.mkString("\n"))
  }

}

case class Push(t:Triple)

case class PushMapping(m:Map[String,String])
case class Last(n:Int)


text:
'use strict';

/**
 * @ngdoc object
 * @name ng.$document
 * @requires $window
 *
 * @description
 * Это {@link angular.element jQuery (lite)}-обертка, ссылающаяся на элемент браузера `window.document`.
 */
function $DocumentProvider(){
  this.$get = ['$window', function(window){
    return jqLite(window.document);
  }];
}


text:
<?php

class ValIng extends \Exception {}
/**
  * @version $Id$
**/

class Ingredient
{
    protected $item;
    protected $amount;
    protected $unit;

    public static function initFromStdClass($std)
    {
        $instance = new self;
        $instance->item = $std->item;
        $instance->amount = $std->amount; // todo add some sanity check
        $instance->unit = $std->unit;
        return $instance;
    }

    public function getItem()
    {
        return $this->item;
    }

    public function getAmount()
    {
        return $this->amount;
    }

    public function getUnit()
    {
        return $this->unit;
    }
}


text:
<?php
$this->import(
  'jquery.js', 'jquery-ui.js', 'js.cookie.js',
  'jivoo/console/console.js', 'jivoo/console/tools.css'
);
?>

<?php echo tr('Development'); ?>

        <input type="checkbox" class="jivoo-devbar-fade"> <?php echo tr('Fade'); ?>

        <input type="checkbox" class="jivoo-devbar-hide"> <?php echo tr('Hide'); ?>


text:
package ast

// TranslationUnitDecl is node represents a translation unit declaration.
type TranslationUnitDecl struct {
	Addr       Address
	ChildNodes []Node
}

func parseTranslationUnitDecl(line string) *TranslationUnitDecl {
	groups := groupsFromRegex("<(?P<position>.*)> <(?P<position2>.*)>", line)

	return &TranslationUnitDecl{
		Addr:       ParseAddress(groups["address"]),
		ChildNodes: []Node{},
	}
}

// AddChild adds a new child node. Child nodes can then be accessed with the
// Children attribute.
func (n *TranslationUnitDecl) AddChild(node Node) {
	n.ChildNodes = append(n.ChildNodes, node)
}

// Address returns the numeric address of the node. See the documentation for
// the Address type for more information.
func (n *TranslationUnitDecl) Address() Address {
	return n.Addr
}

// Children returns the child nodes. If this node does not have any children or
// this node does not support children it will always return an empty slice.
func (n *TranslationUnitDecl) Children() []Node {
	return n.ChildNodes
}

// Position returns the position in the original source code.
func (n *TranslationUnitDecl) Position() Position {
	return Position{}
}


text:
@implementation FLWsdlCodeMethod

+ (id) wsdlCodeMethod:(NSString*) methodName methodReturnType:(NSString*) returnType {

    FLWsdlCodeMethod* method = FLAutorelease([[[self class] alloc] init]);
    method.name = methodName;

    if(FLStringIsNotEmpty(returnType)) {
        method.returnType = returnType;
    }

    return method;
}

- (void) setName:(NSString*) name {
    [super setName:FLDeleteNamespacePrefix(name)];
    FLConfirmStringIsNotEmptyWithComment(self.name, @"method name cannot be empty");
}

- (void) setReturnType:(NSString*) returnType {
    [super setReturnType:FLDeleteNamespacePrefix(returnType)];
}

@end


text:
#ifndef WEATHERENGINETEST_H
#define WEATHERENGINETEST_H

#include <QObject>

#include <KIO/NetAccess>
#include <KIO/Job>
#include <Plasma/DataEngine>

class WeatherEngineTest : public QObject
{
	Q_OBJECT
public:
	WeatherEngineTest( QObject * parent = NULL );
	~WeatherEngineTest();

	bool init();
	bool startTransferJob();

public Q_SLOTS:
	void dataUpdated(const QString & location, const Plasma::DataEngine::Data & data );
	void slotData(KIO::Job * job, const QByteArray & data);
	void slotResult( KJob * job );

private:
	void updatePlaces( const QString & location, const QVariant & data );

	Plasma::DataEngine * m_pWeatherEngine;
};

#endif


text:
package com.intellij.ide.ui.customization;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.keymap.impl.ui.ActionsTreeUtil;
import com.intellij.openapi.keymap.impl.ui.Group;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.wm.ex.IdeFrameEx;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import consulo.logging.Logger;
import consulo.ui.image.Image;
import jakarta.inject.Singleton;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;

import javax.annotation.Nonnull;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * User: anna
 * Date: Jan 20, 2005
 */
@Singleton
@State(name = "com.intellij.ide.ui.customization.CustomActionsSchema", storages = @Storage("customization.xml"))
public class CustomActionsSchema implements JDOMExternalizable {
  @NonNls
  private static final String ACTIONS_SCHEMA = "custom_actions_schema";
  @NonNls
  private static final String ACTIVE = "active";
  @NonNls
  private static final String ELEMENT_ACTION = "action";
  @NonNls
  private static final String ATTRIBUTE_ID = "id";
  @NonNls
  private static final String ATTRIBUTE_ICON = "icon";

  private final Map<String, String> myIconCustomizations = new HashMap<String, String>();

  private ArrayList<ActionUrl> myActions = new ArrayList<ActionUrl>();

  private final HashMap<String, ActionGroup> myIdToActionGroup = new HashMap<String, ActionGroup>();

  private final List<Pair> myIdToNameList = new ArrayList<Pair>();

  @NonNls
  private static final String GROUP = "group";
  private static final Logger LOG = Logger.getInstance(CustomActionsSchema.class);

  public CustomActionsSchema() {
    myIdToNameList.add(new Pair(IdeActions.GROUP_MAIN_MENU, ActionsTreeUtil.MAIN_MENU_TITLE));
    myIdToNameList.add(new Pair(IdeActions.GROUP_MAIN_TOOLBAR, ActionsTreeUtil.MAIN_TOOLBAR));
    myIdToNameList.add(new Pair(IdeActions.GROUP_EDITOR_POPUP, ActionsTreeUtil.EDITOR_POPUP));
    myIdToNameList.add(new Pair(IdeActions.GROUP_EDITOR_GUTTER, "Editor Gutter Popup Menu"));
    myIdToNameList.add(new Pair(IdeActions.GROUP_EDITOR_TAB_POPUP, ActionsTreeUtil.EDITOR_TAB_POPUP));
    myIdToNameList.add(new Pair(IdeActions.GROUP_PROJECT_VIEW_POPUP, ActionsTreeUtil.PROJECT_VIEW_POPUP));
    myIdToNameList.add(new Pair(IdeActions.GROUP_SCOPE_VIEW_POPUP, "Scope View Popup Menu"));
    myIdToNameList.add(new Pair(IdeActions.GROUP_FAVORITES_VIEW_POPUP, ActionsTreeUtil.FAVORITES_POPUP));
    myIdToNameList.add(new Pair(IdeActions.GROUP_COMMANDER_POPUP, ActionsTreeUtil.COMMANDER_POPUP));
    myIdToNameList.add(new Pair(IdeActions.GROUP_J2EE_VIEW_POPUP, ActionsTreeUtil.J2EE_POPUP));
    myIdToNameList.add(new Pair(IdeActions.GROUP_NAVBAR_POPUP, "Navigation Bar"));
    myIdToNameList.add(new Pair("NavBarToolBar", "Navigation Bar Toolbar"));

    CustomizableActionGroupProvider.CustomizableActionGroupRegistrar registrar = new CustomizableActionGroupProvider.CustomizableActionGroupRegistrar() {
      @Override
      public void addCustomizableActionGroup(@Nonnull String groupId, @Nonnull String groupTitle) {
        myIdToNameList.add(new Pair(groupId, groupTitle));
      }
    };
    for (CustomizableActionGroupProvider provider : CustomizableActionGroupProvider.EP_NAME.getExtensions()) {
      provider.registerGroups(registrar);
    }
  }

  public static CustomActionsSchema getInstance() {
    return ServiceManager.getService(CustomActionsSchema.class);
  }

  public void addAction(ActionUrl url) {
    myActions.add(url);
    resortActions();
  }

  public ArrayList<ActionUrl> getActions() {
    return myActions;
  }

  public void setActions(final ArrayList<ActionUrl> actions) {
    myActions = actions;
    resortActions();
  }

  public void copyFrom(CustomActionsSchema result) {
    myIdToActionGroup.clear();
    myActions.clear();
    myIconCustomizations.clear();

    for (ActionUrl actionUrl : result.myActions) {
      final ActionUrl url = new ActionUrl(new ArrayList<String>(actionUrl.getGroupPath()), actionUrl.getComponent(), actionUrl.getActionType(),
                                          actionUrl.getAbsolutePosition());
      url.setInitialPosition(actionUrl.getInitialPosition());
      myActions.add(url);
    }
    resortActions();

    myIconCustomizations.putAll(result.myIconCustomizations);
  }

  private void resortActions() {
    Collections.sort(myActions, ActionUrlComparator.INSTANCE);
  }

  public boolean isModified(CustomActionsSchema schema) {
    final ArrayList<ActionUrl> storedActions = schema.getActions();
    if (ApplicationManager.getApplication().isUnitTestMode() && !storedActions.isEmpty()) {
      System.err.println("stored: " + storedActions.toString());
      System.err.println("actual: " + getActions().toString());
    }
    if (storedActions.size() != getActions().size()) {
      return true;
    }
    for (int i = 0; i < getActions().size(); i++) {
      if (!getActions().get(i).equals(storedActions.get(i))) {
        return true;
      }
    }
    if (schema.myIconCustomizations.size() != myIconCustomizations.size()) return true;
    for (String actionId : myIconCustomizations.keySet()) {
      if (!Comparing.strEqual(schema.getIconPath(actionId), getIconPath(actionId))) return true;
    }
    return false;
  }

  @Override
  public void readExternal(Element element) throws InvalidDataException {
    DefaultJDOMExternalizer.readExternal(this, element);
    Element schElement = element;
    final String activeName = element.getAttributeValue(ACTIVE);
    if (activeName != null) {
      for (Element toolbarElement : (Iterable<Element>)element.getChildren(ACTIONS_SCHEMA)) {
        for (Object o : toolbarElement.getChildren("option")) {
          if (Comparing.strEqual(((Element)o).getAttributeValue("name"), "myName") && Comparing.strEqual(((Element)o).getAttributeValue("value"), activeName)) {
            schElement = toolbarElement;
            break;
          }
        }
      }
    }
    for (Object groupElement : schElement.getChildren(GROUP)) {
      ActionUrl url = new ActionUrl();
      url.readExternal((Element)groupElement);
      myActions.add(url);
    }
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      System.err.println("read custom actions: " + myActions.toString());
    }
    readIcons(element);
  }

  @Override
  public void writeExternal(Element element) throws WriteExternalException {
    DefaultJDOMExternalizer.writeExternal(this, element);
    writeActions(element);
    writeIcons(element);
  }

  private void writeActions(Element element) throws WriteExternalException {
    for (ActionUrl group : myActions) {
      Element groupElement = new Element(GROUP);
      group.writeExternal(groupElement);
      element.addContent(groupElement);
    }
  }

  public AnAction getCorrectedAction(String id) {
    if (!myIdToNameList.contains(new Pair(id, ""))) {
      return ActionManager.getInstance().getAction(id);
    }
    if (myIdToActionGroup.get(id) == null) {
      for (Pair pair : myIdToNameList) {
        if (pair.first.equals(id)) {
          final ActionGroup actionGroup = (ActionGroup)ActionManager.getInstance().getAction(id);
          if (actionGroup != null) { //J2EE/Commander plugin was disabled
            myIdToActionGroup.put(id, CustomizationUtil.correctActionGroup(actionGroup, this, pair.second));
          }
        }
      }
    }
    return myIdToActionGroup.get(id);
  }

  public void resetMainActionGroups() {
    for (Pair pair : myIdToNameList) {
      final ActionGroup actionGroup = (ActionGroup)ActionManager.getInstance().getAction(pair.first);
      if (actionGroup != null) {
        myIdToActionGroup.put(pair.first, CustomizationUtil.correctActionGroup(actionGroup, this, pair.second));
      }
    }
  }

  public void fillActionGroups(DefaultMutableTreeNode root) {
    final ActionManager actionManager = ActionManager.getInstance();
    for (Pair pair : myIdToNameList) {
      final ActionGroup actionGroup = (ActionGroup)actionManager.getAction(pair.first);
      if (actionGroup != null) {
        root.add(ActionsTreeUtil.createNode(ActionsTreeUtil.createGroup(actionGroup, pair.second, null, null, true, null, false)));
      }
    }
  }

  public boolean isCorrectActionGroup(ActionGroup group, String defaultGroupName) {
    if (myActions.isEmpty()) {
      return false;
    }

    final String text = group.getTemplatePresentation().getText();
    if (!StringUtil.isEmpty(text)) {
      for (ActionUrl url : myActions) {
        if (url.getGroupPath().contains(text) || url.getGroupPath().contains(defaultGroupName)) {
          return true;
        }
        if (url.getComponent() instanceof Group) {
          final Group urlGroup = (Group)url.getComponent();
          String id = urlGroup.getName() != null ? urlGroup.getName() : urlGroup.getId();
          if (id == null || id.equals(text) || id.equals(defaultGroupName)) {
            return true;
          }
        }
      }
      return false;
    }
    return true;
  }

  public List<ActionUrl> getChildActions(final ActionUrl url) {
    ArrayList<ActionUrl> result = new ArrayList<ActionUrl>();
    final ArrayList<String> groupPath = url.getGroupPath();
    for (ActionUrl actionUrl : myActions) {
      int index = 0;
      if (groupPath.size() <= actionUrl.getGroupPath().size()) {
        while (index < groupPath.size()) {
          if (!Comparing.equal(groupPath.get(index), actionUrl.getGroupPath().get(index))) {
            break;
          }
          index++;
        }
        if (index == groupPath.size()) {
          result.add(actionUrl);
        }
      }
    }
    return result;
  }

  public void removeIconCustomization(String actionId) {
    myIconCustomizations.remove(actionId);
  }

  public void addIconCustomization(String actionId, String iconPath) {
    myIconCustomizations.put(actionId, iconPath != null ? FileUtil.toSystemIndependentName(iconPath) : null);
  }

  public String getIconPath(String actionId) {
    final String path = myIconCustomizations.get(actionId);
    return path == null ? "" : path;
  }

  private void readIcons(Element parent) {
    for (Object actionO : parent.getChildren(ELEMENT_ACTION)) {
      Element action = (Element)actionO;
      final String actionId = action.getAttributeValue(ATTRIBUTE_ID);
      final String iconPath = action.getAttributeValue(ATTRIBUTE_ICON);
      if (actionId != null) {
        myIconCustomizations.put(actionId, iconPath);
      }
    }
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        initActionIcons();
      }
    });
  }

  private void writeIcons(Element parent) {
    for (String actionId : myIconCustomizations.keySet()) {
      Element action = new Element(ELEMENT_ACTION);
      action.setAttribute(ATTRIBUTE_ID, actionId);
      String icon = myIconCustomizations.get(actionId);
      if (icon != null) {
        action.setAttribute(ATTRIBUTE_ICON, icon);
      }
      parent.addContent(action);
    }
  }

  private void initActionIcons() {
    ActionManager actionManager = ActionManager.getInstance();
    for (String actionId : myIconCustomizations.keySet()) {
      final AnAction anAction = actionManager.getAction(actionId);
      if (anAction != null) {
        Image icon;
        final String iconPath = myIconCustomizations.get(actionId);
        if (iconPath != null && new File(FileUtil.toSystemDependentName(iconPath)).exists()) {
          try {
            icon = Image.fromUrl(VfsUtil.convertToURL(VfsUtil.pathToUrl(iconPath)));
          }
          catch (IOException e) {
            icon = AllIcons.Toolbar.Unknown;

            LOG.warn(e);
          }
        }
        else {
          icon = AllIcons.Toolbar.Unknown;
        }
        if (anAction.getTemplatePresentation() != null) {
          anAction.getTemplatePresentation().setIcon(icon);
          anAction.setDefaultIcon(false);
        }
      }
    }
    final IdeFrameEx frame = WindowManagerEx.getInstanceEx().getIdeFrame(null);
    if (frame != null) {
      frame.updateView();
    }
  }

  private static class Pair {
    String first;
    String second;

    public Pair(final String first, final String second) {
      this.first = first;
      this.second = second;
    }

    @Override
    public int hashCode() {
      return first.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
      return obj instanceof Pair && first.equals(((Pair)obj).first);
    }
  }

  private static class ActionUrlComparator implements Comparator<ActionUrl> {
    public static ActionUrlComparator INSTANCE = new ActionUrlComparator();
    private static final int DELETED = 1;
    private static final int ADDED = 2;

    @Override
    public int compare(ActionUrl u1, ActionUrl u2) {
      final int w1 = getEquivalenceClass(u1);
      final int w2 = getEquivalenceClass(u2);
      if (w1 != w2) {
        return w1 - w2; // deleted < added < others
      }
      if (w1 == DELETED) {
        return u2.getAbsolutePosition() - u1.getAbsolutePosition(); // within DELETED equivalence class urls with greater position go first
      }
      return u1.getAbsolutePosition() - u2.getAbsolutePosition(); // within ADDED equivalence class: urls with lower position go first
    }

    private static int getEquivalenceClass(ActionUrl url) {
      switch (url.getActionType()) {
        case ActionUrl.DELETED:
          return 1;
        case ActionUrl.ADDED:
          return 2;
        default:
          return 3;
      }
    }
  }
}


text:
(function() {

$(document).ready(function(){
    $('.filters__filter').click(function() {
      filter = $(this);
      if( $(this).hasClass('is-active') ) return;
      parent = $(this).parent();
      previous = $(parent).find('.is-active');
      previous.removeClass('is-active');
      $(this).addClass('is-active');
      console.log(previous.data('filter'));
      $('#cards').removeClass( previous.data('filter') );
      $('#cards').addClass( $(this).data('filter') );
  });
});

})();


text: (window.webpackJsonp=window.webpackJsonp||[]).push([[2],{145:function(n,w,o){}}]);