text:
//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// index_scan_executor.cpp
//
// Identification: src/executor/index_scan_executor.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "executor/index_scan_executor.h"

#include <memory>
#include <numeric>
#include <utility>
#include <vector>

#include "catalog/manager.h"
#include "common/container_tuple.h"
#include "common/logger.h"
#include "concurrency/transaction_manager_factory.h"
#include "executor/executor_context.h"
#include "executor/logical_tile.h"
#include "executor/logical_tile_factory.h"
#include "expression/abstract_expression.h"
#include "gc/gc_manager_factory.h"
#include "index/index.h"
#include "planner/index_scan_plan.h"
#include "storage/data_table.h"
#include "storage/masked_tuple.h"
#include "storage/tile_group.h"
#include "storage/tile_group_header.h"
#include "type/types.h"
#include "type/value.h"

namespace peloton {
namespace executor {

/**
 * @brief Constructor for indexscan executor.
 * @param node Indexscan node corresponding to this executor.
 */
IndexScanExecutor::IndexScanExecutor(const planner::AbstractPlan *node,
                                     ExecutorContext *executor_context)
    : AbstractScanExecutor(node, executor_context) {}

IndexScanExecutor::~IndexScanExecutor() {
  // Nothing to do here
}

/**
 * @brief Let base class Dinit() first, then do my job.
 * @return true on success, false otherwise.
 */
bool IndexScanExecutor::DInit() {
  auto status = AbstractScanExecutor::DInit();

  if (!status) return false;

  PL_ASSERT(children_.size() == 0);

  // Grab info from plan node and check it
  const planner::IndexScanPlan &node = GetPlanNode<planner::IndexScanPlan>();

  index_ = node.GetIndex();
  PL_ASSERT(index_ != nullptr);

  index_predicate_ = node.GetIndexPredicate();

  result_itr_ = START_OID;
  result_.clear();
  done_ = false;
  key_ready_ = false;

  column_ids_ = node.GetColumnIds();
  key_column_ids_ = node.GetKeyColumnIds();
  expr_types_ = node.GetExprTypes();
  values_ = node.GetValues();
  runtime_keys_ = node.GetRunTimeKeys();
  predicate_ = node.GetPredicate();
  left_open_ = node.GetLeftOpen();
  right_open_ = node.GetRightOpen();

  // This is for limit operation accelerate
  limit_ = node.GetLimit();
  limit_number_ = node.GetLimitNumber();
  limit_offset_ = node.GetLimitOffset();
  descend_ = node.GetDescend();

  if (runtime_keys_.size() != 0) {
    PL_ASSERT(runtime_keys_.size() == values_.size());

    if (!key_ready_) {
      values_.clear();

      for (auto expr : runtime_keys_) {
        auto value = expr->Evaluate(nullptr, nullptr, executor_context_);
        LOG_TRACE("Evaluated runtime scan key: %s", value.GetInfo().c_str());
        values_.push_back(value.Copy());
      }

      key_ready_ = true;
    }
  }

  table_ = node.GetTable();

  // PAVLO (2017-01-05): This seems unnecessary and a waste of time
  if (table_ != nullptr) {
    full_column_ids_.resize(table_->GetSchema()->GetColumnCount());
    std::iota(full_column_ids_.begin(), full_column_ids_.end(), 0);
  }

  return true;
}

/**
 * @brief Creates logical tile(s) after scanning index.
 * @return true on success, false otherwise.
 */
bool IndexScanExecutor::DExecute() {
  LOG_TRACE("Index Scan executor :: 0 child");

  if (!done_) {
    if (index_->GetIndexType() == IndexConstraintType::PRIMARY_KEY) {
      auto status = ExecPrimaryIndexLookup();
      if (status == false) return false;
    } else {
      auto status = ExecSecondaryIndexLookup();
      if (status == false) return false;
    }
  }
  // Already performed the index lookup
  PL_ASSERT(done_);

  while (result_itr_ < result_.size()) {  // Avoid returning empty tiles
    if (result_[result_itr_]->GetTupleCount() == 0) {
      result_itr_++;
      continue;
    } else {
      LOG_TRACE("Information %s", result_[result_itr_]->GetInfo().c_str());
      SetOutput(result_[result_itr_]);
      result_itr_++;
      return true;
    }

  }  // end while

  return false;
}

bool IndexScanExecutor::ExecPrimaryIndexLookup() {
  PL_ASSERT(!done_);

  std::vector<ItemPointer *> tuple_location_ptrs;

  // Grab info from plan node
  bool acquire_owner = GetPlanNode<planner::AbstractScan>().IsForUpdate();

  PL_ASSERT(index_->GetIndexType() == IndexConstraintType::PRIMARY_KEY);

  if (0 == key_column_ids_.size()) {
    index_->ScanAllKeys(tuple_location_ptrs);
  } else {
    // Limit clause accelerate
    if (limit_) {
      // invoke index scan limit
      if (!descend_) {
        LOG_TRACE("ASCENDING SCAN LIMIT in Primary Index");
        index_->ScanLimit(values_, key_column_ids_, expr_types_,
                          ScanDirectionType::FORWARD, tuple_location_ptrs,
                          &index_predicate_.GetConjunctionList()[0],
                          limit_number_, limit_offset_);
      } else {
        LOG_TRACE("DESCENDING SCAN LIMIT in Primary Index");
        index_->ScanLimit(values_, key_column_ids_, expr_types_,
                          ScanDirectionType::BACKWARD, tuple_location_ptrs,
                          &index_predicate_.GetConjunctionList()[0],
                          limit_number_, limit_offset_);

        LOG_TRACE("1-Result size is %lu", result_.size());
      }
    }
    // Normal SQL (without limit)
    else {
      LOG_TRACE("Index Scan in Primary Index");
      index_->Scan(values_, key_column_ids_, expr_types_,
                   ScanDirectionType::FORWARD, tuple_location_ptrs,
                   &index_predicate_.GetConjunctionList()[0]);
    }

    LOG_TRACE("tuple_location_ptrs:%lu", tuple_location_ptrs.size());
  }

  if (tuple_location_ptrs.size() == 0) {
    LOG_TRACE("no tuple is retrieved from index.");
    return false;
  }

  auto &transaction_manager =
      concurrency::TransactionManagerFactory::GetInstance();

  auto current_txn = executor_context_->GetTransaction();
  auto &manager = catalog::Manager::GetInstance();
  std::vector<ItemPointer> visible_tuple_locations;
  std::map<oid_t, std::vector<oid_t>> visible_tuples;

#ifdef LOG_TRACE_ENABLED
  int num_tuples_examined = 0;
#endif

  // for every tuple that is found in the index.
  for (auto tuple_location_ptr : tuple_location_ptrs) {
    ItemPointer tuple_location = *tuple_location_ptr;
    auto tile_group = manager.GetTileGroup(tuple_location.block);
    auto tile_group_header = tile_group.get()->GetHeader();
    size_t chain_length = 0;

#ifdef LOG_TRACE_ENABLED
    num_tuples_examined++;
#endif

    // the following code traverses the version chain until a certain visible
    // version is found.
    // we should always find a visible version from a version chain.
    while (true) {
      ++chain_length;

      auto visibility = transaction_manager.IsVisible(
          current_txn, tile_group_header, tuple_location.offset);

      // if the tuple is deleted
      if (visibility == VisibilityType::DELETED) {
        LOG_TRACE("encounter deleted tuple: %u, %u", tuple_location.block,
                  tuple_location.offset);
        break;
      }
      // if the tuple is visible.
      else if (visibility == VisibilityType::OK) {
        LOG_TRACE("perform read: %u, %u", tuple_location.block,
                  tuple_location.offset);

        bool eval = true;
        // if having predicate, then perform evaluation.
        if (predicate_ != nullptr) {
          LOG_TRACE("perform predicate evaluate");
          expression::ContainerTuple<storage::TileGroup> tuple(
              tile_group.get(), tuple_location.offset);
          eval =
              predicate_->Evaluate(&tuple, nullptr, executor_context_).IsTrue();
        }
        // if passed evaluation, then perform write.
        if (eval == true) {
          LOG_TRACE("perform read operation");
          auto res = transaction_manager.PerformRead(
              current_txn, tuple_location, acquire_owner);
          if (!res) {
            LOG_TRACE("read nothing");
            transaction_manager.SetTransactionResult(current_txn,
                                                     ResultType::FAILURE);
            return res;
          }
          // if perform read is successful, then add to visible tuple vector.
          visible_tuple_locations.push_back(tuple_location);
        }

        break;
      }
      // if the tuple is not visible.
      else {
        PL_ASSERT(visibility == VisibilityType::INVISIBLE);

        LOG_TRACE("Invisible read: %u, %u", tuple_location.block,
                  tuple_location.offset);

        bool is_acquired = (tile_group_header->GetTransactionId(
                                tuple_location.offset) == INITIAL_TXN_ID);
        bool is_alive =
            (tile_group_header->GetEndCommitId(tuple_location.offset) <=
             current_txn->GetReadId());
        if (is_acquired && is_alive) {
          // See an invisible version that does not belong to any one in the
          // version chain.
          // this means that some other transactions have modified the version
          // chain.
          // Wire back because the current version is expired. have to search
          // from scratch.
          tuple_location =
              *(tile_group_header->GetIndirection(tuple_location.offset));
          tile_group = manager.GetTileGroup(tuple_location.block);
          tile_group_header = tile_group.get()->GetHeader();
          chain_length = 0;
          continue;
        }

        ItemPointer old_item = tuple_location;
        tuple_location = tile_group_header->GetNextItemPointer(old_item.offset);

        // there must exist a visible version.
        if (tuple_location.IsNull()) {
          if (chain_length == 1) {
            break;
          }

          // in most cases, there should exist a visible version.
          // if we have traversed through the chain and still can not fulfill
          // one of the above conditions,
          // then return result_failure.
          transaction_manager.SetTransactionResult(current_txn,
                                                   ResultType::FAILURE);
          return false;
        }

        // search for next version.
        tile_group = manager.GetTileGroup(tuple_location.block);
        tile_group_header = tile_group.get()->GetHeader();
        continue;
      }
    }
    LOG_TRACE("Traverse length: %d\n", (int)chain_length);
  }
#ifdef LOG_TRACE_ENABLED
  LOG_TRACE("Examined %d tuples from index %s", num_tuples_examined,
            index_->GetName().c_str());
#endif

  LOG_TRACE("%ld tuples before pruning boundaries",
            visible_tuple_locations.size());

  // Check whether the boundaries satisfy the required condition
  CheckOpenRangeWithReturnedTuples(visible_tuple_locations);

  LOG_TRACE("%ld tuples after pruning boundaries",
            visible_tuple_locations.size());

  for (auto &visible_tuple_location : visible_tuple_locations) {
    visible_tuples[visible_tuple_location.block]
        .push_back(visible_tuple_location.offset);
  }

  // Construct a logical tile for each block
  for (auto tuples : visible_tuples) {
    auto &manager = catalog::Manager::GetInstance();
    auto tile_group = manager.GetTileGroup(tuples.first);

    std::unique_ptr<LogicalTile> logical_tile(LogicalTileFactory::GetTile());
    // Add relevant columns to logical tile
    logical_tile->AddColumns(tile_group, full_column_ids_);
    logical_tile->AddPositionList(std::move(tuples.second));
    if (column_ids_.size() != 0) {
      logical_tile->ProjectColumns(full_column_ids_, column_ids_);
    }

    result_.push_back(logical_tile.release());
  }

  done_ = true;

  LOG_TRACE("Result tiles : %lu", result_.size());

  return true;
}

bool IndexScanExecutor::ExecSecondaryIndexLookup() {
  LOG_TRACE("ExecSecondaryIndexLookup");
  PL_ASSERT(!done_);
  PL_ASSERT(index_->GetIndexType() != IndexConstraintType::PRIMARY_KEY);

  std::vector<ItemPointer *> tuple_location_ptrs;

  // Grab info from plan node
  bool acquire_owner = GetPlanNode<planner::AbstractScan>().IsForUpdate();

  if (0 == key_column_ids_.size()) {
    index_->ScanAllKeys(tuple_location_ptrs);
  } else {
    // Limit clause accelerate
    if (limit_) {
      // invoke index scan limit
      if (!descend_) {
        LOG_TRACE("ASCENDING SCAN LIMIT in Secondary Index");
        index_->ScanLimit(values_, key_column_ids_, expr_types_,
                          ScanDirectionType::FORWARD, tuple_location_ptrs,
                          &index_predicate_.GetConjunctionList()[0],
                          limit_number_, limit_offset_);
      } else {
        LOG_TRACE("DESCENDING SCAN LIMIT in Secondary Index");
        index_->ScanLimit(values_, key_column_ids_, expr_types_,
                          ScanDirectionType::BACKWARD, tuple_location_ptrs,
                          &index_predicate_.GetConjunctionList()[0],
                          limit_number_, limit_offset_);

        if (tuple_location_ptrs.size() == 0) {
          LOG_TRACE("2-Result size is %lu", tuple_location_ptrs.size());
        }
      }
    }
    // Normal SQL (without limit)
    else {
      LOG_TRACE("Index Scan in Primary Index");
      index_->Scan(values_, key_column_ids_, expr_types_,
                   ScanDirectionType::FORWARD, tuple_location_ptrs,
                   &index_predicate_.GetConjunctionList()[0]);
    }
  }

  if (tuple_location_ptrs.size() == 0) {
    LOG_TRACE("no tuple is retrieved from index.");
    return false;
  }

  auto &transaction_manager =
      concurrency::TransactionManagerFactory::GetInstance();

  auto current_txn = executor_context_->GetTransaction();

  std::vector<ItemPointer> visible_tuple_locations;
  std::map<oid_t, std::vector<oid_t>> visible_tuples;
  auto &manager = catalog::Manager::GetInstance();

  // Quickie Hack
  // Sometimes we can get the tuples we need in the same block if they
  // were inserted at the same time. So we'll record the last block that
  // we got for each tuple and check whether its the same to avoid having
  // to go back to the catalog each time.
  oid_t last_block = INVALID_OID;
  std::shared_ptr<storage::TileGroup> tile_group;
  storage::TileGroupHeader *tile_group_header = nullptr;

#ifdef LOG_TRACE_ENABLED
  int num_tuples_examined = 0;
  int num_blocks_reused = 0;
#endif

  for (auto tuple_location_ptr : tuple_location_ptrs) {
    ItemPointer tuple_location = *tuple_location_ptr;
    if (tuple_location.block != last_block) {
      tile_group = manager.GetTileGroup(tuple_location.block);
      tile_group_header = tile_group.get()->GetHeader();
    }
#ifdef LOG_TRACE_ENABLED
    else
      num_blocks_reused++;
    num_tuples_examined++;
#endif

    // the following code traverses the version chain until a certain visible
    // version is found.
    // we should always find a visible version from a version chain.
    // different from primary key index lookup, we have to compare the
    // secondary
    // key to guarantee the correctness of the result.
    size_t chain_length = 0;
    while (true) {
      ++chain_length;

      auto visibility = transaction_manager.IsVisible(
          current_txn, tile_group_header, tuple_location.offset);

      // if the tuple is deleted
      if (visibility == VisibilityType::DELETED) {
        LOG_TRACE("encounter deleted tuple: %u, %u", tuple_location.block,
                  tuple_location.offset);
        break;
      }
      // if the tuple is visible.
      else if (visibility == VisibilityType::OK) {
        LOG_TRACE("perform read: %u, %u", tuple_location.block,
                  tuple_location.offset);

        // Further check if the version has the secondary key
        expression::ContainerTuple<storage::TileGroup> candidate_tuple(
            tile_group.get(), tuple_location.offset);

        LOG_TRACE("candidate_tuple size: %s",
                  candidate_tuple.GetInfo().c_str());
        // Construct the key tuple
        auto &indexed_columns = index_->GetKeySchema()->GetIndexedColumns();
        storage::MaskedTuple key_tuple(&candidate_tuple, indexed_columns);

        // Compare the key tuple and the key
        if (index_->Compare(key_tuple, key_column_ids_, expr_types_, values_) ==
            false) {
          LOG_TRACE("Secondary key mismatch: %u, %u\n", tuple_location.block,
                    tuple_location.offset);
          break;
        }

        bool eval = true;
        // if having predicate, then perform evaluation.
        if (predicate_ != nullptr) {
          eval = predicate_->Evaluate(&candidate_tuple, nullptr,
                                      executor_context_).IsTrue();
        }
        // if passed evaluation, then perform write.
        if (eval == true) {
          auto res = transaction_manager.PerformRead(
              current_txn, tuple_location, acquire_owner);
          if (!res) {
            transaction_manager.SetTransactionResult(current_txn,
                                                     ResultType::FAILURE);
            LOG_TRACE("passed evaluation, but txn read fails");
            return res;
          }
          // if perform read is successful, then add to visible tuple vector.
          visible_tuple_locations.push_back(tuple_location);
          LOG_TRACE("passed evaluation, visible_tuple_locations size: %lu",
                    visible_tuple_locations.size());
        } else {
          LOG_TRACE("predicate evaluate fails");
        }

        break;
      }
      // if the tuple is not visible.
      else {
        PL_ASSERT(visibility == VisibilityType::INVISIBLE);

        LOG_TRACE("Invisible read: %u, %u", tuple_location.block,
                  tuple_location.offset);

        bool is_acquired = (tile_group_header->GetTransactionId(
                                tuple_location.offset) == INITIAL_TXN_ID);
        bool is_alive =
            (tile_group_header->GetEndCommitId(tuple_location.offset) <=
             current_txn->GetReadId());
        if (is_acquired && is_alive) {
          // See an invisible version that does not belong to any one in the
          // version chain.
          // this means that some other transactions have modified the version
          // chain.
          // Wire back because the current version is expired. have to search
          // from scratch.
          tuple_location =
              *(tile_group_header->GetIndirection(tuple_location.offset));
          tile_group = manager.GetTileGroup(tuple_location.block);
          tile_group_header = tile_group.get()->GetHeader();
          chain_length = 0;
          continue;
        }

        ItemPointer old_item = tuple_location;
        tuple_location = tile_group_header->GetNextItemPointer(old_item.offset);

        if (tuple_location.IsNull()) {
          // For an index scan on a version chain, the result should be one of
          // the following:
          //    (1) find a visible version
          //    (2) find a deleted version
          //    (3) find an aborted version with chain length equal to one
          if (chain_length == 1) {
            break;
          }

          // in most cases, there should exist a visible version.
          // if we have traversed through the chain and still can not fulfill
          // one of the above conditions,
          // then return result_failure.
          transaction_manager.SetTransactionResult(current_txn,
                                                   ResultType::FAILURE);
          return false;
        }

        // search for next version.
        tile_group = manager.GetTileGroup(tuple_location.block);
        tile_group_header = tile_group.get()->GetHeader();
      }
    }
    LOG_TRACE("Traverse length: %d\n", (int)chain_length);
  }
#ifdef LOG_TRACE_ENABLED
  LOG_TRACE("Examined %d tuples from index %s [num_blocks_reused=%d]",
            num_tuples_examined, index_->GetName().c_str(), num_blocks_reused);
#endif

  // Check whether the boundaries satisfy the required condition
  CheckOpenRangeWithReturnedTuples(visible_tuple_locations);

  for (auto &visible_tuple_location : visible_tuple_locations) {
    visible_tuples[visible_tuple_location.block]
        .push_back(visible_tuple_location.offset);
  }

  // Construct a logical tile for each block
  for (auto tuples : visible_tuples) {
    auto &manager = catalog::Manager::GetInstance();
    auto tile_group = manager.GetTileGroup(tuples.first);

    std::unique_ptr<LogicalTile> logical_tile(LogicalTileFactory::GetTile());
    // Add relevant columns to logical tile
    logical_tile->AddColumns(tile_group, full_column_ids_);
    logical_tile->AddPositionList(std::move(tuples.second));
    if (column_ids_.size() != 0) {
      logical_tile->ProjectColumns(full_column_ids_, column_ids_);
    }

    result_.push_back(logical_tile.release());
  }

  done_ = true;

  LOG_TRACE("Result tiles : %lu", result_.size());

  return true;
}

void IndexScanExecutor::CheckOpenRangeWithReturnedTuples(
    std::vector<ItemPointer> &tuple_locations) {
  while (left_open_) {
    LOG_TRACE("Range left open!");
    auto tuple_location_itr = tuple_locations.begin();

    if (tuple_location_itr == tuple_locations.end() ||
        CheckKeyConditions(*tuple_location_itr) == true)
      left_open_ = false;
    else
      tuple_locations.erase(tuple_location_itr);
  }

  while (right_open_) {
    LOG_TRACE("Range right open!");
    auto tuple_location_itr = tuple_locations.rbegin();

    if (tuple_location_itr == tuple_locations.rend() ||
        CheckKeyConditions(*tuple_location_itr) == true)
      right_open_ = false;
    else
      tuple_locations.pop_back();
  }
}

bool IndexScanExecutor::CheckKeyConditions(const ItemPointer &tuple_location) {
  // The size of these three arrays must be the same
  PL_ASSERT(key_column_ids_.size() == expr_types_.size());
  PL_ASSERT(expr_types_.size() == values_.size());

  LOG_TRACE("Examining key conditions for the returned tuple.");

  auto &manager = catalog::Manager::GetInstance();

  auto tile_group = manager.GetTileGroup(tuple_location.block);
  expression::ContainerTuple<storage::TileGroup> tuple(tile_group.get(),
                                                       tuple_location.offset);

  // This is the end of loop
  oid_t cond_num = key_column_ids_.size();

  // Go over each attribute in the list of comparison columns
  // The key_columns_ids, as the name shows, saves the key column ids that
  // have values and expression needs to be compared.

  for (oid_t i = 0; i < cond_num; i++) {
    // First retrieve the tuple column ID from the map, and then map
    // it to the column ID of index key
    oid_t tuple_key_column_id = key_column_ids_[i];

    // This the comparison right hand side operand
    const type::Value &rhs = values_[i];

    // Also retrieve left hand side operand using index key column ID
    type::Value val = (tuple.GetValue(tuple_key_column_id));
    const type::Value &lhs = val;

    // Expression type. We use this to interpret comparison result
    //
    // Possible results of comparison are: EQ, >, <
    const ExpressionType expr_type = expr_types_[i];

    // If the operation is IN, then use the boolean values comparator
    // that determines whether a value is in a list
    //
    // To make the procedure more uniform, we interpret IN as EQUAL
    // and NOT IN as NOT EQUAL, and react based on expression type below
    // accordingly
    /*if (expr_type == ExpressionType::COMPARE_IN) {
      bool bret = lhs.InList(rhs);

      if (bret == true) {
        diff = VALUE_COMPARE_EQUAL;
      } else {
        diff = VALUE_COMPARE_NO_EQUAL;
      }
    } else {
      diff = lhs.Compare(rhs);
    }

    LOG_TRACE("Difference : %d ", diff);*/
    if (lhs.CompareEquals(rhs) == type::CMP_TRUE) {
      switch (expr_type) {
        case ExpressionType::COMPARE_EQUAL:
        case ExpressionType::COMPARE_LESSTHANOREQUALTO:
        case ExpressionType::COMPARE_GREATERTHANOREQUALTO:
        case ExpressionType::COMPARE_IN:
          continue;

        case ExpressionType::COMPARE_NOTEQUAL:
        case ExpressionType::COMPARE_LESSTHAN:
        case ExpressionType::COMPARE_GREATERTHAN:
          return false;

        default:
          throw IndexException("Unsupported expression type : " +
                               ExpressionTypeToString(expr_type));
      }
    } else {
      if (lhs.CompareLessThan(rhs) == type::CMP_TRUE) {
        switch (expr_type) {
          case ExpressionType::COMPARE_NOTEQUAL:
          case ExpressionType::COMPARE_LESSTHAN:
          case ExpressionType::COMPARE_LESSTHANOREQUALTO:
            continue;

          case ExpressionType::COMPARE_EQUAL:
          case ExpressionType::COMPARE_GREATERTHAN:
          case ExpressionType::COMPARE_GREATERTHANOREQUALTO:
          case ExpressionType::COMPARE_IN:
            return false;

          default:
            throw IndexException("Unsupported expression type : " +
                                 ExpressionTypeToString(expr_type));
        }
      } else {
        if (lhs.CompareGreaterThan(rhs) == type::CMP_TRUE) {
          switch (expr_type) {
            case ExpressionType::COMPARE_NOTEQUAL:
            case ExpressionType::COMPARE_GREATERTHAN:
            case ExpressionType::COMPARE_GREATERTHANOREQUALTO:
              continue;

            case ExpressionType::COMPARE_EQUAL:
            case ExpressionType::COMPARE_LESSTHAN:
            case ExpressionType::COMPARE_LESSTHANOREQUALTO:
            case ExpressionType::COMPARE_IN:
              return false;

            default:
              throw IndexException("Unsupported expression type : " +
                                   ExpressionTypeToString(expr_type));
          }
        } else {
          // Since it is an AND predicate, we could directly return false
          return false;
        }
      }
    }
  }

  LOG_TRACE("Examination returning true.");

  return true;
}

// column_ids is the right predicate column id. For example,
// i_id = s_id, then s_id is column_ids
// But the passing value is the result (output) id. We need to transform it to
// physical id
void IndexScanExecutor::UpdatePredicate(
    const std::vector<oid_t> &column_ids,
    const std::vector<type::Value> &values) {
  // Update index predicate
  LOG_TRACE("values_ size %lu", values_.size());

  std::vector<oid_t> key_column_ids;

  PL_ASSERT(column_ids.size() <= column_ids_.size());
  // Get the real physical ids
  for (auto column_id : column_ids) {
    key_column_ids.push_back(column_ids_[column_id]);

    LOG_TRACE("Output id is %d---physical column id is %d", column_id,
              column_ids_[column_id]);
  }

  // Update values in index plan node
  PL_ASSERT(key_column_ids.size() == values.size());
  PL_ASSERT(key_column_ids_.size() == values_.size());

  // Find out the position (offset) where is key_column_id
  for (oid_t new_idx = 0; new_idx < key_column_ids.size(); new_idx++) {
    unsigned int current_idx = 0;
    for (; current_idx < values_.size(); current_idx++) {
      if (key_column_ids[new_idx] == key_column_ids_[current_idx]) {
        LOG_TRACE("Orignial is %d:%s", key_column_ids[new_idx],
                  values_[current_idx].GetInfo().c_str());
        LOG_TRACE("Changed to %d:%s", key_column_ids[new_idx],
                  values[new_idx].GetInfo().c_str());
        values_[current_idx] = values[new_idx];

        // There should not be two same columns. So when we find a column, we
        // should break the loop
        break;
      }
    }

    // If new value doesn't exist in current value list, add it.
    // For the current simple optimizer, since all the key column ids must be
    // initiated when creating index_scan_plan, we don't need to examine
    // whether
    // the passing column and value exist or not (they definitely exist). But
    // for the future optimizer, we probably change the logic. So we still
    // keep
    // the examine code here.
    if (current_idx == values_.size()) {
      LOG_TRACE("Add new column for index predicate:%u-%s",
                key_column_ids[new_idx], values[new_idx].GetInfo().c_str());

      // Add value
      values_.push_back(values[new_idx]);

      // Add column id
      key_column_ids_.push_back(key_column_ids[new_idx]);

      // Add column type.
      // TODO: We should add other types in the future
      expr_types_.push_back(ExpressionType::COMPARE_EQUAL);
    }
  }

  // Update the new value
  index_predicate_.GetConjunctionListToSetup()[0]
      .SetTupleColumnValue(index_.get(), key_column_ids, values);
}

void IndexScanExecutor::ResetState() {
  result_.clear();

  result_itr_ = START_OID;

  done_ = false;

  const planner::IndexScanPlan &node = GetPlanNode<planner::IndexScanPlan>();

  left_open_ = node.GetLeftOpen();

  right_open_ = node.GetRightOpen();
}

}  // namespace executor
}  // namespace peloton


text:
package widget;

import javax.swing.*;
import java.awt.image.*;
import java.awt.*;

public class PanelJudul extends JPanel
{
    private static final long serialVersionUID = 1L;
    private BufferedImage gradientImage;
    private BufferedImage ligthImage;
    private Color light;
    private Color dark;
    private Color black;
    private Color warna;

    public PanelJudul() {
        this.light = new Color(1.0f, 1.0f, 1.0f, 0.5f);
        this.dark = new Color(1.0f, 1.0f, 1.0f, 0.0f);
        this.black = Color.black;
        this.warna = new Color(34, 14, 85);
    }

    protected void paintComponent(final Graphics g) {
        super.paintComponent(g);
        this.setUpGradientImage();
        this.setUpLigthImage();
        if (this.isOpaque()) {
            g.drawImage(this.gradientImage, 0, 0, this.getWidth(), this.getHeight(), null);
            g.drawImage(this.ligthImage, 0, 0, this.getWidth(), this.getHeight() / 2, null);
        }
    }

    private void setUpGradientImage() {
        this.gradientImage = new BufferedImage(1, this.getHeight(), 2);
        final GradientPaint paint = new GradientPaint(0.0f, 0.0f, this.warna, 0.0f, this.getHeight(), this.black);
        final Graphics2D g = (Graphics2D)this.gradientImage.getGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setPaint(paint);
        g.fillRect(0, 0, 1, this.getHeight());
        g.dispose();
    }

    private void setUpLigthImage() {
        this.ligthImage = new BufferedImage(1, this.getHeight() / 2, 2);
        final GradientPaint paint = new GradientPaint(0.0f, 0.0f, this.light, 0.0f, this.getHeight(), this.dark);
        final Graphics2D g = (Graphics2D)this.ligthImage.getGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setPaint(paint);
        g.fillRect(0, 0, 1, this.getHeight() / 2);
        g.dispose();
    }
}

redpajama_set_name: RedPajamaGithub


text:
var Vehicle = function(){

}

Vehicle.prototype.drive = function () {
    console.log("driving...");
}

var Car = function(){

}

Car.prototype = Object.create(Vehicle.prototype); //the key for inheritance
Car.prototype.constructor = Car;


text:
with open('propvalue_vs_noise_per_resunit.csv') as csvpairs:
     maximum =0
     for line in csvpairs:
         newvalue = float(line.encode('utf-8').split(',')[1].strip())
         maximum = max(maximum,newvalue)
     print maximum


text:
<?php

/**
 * Define DocBlock
 */
class Meta_model extends CI_Model {
    public static $TBNAME="meta";
    public $id;//自增id
    public $seo_title;//标题
    public $seo_keywords;//关键字
    public $seo_description;//描述

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function get_metas()
    {
        $query = $this->db->get(self::$TBNAME);
        return $query->result_array();
    }

    public function insert_meta($seo_title,$seo_description,$seo_keywords="")
    {
        $this->seo_title = $seo_title;
        $this->seo_description = $seo_description;
        $this->seo_keywords = $seo_keywords;
        $this->db->insert(self::$TBNAME,$this);
        return $this->db->insert_id();
    }

    public function update_meta($seo_title,$seo_description,$seo_id)
    {
        $this->seo_title = $seo_title;
        $this->seo_description = $seo_description;
        $this->id = $seo_id;
        $this->db->where("id",$seo_id);
        $this->db->update(self::$TBNAME, $this);
    }

    public function get_meta($id)
    {
        $query = $this->db->get_where(self::$TBNAME,array("id"=>$id));
        return $query->row_array();
    }

}
?>


text:
Imports SistFoncreagro.BussinessEntities

Public Interface IFeriadoRepository

    Function GetFeriadoByFecha(ByVal _Fecha As Date) As Feriado
    Function GetFeriadoById(ByVal _Id As Int32) As Feriado
    Function GetAllFromFeriado() As List(Of Feriado)
    Sub DeleteFeriado(ByVal _id As Int32)
    Function SaveFeriado(ByVal _Feriado As Feriado) As Int32

End Interface


text:
'''OpenGL extension AMD.depth_clamp_separate

Automatically generated by the get_gl_extensions script, do not edit!
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions
from OpenGL.GL import glget
import ctypes
EXTENSION_NAME = 'GL_AMD_depth_clamp_separate'
_DEPRECATED = False
GL_DEPTH_CLAMP_NEAR_AMD = constant.Constant( 'GL_DEPTH_CLAMP_NEAR_AMD', 0x901E )
GL_DEPTH_CLAMP_FAR_AMD = constant.Constant( 'GL_DEPTH_CLAMP_FAR_AMD', 0x901F )

def glInitDepthClampSeparateAMD():
    '''Return boolean indicating whether this extension is available'''
    return extensions.hasGLExtension( EXTENSION_NAME )


text:
module Helpers
  module Volume
    def volume_env
      @volume_env ||=
        begin
          env = {
            "BB_MANUAL_MODE"             => "1",
            "LABEL"                      => vol_name,
            "BLOCKBRIDGE_VOLUME_NAME"    => vol_name,
            "BLOCKBRIDGE_VOLUME_REF"     => volume_ref_name,
            "BLOCKBRIDGE_CACHE_REF"      => vol_cache_ref,
            "BLOCKBRIDGE_HOSTINFO_REF"   => vol_hostinfo_ref,
            "BLOCKBRIDGE_VOLUME_PARAMS"  => volume_params_json,
            "BLOCKBRIDGE_VOLUME_PATH"    => vol_path,
            "BLOCKBRIDGE_MOUNT_PATH"     => mnt_path,
            "BLOCKBRIDGE_MODULES_EXPORT" => "1",
            "BLOCKBRIDGE_API_HOST"       => api_host,
            "BLOCKBRIDGE_API_URL"        => api_url,
          }

          # set volume params in environment
          vol_param_keys.each do |p|
            env[p.to_s.upcase] = volume_params[p].to_s if volume_params[p]
          end

          env
        end
      @volume_env["BLOCKBRIDGE_API_KEY"] = volume_access_token
      @volume_env["BLOCKBRIDGE_API_URL"] = api_url(@volume_env["BLOCKBRIDGE_API_KEY"])
      @volume_env["BLOCKBRIDGE_API_SU"]  = volume_su_user
      @volume_env["BLOCKBRIDGE_HOST_TRANSPORT"] = "--#{volume_params[:transport].downcase}" if volume_params[:transport]
      @volume_env.reject { |k, v| v.nil? }
    end

    def volume_params_json
      MultiJson.dump(volume_params)
    end

    def volume_cmd_exec(cmd, **params)
      cmd_exec(cmd, volume_env.merge(**params))
    end

    def vol_hostinfo_ref(name = nil)
      if name
        "docker-volumehostinfo-#{name}"
      else
        "docker-volumehostinfo-#{vol_name}"
      end
    end

    def vol_param_keys
      [
        :user,
        :capacity,
        :type,
        :iops,
        :attributes,
        :transport,
        :from_backup,
        :access_token,
      ]
    end

    def volume_ref_prefix
      "docker-volume-"
    end

    def volume_ref_name(name = nil)
      if name
        "#{volume_ref_prefix}#{name}"
      else
        "#{volume_ref_prefix}#{vol_name}"
      end
    end

    def volume_user
      return unless defined? params
      return if env['REQUEST_URI'].start_with? '/profile'
      return if user_access_token
      @volume_user ||=
        begin
          raise Blockbridge::NotFound, "No volume user found (and no default profile?); specify user or volume profile" if volume_params[:user].nil?
          user = bbapi(nil, nil).user_profile.list(login: volume_params[:user])&.first
          raise Blockbridge::NotFound, "Volume user #{volume_params[:user]} does not exist." unless user
          logger.info "#{vol_name} using user #{user.login} #{user.serial}"
          volume_params[:user]
        end
    end

    def volume_profile
      return unless defined? params
      return if env['REQUEST_URI'].start_with? '/profile'
      @volume_profile ||=
        begin
          name = params_profile || 'default'
          profile = profile_info(name).first
          raise "no profile found" if profile.nil?
          profile
        end
    rescue => e
      raise Blockbridge::NotFound, "Volume profile not found: #{params_profile}: #{e.message}" if params_profile
    end

    def volume_params_opts
      if (opts = params_opts)
        h = Hash.new.tap do |h|
          vol_param_keys.each do |p|
            h[p] = opts[p] if opts.has_key?(p)
          end
        end
        h
      end
    end

    def volume_params_find
      if volume_profile
        profile = volume_profile.reject { |k, v|
          k == :name ||
          (k == :user && user_access_token)
        }
        logger.info "#{vol_name} using volume info from profile #{volume_profile[:name]}: #{profile}"
        profile
      else
        {}
      end
    end

    def volume_params_augment(p)
      p[:name]   = vol_name
      p[:s3]     = params_obj_store if params_obj_store
      p[:backup] = params_backup if params_backup
      p.delete(:backup_name)
      p.delete(:from_backup)
    end

    def volume_params
      return unless defined? params
      return if env['REQUEST_URI'].start_with? '/profile'
      return if vol_cache_enabled?(vol_name)
      @volume_params ||=
        begin
          p = volume_def || volume_params_find
          p.merge! volume_params_opts if volume_params_opts
          volume_params_augment p
          logger.info "#{vol_name} using volume options: #{p}" unless volume_def
          p
        end
    end

    def volume_check_params
      return if vol_name.nil? && params_profile.nil?
      raise Blockbridge::NotFound, "No volume profile found matching #{params_profile}" if params_profile && volume_profile.nil?
      raise Blockbridge::NotFound, "No volume parameters specified and no default profile found" if volume_params.nil?
    end

    def volume_def
      return if vol_name.nil?
      @volume_def ||= volume_info.first
    end

    def volume_hosts(xmd)
      xmd[:tags].select { |t| t.include? 'docker-host' }.map { |t| t.gsub('docker-host:', '') }.join(',')
    end

    def volume_info_map(info, raw = false)
      info.map do |xmd|
        next unless (v = xmd[:data][:volume])
        v[:hosts] = volume_hosts(xmd) if volume_hosts(xmd).length > 0
        v[:deleted] = xmd[:data][:deleted] if xmd[:data][:deleted]
        unless raw
          v.delete(:scope_token)
        end
        v
      end
    end

    def volume_mapped_name(volume)
      name  = volume[:name]
      name += " [ #{volume[:hosts]} ]" if volume[:hosts]
      name
    end

    def volume_info(raw = false)
      if vol_name.nil?
        info = bbapi(nil, nil).xmd.list.select { |x| x[:ref].include? volume_ref_prefix }
      else
        info = [ bbapi(nil, nil).xmd.info(volume_ref_name) ]
      end
      volume_info_map(symbolize(info), raw)
    rescue Excon::Errors::NotFound, Excon::Errors::Gone, Blockbridge::NotFound, Blockbridge::Api::NotFoundError
      []
    end

    def volume_lookup(raw = false)
      info = volume_info(raw)
      raise Blockbridge::NotFound, "No volume named #{vol_name} found" if info.length == 0
      info
    end

    def volume_lookup_all
      volume_lookup
    rescue
      []
    end

    def volume_lookup_one(raw = false)
      volume_lookup(raw).first
    end

    def mnt_path_map(name = nil)
      return "" if name.nil?
      return "" unless mount_needed?(name)
      mnt_path(name)
    end

    def volume_list
      volume_info.select { |v| !v.has_key?(:deleted) }.map do |v|
        {
          Name:       v[:name],
          Mountpoint: mnt_path(v[:name])
        }
      end
    end

    def volume_get
      if vol_cache_enabled?(vol_name)
        v = vol_cache_get(vol_name)
        {
          Name:       params_name || v[:name],
          Mountpoint: mnt_path_map(v[:name]),
          Status:     v,
        }
      elsif (v = volume_lookup_one)
        {
          Name:       params_name || v[:name],
          Mountpoint: mnt_path_map(v[:name]),
          Status:     v,
        }
      end
    end

    def volume_exists?
      bbapi.vdisk.list(label: vol_name).first
    end

    def volume_create
      volume_check_params
      return if volume_exists?
      logger.info "#{vol_name} creating..."
      bb_vss_provision
      logger.info "#{vol_name} created"
    rescue
      volume_cmd_exec("bb_remove") rescue nil
      raise
    end

    def volume_clone
      logger.info "#{vol_name} cloning..."
      volume_cmd_exec("bb_clone")
      logger.info "#{vol_name} cloned"
    end

    def volume_bb_remove
      logger.info "#{vol_name} removing..."
      volume_cmd_exec("bb_remove")
      logger.info "#{vol_name} removed"
    end

    def volume_scoped
      case env['REQUEST_URI']
      when '/VolumeDriver.Unmount'
        true
      else
        false
      end
    end

    def volume_access_token
      return unless defined? params
      return if env['REQUEST_URI'].start_with? '/profile'
      # if otp specified, use session token. Either auth login to create one or use valid one.
      # - if can't SU, then it will fail. RETURN good error here saying can't SU
      #
      # if otp not specified, use user token. If not user token, use system + su
      # - if otp is required by user, it will fail. RETURN GOOD error here saying OTP required.
      #
      # - User has OTP enabled
      # - User has SU disabled
      # - User token should be created with respect OTP
      # - System token should be created with respect OTP
      if volume_scoped && (scope_token = volume_scope_token)
        token = scope_token
      elsif (otp = params_opts[:otp])
        if session_token_valid? otp
          token = get_session_token(otp)
        else
          if volume_params[:access_token]
            # login otp with volume access token
            bbapi(nil, volume_params[:access_token], otp)
          elsif user_access_token
            # login otp with user access token
            bbapi(nil, user_access_token, otp)
          else
            # login otp with system token and SU
            bbapi(volume_user, system_access_token, otp)
          end
          token = get_session_token(otp)
        end
      else
        if volume_params[:access_token]
          token = volume_params[:access_token]
        elsif user_access_token
          token = user_access_token
        else
          token = system_access_token
        end

        # login to check for otp required
        bbapi(nil, token)
      end
      token
    end

    def volume_su_user
      return if volume_access_token != system_access_token
      volume_user
    end

    def volume_scope_token
      volume = volume_info(true).first
      return volume[:scope_token]
    end

    def volume_start_async_remove
      params = {
        mode: 'patch',
        data: [ { op: 'add', path: '/deleted', value: Time.now.tv_sec } ]
      }
      bbapi(volume_user, volume_access_token).xmd.update(volume_ref_name, params)
      vol_cache_add(vol_name, volume_params.merge({deleted: true, env: volume_env}), true)
    end

    def volume_remove(opts = {})
      return if vol_cache_enabled?(vol_name)
      vol_info = volume_lookup_one(true)
      if bb_get_attached(vol_info[:name], vol_info[:user], vol_info[:scope_token])
        raise Blockbridge::VolumeInuse, "Volume cannot be removed; it is still in-use"
      end
      if opts[:async]
        volume_start_async_remove
      else
        volume_bb_remove
      end
    end

    def volume_freeze(vol)
      return unless mount_needed?
      cmd = "#{ns_exec_mnt} #{fsfreeze} --freeze #{mnt_path(vol[:name])}"
      volume_cmd_exec(cmd)
    end

    def volume_unfreeze(vol)
      return unless vol && mount_needed?
      cmd = "#{ns_exec_mnt} #{fsfreeze} --unfreeze #{mnt_path(vol[:name])}"
      volume_cmd_exec(cmd)
    end

    def volume_backup
      vol = volume_lookup_one(true)
      volume_freeze(vol)
      bb_backup_vol(vol)
    ensure
      volume_unfreeze(vol)
    end

    def volume_provision
      logger.info "#{vol_name} provisioning if needed..."
      volume_cmd_exec("bb_provision")
      logger.info "#{vol_name} provisioned"
    rescue Blockbridge::CommandError => e
      if e.message.include? "Query returned no results"
        cmd_res_dump(e.message)
        raise Blockbridge::ResourcesUnavailable, 'No resources available with requested provisioning parameters'
      end
      raise
    end

    def volume_mkfs
      begin
        volume_cmd_exec("bb_mkfs")
      rescue
        logger.info "#{vol_name} formatting..."
        volume_cmd_exec("bb_attach")
        volume_cmd_exec("bb_mkfs")
        logger.info "#{vol_name} formatted"
      ensure
        volume_cmd_exec("bb_detach")
      end
    rescue => e
      volume_unmount
      case e.message
      when /Disk not found/
        raise Blockbridge::NotFound, "Volume not found"
      else
        raise
      end
    end

    def volume_mount
      mount_ref
      logger.info "#{vol_name} mounting if needed..."
      volume_cmd_exec("bb_attach")
      volume_cmd_exec("bb_mkfs")
      volume_cmd_exec("bb_mount")
      logger.info "#{vol_name} mounted"
    rescue => e
      volume_unmount
      case e.message
      when /Disk not found/
        raise Blockbridge::NotFound, "Volume not found"
      else
        raise
      end
    end

    def volume_unmount
      mount_unref
      return if mount_needed?
      logger.info "#{vol_name} unmounting..."
      volume_cmd_exec("bb_unmount")
      while true
        begin
          volume_cmd_exec("bb_detach", BLOCKBRIDGE_DETACH_FAIL: "1")
          break
        rescue => e
          case e.message
          when /Could not logout of all requested sessions/
            logger.debug "#{vol_name} detach retrying: could not log out of session"
            EM::Synchrony.sleep 1
          else
            logger.debug "#{vol_name} detach failed: #{e.message}"
            break
          end
        end
      end
      volume_cmd_exec("bb_detach")
      logger.info "#{vol_name} unmounted"
    rescue => e
      case e.message
      when /Disk not found/
        raise Blockbridge::NotFound, "Volume not found"
      else
        raise
      end
    end
  end
end


text:
@echo off
setlocal
SET initialDir=%cd%
pushd %~dp0
SET STARTTITLE="Kitchen"
SET SPOON_CONSOLE=1
call Spoon.bat -main org.pentaho.di.kitchen.Kitchen -initialDir "%initialDir%"\ %*
popd


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="format-detection" content="telephone=no">

    <title>Fattoria il Milione - Residence e Agriturismo</title>
    <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700|Playfair+Display+SC:400,700|Playfair+Display:400,400i,700" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="css/main.css" media="screen" />

   <link href="./favicon.ico" rel="SHORTCUT ICON">

Tel.(+39) 055 23 23 211

info@fattoriailmilione.it

Fattoria il Milione

Residence e Agriturismo alle porte di Firenze

                Menu

Home page

La tenuta

Appartamenti

Gusti e sapori

Attività

Promozioni e offerte

Dove siamo

Contatti

Promozioni di stagione

Cogliere l'attimo

Verifica disponibilità

                <form class="booking-engine">
                  <input class="small" type="text" name="" />
                  <input class="small" type="text" name="" />
                  <input class="small" type="text" name="" />
                  <input class="small" type="text" name="" />
                  <input class="small" type="text" name="" />
                  <input type="submit" value="prenota" />
                </form>

                  Promozione

Degustazione della nuova annata

Phasellus a est quam. Vivamus id ornare mauris. Donec in lacus turpis. Nam non lorem eu nunc dictum luctus. Nulla sed orci vel odio volutpat volutpat eu eget orci. Donec ac velit auctor, interdum tortor nec, facilisis orci. In hendrerit egestas diam, nec suscipit ante sollicitudin ut. Integer aliquet mattis magna, et semper erat sollicitudin vitae. Praesent eu mauris lobortis, malesuada massa ut, vestibulum nisl. Maecenas vitae malesuada enim, sed euismod justo. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Suspendisse vehicula consequat ex non iaculis. Duis efficitur mattis pharetra.

                  Sed id nunc facilisis, placerat nibh eget, malesuada enim. Duis in venenatis nibh. Integer porta egestas urna, eu pharetra risus. Sed egestas nibh at ipsum pellentesque suscipit. Nulla sed tortor ultrices, accumsan dui sit amet, facilisis arcu. Donec feugiat tincidunt orci, pellentesque molestie diam sodales semper. Etiam condimentum mollis lacus, ac condimentum orci vestibulum at. Donec nisl mauris, egestas lobortis magna quis, venenatis congue quam. Nunc mattis felis ut eleifend suscipit.

                  Aliquam dui ex, feugiat id nulla ut, varius dapibus arcu. Etiam cursus nisl neque, in rhoncus enim maximus sit amet. Suspendisse elit justo, laoreet ac dictum in, ultrices eu nisi. Duis gravida vehicula mi. Morbi quis aliquet felis, eget dignissim nibh. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed lacinia tristique semper. Morbi finibus erat at massa malesuada consequat. Vivamus efficitur elementum enim quis interdum. Nullam in sem consequat, sollicitudin ante id, tempor elit. Donec pretium, quam at congue ultricies, eros lectus pretium massa, a euismod orci augue eget lacus. Curabitur accumsan sapien a nisi imperdiet, at luctus erat porttitor.

                    Precedente

                    Successiva

                  Promozione

Promozione del 1° Maggio

Promozione valida dal 24/05/2017 al 25/0672017

                  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus consectetuer lectus ut nisi.

                  Quisque vulputate neque non dolor. Sed sed odio. Sed placerat pretium mi. Nunc mi justo, sodales a, dignissim eu, placerat nec, elit. Mauris elit. Pellentesque cursus ante sit amet nunc.

                    Precedente

                    Successiva

                  Offerta

Escursioni guidate nei dintorni

Promozione valida dal 24/05/2017 al 25/0672017

                  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus consectetuer lectus ut nisi.

                  Quisque vulputate neque non dolor. Sed sed odio. Sed placerat pretium mi. Nunc mi justo, sodales a, dignissim eu, placerat nec, elit. Mauris elit. Pellentesque cursus ante sit amet nunc.

                    Precedente

                    Successiva

                  Offerta

La specialità della trattoria in offerta!

Promozione valida dal 24/05/2017 al 25/0672017

                  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus consectetuer lectus ut nisi.

                  Quisque vulputate neque non dolor. Sed sed odio. Sed placerat pretium mi. Nunc mi justo, sodales a, dignissim eu, placerat nec, elit. Mauris elit. Pellentesque cursus ante sit amet nunc.

                    Precedente

                    Successiva

                  Promozione

Degustazione della nuova annata

Promozione valida dal 24/05/2017 al 25/0672017

                  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus consectetuer lectus ut nisi.

                  Quisque vulputate neque non dolor. Sed sed odio. Sed placerat pretium mi. Nunc mi justo, sodales a, dignissim eu, placerat nec, elit. Mauris elit. Pellentesque cursus ante sit amet nunc.

                    Precedente

                    Successiva

                  Promozione

Promozione del 1° Maggio

Promozione valida dal 24/05/2017 al 25/0672017

                  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus consectetuer lectus ut nisi.

                  Quisque vulputate neque non dolor. Sed sed odio. Sed placerat pretium mi. Nunc mi justo, sodales a, dignissim eu, placerat nec, elit. Mauris elit. Pellentesque cursus ante sit amet nunc.

                    Precedente

                    Successiva

                  Offerta

Escursioni guidate nei dintorni

Promozione valida dal 24/05/2017 al 25/0672017

                  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus consectetuer lectus ut nisi.

                  Quisque vulputate neque non dolor. Sed sed odio. Sed placerat pretium mi. Nunc mi justo, sodales a, dignissim eu, placerat nec, elit. Mauris elit. Pellentesque cursus ante sit amet nunc.

                    Precedente

                    Successiva

                  Offerta

La specialità della trattoria in offerta!

Promozione valida dal 24/05/2017 al 25/0672017

                  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus consectetuer lectus ut nisi.

                  Quisque vulputate neque non dolor. Sed sed odio. Sed placerat pretium mi. Nunc mi justo, sodales a, dignissim eu, placerat nec, elit. Mauris elit. Pellentesque cursus ante sit amet nunc.

                    Precedente

                    Successiva

              Carica altro

© copyright 2017 Soc. Fattoria Il Milione S.r.l
P.IVA 05170900483

Tripadvisor

Instagram

Facebook

Contatti

Via di Giogoli 12 - Firenze

Tel.(+39) 055 23 23 211

info@fattoriailmilione.it

latitudine      43.73509829069459
longitudine  11.20864570140836

RICHIEDI MAGGIORI INFORMAZIONI

          <form>

                Nome
                <input type="text" name="" id="" />

                Cognome
                <input type="text" name="" id="" />

                Email
                <input type="email" name="" id="" />

                Messaggio
                <textarea name="" id="" /></textarea>

                <input type="checkbox" id="acconsento" name="acconsento" value="ok" />Acconsento al trattamento dei miei dati personali

                <input type="submit" id="isSubmitted" name="isSubmitted" value="Invia" class="submit" />

          </form>


text:
namespace seec {

class AugmentationCollection;

namespace cm {

class ProcessTrace;

class OPTSettings {
  seec::AugmentationCollection const &Augmentations;

  bool PyCrazyMode;

  std::string VariableName;

public:
  OPTSettings(seec::AugmentationCollection const &WithAugmentations)
  : Augmentations(WithAugmentations),
    PyCrazyMode(false),
    VariableName()
  {}

  seec::AugmentationCollection const &getAugmentations() const {
    return Augmentations;
  }

  bool getPyCrazyMode() const { return PyCrazyMode; }

  OPTSettings &setPyCrazyMode(bool const Value) {
    PyCrazyMode = Value;
    return *this;
  }

  std::string const &getVariableName() const { return VariableName; }

  OPTSettings &setVariableName(llvm::StringRef Value) {
    VariableName = Value;
    return *this;
  }
};

void PrintOnlinePythonTutor(seec::cm::ProcessTrace const &Trace,
                            OPTSettings const &Settings,
                            llvm::raw_ostream &Out);

void PrintOnlinePythonTutor(seec::cm::ProcessTrace const &Trace,
                            OPTSettings const &Settings);

} // namespace cm (in seec)

} // namespace seec

#endif // SEEC_CLANG_PRINTONLINEPYTHONTUTORTRACE_HPP


text:
/**
 * Select2 Greek translation.
 *
 * @author  Uriy Efremochkin <efremochkin@uriy.me>
 */
(function ($) {
    "use strict";

    $.extend($.fn.select2.defaults, {
        formatNoMatches: function () { return "Δεν βρέθηκαν αποτελέσματα"; },
        formatInputTooShort: function (input, min) { var n = min - input.length; return "Παρακαλούμε εισάγετε " + n + " περισσότερο" + (n > 1 ? "υς" : "") + " χαρακτήρ" + (n > 1 ? "ες" : "α"); },
        formatInputTooLong: function (input, max) { var n = input.length - max; return "Παρακαλούμε διαγράψτε " + n + " χαρακτήρ" + (n > 1 ? "ες" : "α"); },
        formatSelectionTooBig: function (limit) { return "Μπορείτε να επιλέξετε μόνο " + limit + " αντικείμεν" + (limit > 1 ? "α" : "ο"); },
        formatLoadMore: function (pageNumber) { return "Φόρτωση περισσότερων…"; },
        formatSearching: function () { return "Αναζήτηση…"; }
    });
})(jQuery);


text:
/*
 * =====================================================================================
 *
 *       Filename:  BtOgreExtras.h
 *
 *    Description:  Contains the Ogre Mesh to Bullet Shape converters.
 *
 *        Version:  1.0
 *        Created:  27/12/2008 01:45:56 PM
 *
 *         Author:  Nikhilesh (nikki)
 *
 * =====================================================================================
 */

// Modified by freshrat912@gmail.com (Akira Sakurai aka. TennenColl) to fit multithreading situations.

#ifndef _BtOgreShapes_H_
#define _BtOgreShapes_H_

#include <bullet/btBulletDynamicsCommon.h>
#include <Ogre/OgreVector3.h>
#include <Ogre/OgreQuaternion.h>

namespace BtOgre
{

typedef std::vector<Ogre::Vector3> Vector3Array;

//Converts from and to Bullet and Ogre stuff. Pretty self-explanatory.
class Convert
{
public:
	Convert() {};
	~Convert() {};

	static btQuaternion toBullet(const Ogre::Quaternion &q)
	{
		return btQuaternion(q.x, q.y, q.z, q.w);
	}
	static btVector3 toBullet(const Ogre::Vector3 &v)
	{
		return btVector3(v.x, v.y, v.z);
	}

	static Ogre::Quaternion toOgre(const btQuaternion &q)
	{
		return Ogre::Quaternion(q.w(), q.x(), q.y(), q.z());
	}
	static Ogre::Vector3 toOgre(const btVector3 &v)
	{
		return Ogre::Vector3(v.x(), v.y(), v.z());
	}
};

}

#endif


text:
package expr

import (
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
	"reflect"
	"strconv"
	"strings"
	"time"

	"github.com/golang/glog"
	lru "github.com/hashicorp/golang-lru"

	dpb "istio.io/api/mixer/v1/config/descriptor"
	"istio.io/istio/mixer/pkg/attribute"
	cfgpb "istio.io/istio/mixer/pkg/config/proto"
	"istio.io/istio/mixer/pkg/pool"
)

// This private variable is an extract from go/token
// it maps expression related token to its names
var tMap = map[token.Token]string{
	token.ILLEGAL: "ILLEGAL",

	token.EOF:     "EOF",
	token.COMMENT: "COMMENT",

	token.IDENT:  "IDENT",
	token.INT:    "INT",
	token.FLOAT:  "FLOAT",
	token.IMAG:   "IMAG",
	token.CHAR:   "CHAR",
	token.STRING: "STRING",

	token.ADD: "ADD",
	token.SUB: "SUB",
	token.MUL: "MUL",
	token.QUO: "QUO",
	token.REM: "REM",

	token.AND:  "AND",
	token.OR:   "OR",
	token.XOR:  "XOR",
	token.LAND: "LAND",
	token.LOR:  "LOR",

	token.EQL: "EQ",
	token.LSS: "LT",
	token.GTR: "GT",
	token.NOT: "NOT",

	token.NEQ: "NEQ",
	token.LEQ: "LEQ",
	token.GEQ: "GEQ",

	token.LBRACK: "INDEX",
}

var typeMap = map[token.Token]dpb.ValueType{
	token.INT:    dpb.INT64,
	token.FLOAT:  dpb.DOUBLE,
	token.CHAR:   dpb.STRING,
	token.STRING: dpb.STRING,
}

// Expression is a simplified expression AST
type Expression struct {
	// Oneof the following
	Const *Constant
	Var   *Variable
	Fn    *Function
}

// AttributeDescriptorFinder finds attribute descriptors.
type AttributeDescriptorFinder interface {
	// GetAttribute finds attribute descriptor in the vocabulary. returns nil if not found.
	GetAttribute(name string) *cfgpb.AttributeManifest_AttributeInfo
}

// EvalType Function an expression using fMap and attribute vocabulary. Returns the type that this expression evaluates to.
func (e *Expression) EvalType(attrs AttributeDescriptorFinder, fMap map[string]FuncBase) (valueType dpb.ValueType, err error) {
	if e.Const != nil {
		return e.Const.Type, nil
	}
	if e.Var != nil {
		ad := attrs.GetAttribute(e.Var.Name)
		if ad == nil {
			return valueType, fmt.Errorf("unknown attribute %s", e.Var.Name)
		}
		return ad.ValueType, nil
	}
	return e.Fn.EvalType(attrs, fMap)
}

// Eval returns value of the contained variable or error
func (v *Variable) Eval(attrs attribute.Bag) (interface{}, error) {
	if val, ok := attrs.Get(v.Name); ok {
		return val, nil
	}
	return nil, fmt.Errorf("unresolved attribute %s", v.Name)
}

// Eval evaluates the expression given an attribute bag and a function map.
func (e *Expression) Eval(attrs attribute.Bag, fMap map[string]FuncBase) (interface{}, error) {
	if e.Const != nil {
		return e.Const.Value, nil
	}
	if e.Var != nil {
		return e.Var.Eval(attrs)
	}

	fn := fMap[e.Fn.Name]
	if fn == nil {
		return nil, fmt.Errorf("unknown function: %s", e.Fn.Name)
	}
	// may panic
	return fn.(Func).Call(attrs, e.Fn.Args, fMap)
}

// String produces postfix version with all operators converted to function names
func (e *Expression) String() string {
	if e.Const != nil {
		return e.Const.String()
	}
	if e.Var != nil {
		return e.Var.String()
	}
	if e.Fn != nil {
		return e.Fn.String()
	}
	return "<nil>"
}

// newConstant converts literals recognized by parser (ie. int and string) to
// `dpb.ValueType`s, building a typed *Constant.
func newConstant(v string, vType dpb.ValueType) (*Constant, error) {
	var typedVal interface{}
	var err error
	switch vType {
	case dpb.INT64:
		if typedVal, err = strconv.ParseInt(v, 10, 64); err != nil {
			return nil, err
		}
	case dpb.DOUBLE:
		if typedVal, err = strconv.ParseFloat(v, 64); err != nil {
			return nil, err
		}
	default: // string
		// Several `dpb.ValueType`s are parsed as strings, so
		// they must be parse separately as those value types
		// (and the appropriate vType must be set).
		var unquoted string
		if unquoted, err = strconv.Unquote(v); err != nil {
			return nil, err
		}
		if typedVal, err = time.ParseDuration(unquoted); err == nil {
			vType = dpb.DURATION
			break
		}
		// TODO: add support for other dpb ValueTypes serialized
		// as string
		typedVal = unquoted
	}
	return &Constant{StrValue: v, Type: vType, Value: typedVal}, nil
}

// Constant models a typed constant.
type Constant struct {
	StrValue string
	Value    interface{}
	Type     dpb.ValueType
}

func (c *Constant) String() string {
	return c.StrValue
}

// Variable models a variable.
type Variable struct {
	Name string
}

func (v *Variable) String() string {
	return "$" + v.Name
}

// Function models a function with multiple parameters
// 1st arg can be thought of as the receiver.
type Function struct {
	Name string
	Args []*Expression
}

func (f *Function) String() string {
	w := pool.GetBuffer()
	w.WriteString(f.Name + "(")
	for idx, arg := range f.Args {
		if idx != 0 {
			w.WriteString(", ")
		}
		w.WriteString(arg.String())
	}
	w.WriteString(")")
	s := w.String()
	pool.PutBuffer(w)
	return s
}

// EvalType Function using fMap and attribute vocabulary. Return static or computed return type if all args have correct type.
func (f *Function) EvalType(attrs AttributeDescriptorFinder, fMap map[string]FuncBase) (valueType dpb.ValueType, err error) {
	fn := fMap[f.Name]
	if fn == nil {
		return valueType, fmt.Errorf("unknown function: %s", f.Name)
	}

	var idx int
	argTypes := fn.ArgTypes()

	if len(f.Args) < len(argTypes) {
		return valueType, fmt.Errorf("%s arity mismatch. Got %d arg(s), expected %d arg(s)", f, len(f.Args), len(argTypes))
	}

	var argType dpb.ValueType
	tmplType := dpb.VALUE_TYPE_UNSPECIFIED
	// check arg types with fn args
	for idx = 0; idx < len(f.Args) && idx < len(argTypes); idx++ {
		argType, err = f.Args[idx].EvalType(attrs, fMap)
		if err != nil {
			return valueType, err
		}
		expectedType := argTypes[idx]
		if expectedType == dpb.VALUE_TYPE_UNSPECIFIED {
			if tmplType == dpb.VALUE_TYPE_UNSPECIFIED {
				// all future args must be of this type.
				tmplType = argType
				continue
			}
			expectedType = tmplType
		}
		if argType != expectedType {
			return valueType, fmt.Errorf("%s arg %d (%s) typeError got %s, expected %s", f, idx+1, f.Args[idx], argType, expectedType)
		}
	}

	// TODO check if we have excess args, only works when Fn is Variadic

	retType := fn.ReturnType()
	if retType == dpb.VALUE_TYPE_UNSPECIFIED {
		// if return type is unspecified, you the discovered type
		retType = tmplType
	}

	return retType, nil
}

func process(ex ast.Expr, tgt *Expression) (err error) {
	switch v := ex.(type) {
	case *ast.UnaryExpr:
		tgt.Fn = &Function{Name: tMap[v.Op]}
		if err = processFunc(tgt.Fn, []ast.Expr{v.X}); err != nil {
			return
		}
	case *ast.BinaryExpr:
		tgt.Fn = &Function{Name: tMap[v.Op]}
		if err = processFunc(tgt.Fn, []ast.Expr{v.X, v.Y}); err != nil {
			return
		}
	case *ast.CallExpr:
		vfunc, found := v.Fun.(*ast.Ident)
		if !found {
			return fmt.Errorf("unexpected expression: %#v", v.Fun)
		}
		tgt.Fn = &Function{Name: vfunc.Name}
		if err = processFunc(tgt.Fn, v.Args); err != nil {
			return
		}
	case *ast.ParenExpr:
		if err = process(v.X, tgt); err != nil {
			return
		}
	case *ast.BasicLit:
		tgt.Const, err = newConstant(v.Value, typeMap[v.Kind])
		if err != nil {
			return
		}
	case *ast.Ident:
		// true and false are treated as identifiers by parser
		// we need to convert them into constants here
		lv := strings.ToLower(v.Name)
		if lv == "true" || lv == "false" {
			typedVal := true
			if lv == "false" {
				typedVal = false
			}
			tgt.Const = &Constant{StrValue: lv, Type: dpb.BOOL, Value: typedVal}
		} else {
			tgt.Var = &Variable{Name: v.Name}
		}
	case *ast.SelectorExpr:
		// a.b.c.d is a selector expression
		// normally one walks down a chain of objects
		// we have chosen an internally flat namespace, therefore
		// a.b.c.d if an identifer. converts
		// a.b.c.d --> $a.b.c.d
		// for selectorExpr length is guaranteed to be at least 2.
		var w []string
		if err = processSelectorExpr(v, &w); err != nil {
			return
		}
		ww := pool.GetBuffer()
		ww.WriteString(w[len(w)-1])
		for idx := len(w) - 2; idx >= 0; idx-- {
			ww.WriteString("." + w[idx])
		}
		tgt.Var = &Variable{Name: ww.String()}
		pool.PutBuffer(ww)
	case *ast.IndexExpr:
		// accessing a map
		// request.header["abc"]
		tgt.Fn = &Function{Name: tMap[token.LBRACK]}
		if err = processFunc(tgt.Fn, []ast.Expr{v.X, v.Index}); err != nil {
			return
		}
	default:
		return fmt.Errorf("unexpected expression: %#v", v)
	}

	return nil
}

func processSelectorExpr(exin *ast.SelectorExpr, w *[]string) (err error) {
	ex := exin
	for {
		*w = append(*w, ex.Sel.Name)
		switch v := ex.X.(type) {
		case *ast.SelectorExpr:
			ex = v
		case *ast.Ident:
			*w = append(*w, v.Name)
			return nil
		default:
			return fmt.Errorf("unexpected expression: %#v", v)
		}
	}
}

func processFunc(fn *Function, args []ast.Expr) (err error) {
	fAargs := []*Expression{}
	for _, ee := range args {
		aex := &Expression{}
		fAargs = append(fAargs, aex)
		if err = process(ee, aex); err != nil {
			return
		}
	}
	fn.Args = fAargs
	return nil
}

// Parse parses a given expression to ast.Expression.
func Parse(src string) (ex *Expression, err error) {
	a, err := parser.ParseExpr(src)
	if err != nil {
		return nil, fmt.Errorf("unable to parse expression '%s': %v", src, err)
	}
	if glog.V(6) {
		glog.Infof("Parsed expression '%s' into '%v'", src, a)
	}

	ex = &Expression{}
	if err = process(a, ex); err != nil {
		return nil, err
	}
	return ex, nil
}

// ExtractEQMatches extracts equality sub expressions from the match expression.
// It only extracts `attribute == literal` type equality matches.
// It returns a list of  <attribute name, value> such that
// if **any** of these comparisons is false, the expression will evaluate to false.
// These sub expressions can be hoisted out of the match clause and evaluated separately.
// For example
// destination.service == "abc"  -- Used to index rules by destination service.
// context.protocol == "tcp"  -- Used to filter rules by context
func ExtractEQMatches(src string) (map[string]interface{}, error) {
	ex, err := Parse(src)
	if err != nil {
		return nil, err
	}
	eqMap := make(map[string]interface{})
	extractEQMatches(ex, eqMap)
	return eqMap, nil
}

func recordIfEQ(fn *Function, eqMap map[string]interface{}) {
	if fn.Name != "EQ" {
		return
	}

	// x == "y"
	if fn.Args[0].Var != nil && fn.Args[1].Const != nil {
		eqMap[fn.Args[0].Var.Name] = fn.Args[1].Const.Value
		return
	}

	// yoda style, "y" == x
	if fn.Args[0].Const != nil && fn.Args[1].Var != nil {
		eqMap[fn.Args[1].Var.Name] = fn.Args[0].Const.Value
	}
}

// parseEQMatches traverse down "LANDS" and record EQs of variable and constants.
func extractEQMatches(ex *Expression, eqMap map[string]interface{}) {
	if ex.Fn == nil {
		return
	}

	recordIfEQ(ex.Fn, eqMap)

	// only recurse on AND function.
	if ex.Fn.Name != "LAND" {
		return
	}

	//TODO remove collected equality expressions from AST
	for _, arg := range ex.Fn.Args {
		extractEQMatches(arg, eqMap)
	}
}

// DefaultCacheSize is the default size for the expression cache.
const DefaultCacheSize = 1024

// Evaluator for a c-like expression language.
type cexl struct {
	cache *lru.Cache
	// function Map
	fMap map[string]FuncBase
}

func (e *cexl) cacheGetExpression(exprStr string) (ex *Expression, err error) {

	// TODO: add normalization for exprStr string, so that 'a | b' is same as 'a|b', and  'a == b' is same as 'b == a'

	if v, found := e.cache.Get(exprStr); found {
		return v.(*Expression), nil
	}

	if glog.V(6) {
		glog.Infof("expression cache miss for '%s'", exprStr)
	}

	ex, err = Parse(exprStr)
	if err != nil {
		return nil, err
	}
	if glog.V(6) {
		glog.Infof("caching expression for '%s''", exprStr)
	}

	_ = e.cache.Add(exprStr, ex)
	return ex, nil
}

func (e *cexl) Eval(s string, attrs attribute.Bag) (ret interface{}, err error) {
	var ex *Expression
	if ex, err = e.cacheGetExpression(s); err != nil {
		return
	}
	return ex.Eval(attrs, e.fMap)
}

// Eval evaluates given expression using the attribute bag to a string
func (e *cexl) EvalString(s string, attrs attribute.Bag) (ret string, err error) {
	var uret interface{}
	var ok bool
	if uret, err = e.Eval(s, attrs); err != nil {
		return
	}
	if ret, ok = uret.(string); ok {
		return
	}
	return "", fmt.Errorf("typeError: got %s, expected string", reflect.TypeOf(uret).String())
}

func (e *cexl) EvalPredicate(s string, attrs attribute.Bag) (ret bool, err error) {
	var uret interface{}
	var ok bool
	if uret, err = e.Eval(s, attrs); err != nil {
		return
	}
	if ret, ok = uret.(bool); ok {
		return
	}
	return false, fmt.Errorf("typeError: got %s, expected bool", reflect.TypeOf(uret).String())
}

func (e *cexl) EvalType(expr string, attrFinder AttributeDescriptorFinder) (dpb.ValueType, error) {
	v, err := e.cacheGetExpression(expr)
	if err != nil {
		return dpb.VALUE_TYPE_UNSPECIFIED, fmt.Errorf("failed to parse expression '%s': %v", expr, err)
	}
	return v.EvalType(attrFinder, e.fMap)
}

func (e *cexl) AssertType(expr string, finder AttributeDescriptorFinder, expectedType dpb.ValueType) error {
	if t, err := e.EvalType(expr, finder); err != nil {
		return err
	} else if t != expectedType {
		return fmt.Errorf("expression '%s' evaluated to type %v, expected type %v", expr, t, expectedType)
	}
	return nil
}

// NewCEXLEvaluator returns a new Evaluator of this type.
func NewCEXLEvaluator(cacheSize int) (Evaluator, error) {
	cache, err := lru.New(cacheSize)
	if err != nil {
		return nil, err
	}
	return &cexl{
		fMap: FuncMap(), cache: cache,
	}, nil
}


text:
class Users::RegistrationsController < ::Devise::RegistrationsController
  # before_filter :configure_permitted_parameters, :only => [:create]
  include UsersHelper
  before_filter :configure_permitted_parameters, :only => [:create]

  def new
    @skills = Skill.all
    super
  end

  def edit
    @skills = Skill.all
  end

  def update
  end

  def create
    sanitize_params_by_role
    build_resource(sign_up_params)
    resource_saved = resource.save
    yield resource if block_given?
    if resource_saved
    add_skills_to_adults(resource.id, skills_params[:skill_ids], skills_params[:descriptions]) unless skills_params[:skill_ids].nil?

      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_flashing_format?
        sign_up(resource_name, resource)
        respond_with resource, location: after_sign_up_path_for(resource)
      else
        set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
        expire_data_after_sign_in!
        respond_with resource, location: after_inactive_sign_up_path_for(resource)
      end
    else
      @skills = Skill.all
      clean_up_passwords resource
      respond_with resource
    end
  end

  def after_inactive_sign_up_path_for(resource)
    @skills = Skill.all
    respond_to?(:root_path) ? root_path : "/"
  end

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:admin_privileges, :role, :name, :phone_number, :grade, :birthday, :badges, :profile_photo, :email, :password, :password_confirmation) }
  end

  def skills_params
    params.require(:user).permit(:skill_ids => [], :descriptions => [])
  end

  def troop_ids_param
    params.require(:user).permit(:troops_ids => [])
  end

  private
  def sanitize_params_by_role
    if params[:user][:role] != "Scout"
      params[:user][:birthday] = nil
      params[:user][:grade] = nil
    # else
      # params[:user][:skill_ids].clear
    end
    if
      params[:user][:role] == "Troop Leader"
      params[:user][:admin_privileges] = 0
    end
  end

end


text:
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
#include <asm/uaccess.h>

/*
 * Version Information
 */
#define DRIVER_VERSION	"v0.3"
#define DRIVER_AUTHOR	"Roelf Diedericks"
#define DRIVER_DESC	"IPWireless tty driver"

#define IPW_TTY_MAJOR	240	/* real device node major id, experimental range */
#define IPW_TTY_MINORS	256	/* we support 256 devices, dunno why, it'd be insane :) */

#define USB_IPW_MAGIC	0x6d02	/* magic number for ipw struct */

/* Message sizes */
#define EVENT_BUFFER_SIZE	0xFF
#define CHAR2INT16(c1,c0)	(((u32)((c1) & 0xff) << 8) + (u32)((c0) & 0xff))
#define NUM_BULK_URBS		24
#define NUM_CONTROL_URBS	16

/* vendor/product pairs that are known work with this driver*/
#define IPW_VID		0x0bc3
#define IPW_PID		0x0001

/* Vendor commands: */

/* baud rates */
enum {
	ipw_sio_b256000 = 0x000e,
	ipw_sio_b128000 = 0x001d,
	ipw_sio_b115200 = 0x0020,
	ipw_sio_b57600  = 0x0040,
	ipw_sio_b56000  = 0x0042,
	ipw_sio_b38400  = 0x0060,
	ipw_sio_b19200  = 0x00c0,
	ipw_sio_b14400  = 0x0100,
	ipw_sio_b9600   = 0x0180,
	ipw_sio_b4800   = 0x0300,
	ipw_sio_b2400   = 0x0600,
	ipw_sio_b1200   = 0x0c00,
	ipw_sio_b600    = 0x1800
};

/* data bits */
#define ipw_dtb_7		0x700
#define ipw_dtb_8		0x810	// ok so the define is misleading, I know, but forces 8,n,1
					// I mean, is there a point to any other setting these days? :)

/* usb control request types : */
#define IPW_SIO_RXCTL		0x00	// control bulk rx channel transmissions, value=1/0 (on/off)
#define IPW_SIO_SET_BAUD	0x01	// set baud, value=requested ipw_sio_bxxxx
#define IPW_SIO_SET_LINE	0x03	// set databits, parity. value=ipw_dtb_x
#define IPW_SIO_SET_PIN		0x03	// set/clear dtr/rts value=ipw_pin_xxx
#define IPW_SIO_POLL		0x08	// get serial port status byte, call with value=0
#define IPW_SIO_INIT		0x11	// initializes ? value=0 (appears as first thing todo on open)
#define IPW_SIO_PURGE		0x12	// purge all transmissions?, call with value=numchar_to_purge
#define IPW_SIO_HANDFLOW	0x13	// set xon/xoff limits value=0, and a buffer of 0x10 bytes
#define IPW_SIO_SETCHARS	0x13	// set the flowcontrol special chars, value=0, buf=6 bytes,
					// last 2 bytes contain flowcontrol chars e.g. 00 00 00 00 11 13

/* values used for request IPW_SIO_SET_PIN */
#define IPW_PIN_SETDTR		0x101
#define IPW_PIN_SETRTS		0x202
#define IPW_PIN_CLRDTR		0x100
#define IPW_PIN_CLRRTS		0x200 // unconfirmed

/* values used for request IPW_SIO_RXCTL */
#define IPW_RXBULK_ON		1
#define IPW_RXBULK_OFF		0

/* various 16 byte hardcoded transferbuffers used by flow control */
#define IPW_BYTES_FLOWINIT	{ 0x01, 0, 0, 0, 0x40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }

/* Interpretation of modem status lines */
/* These need sorting out by individually connecting pins and checking
 * results. FIXME!
 * When data is being sent we see 0x30 in the lower byte; this must
 * contain DSR and CTS ...
 */
#define IPW_DSR			((1<<4) | (1<<5))
#define IPW_CTS			((1<<5) | (1<<4))

#define IPW_WANTS_TO_SEND	0x30
//#define IPW_DTR			/* Data Terminal Ready */
//#define IPW_CTS			/* Clear To Send */
//#define IPW_CD			/* Carrier Detect */
//#define IPW_DSR			/* Data Set Ready */
//#define IPW_RxD			/* Receive pin */

//#define IPW_LE
//#define IPW_RTS
//#define IPW_ST
//#define IPW_SR
//#define IPW_RI			/* Ring Indicator */

static struct usb_device_id usb_ipw_ids[] = {
	{ USB_DEVICE(IPW_VID, IPW_PID) },
	{ },
};

MODULE_DEVICE_TABLE(usb, usb_ipw_ids);

static struct usb_driver usb_ipw_driver = {
	.name =		"ipwtty",
	.probe =	usb_serial_probe,
	.disconnect =	usb_serial_disconnect,
	.id_table =	usb_ipw_ids,
	.no_dynamic_id = 	1,
};

static int debug;

static void ipw_read_bulk_callback(struct urb *urb)
{
	struct usb_serial_port *port = urb->context;
	unsigned char *data = urb->transfer_buffer;
	struct tty_struct *tty;
	int result;

	dbg("%s - port %d", __FUNCTION__, port->number);

	if (urb->status) {
		dbg("%s - nonzero read bulk status received: %d", __FUNCTION__, urb->status);
		return;
	}

	usb_serial_debug_data(debug, &port->dev, __FUNCTION__, urb->actual_length, data);

	tty = port->tty;
	if (tty && urb->actual_length) {
		tty_buffer_request_room(tty, urb->actual_length);
		tty_insert_flip_string(tty, data, urb->actual_length);
		tty_flip_buffer_push(tty);
	}

	/* Continue trying to always read  */
	usb_fill_bulk_urb (port->read_urb, port->serial->dev,
			   usb_rcvbulkpipe(port->serial->dev,
					   port->bulk_in_endpointAddress),
			   port->read_urb->transfer_buffer,
			   port->read_urb->transfer_buffer_length,
			   ipw_read_bulk_callback, port);
	result = usb_submit_urb(port->read_urb, GFP_ATOMIC);
	if (result)
		dev_err(&port->dev, "%s - failed resubmitting read urb, error %d\n", __FUNCTION__, result);
	return;
}

static int ipw_open(struct usb_serial_port *port, struct file *filp)
{
	struct usb_device *dev = port->serial->dev;
	u8 buf_flow_static[16] = IPW_BYTES_FLOWINIT;
	u8 *buf_flow_init;
	int result;

	dbg("%s", __FUNCTION__);

	buf_flow_init = kmemdup(buf_flow_static, 16, GFP_KERNEL);
	if (!buf_flow_init)
		return -ENOMEM;

	if (port->tty)
		port->tty->low_latency = 1;

	/* --1: Tell the modem to initialize (we think) From sniffs this is always the
	 * first thing that gets sent to the modem during opening of the device */
	dbg("%s: Sending SIO_INIT (we guess)",__FUNCTION__);
	result = usb_control_msg(dev, usb_sndctrlpipe(dev,0),
				 IPW_SIO_INIT,
				 USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_DIR_OUT,
				 0,
				 0, /* index */
				 NULL,
				 0,
				 100000);
	if (result < 0)
		dev_err(&port->dev, "Init of modem failed (error = %d)", result);

	/* reset the bulk pipes */
	usb_clear_halt(dev, usb_rcvbulkpipe(dev, port->bulk_in_endpointAddress));
	usb_clear_halt(dev, usb_sndbulkpipe(dev, port->bulk_out_endpointAddress));

	/*--2: Start reading from the device */
	dbg("%s: setting up bulk read callback",__FUNCTION__);
	usb_fill_bulk_urb(port->read_urb, dev,
			  usb_rcvbulkpipe(dev, port->bulk_in_endpointAddress),
			  port->bulk_in_buffer,
			  port->bulk_in_size,
			  ipw_read_bulk_callback, port);
	result = usb_submit_urb(port->read_urb, GFP_KERNEL);
	if (result < 0)
		dbg("%s - usb_submit_urb(read bulk) failed with status %d", __FUNCTION__, result);

	/*--3: Tell the modem to open the floodgates on the rx bulk channel */
	dbg("%s:asking modem for RxRead (RXBULK_ON)",__FUNCTION__);
	result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
				 IPW_SIO_RXCTL,
				 USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_DIR_OUT,
				 IPW_RXBULK_ON,
				 0, /* index */
				 NULL,
				 0,
				 100000);
	if (result < 0)
		dev_err(&port->dev, "Enabling bulk RxRead failed (error = %d)", result);

	/*--4: setup the initial flowcontrol */
	dbg("%s:setting init flowcontrol (%s)",__FUNCTION__,buf_flow_init);
	result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
				 IPW_SIO_HANDFLOW,
				 USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_DIR_OUT,
				 0,
				 0,
				 buf_flow_init,
				 0x10,
				 200000);
	if (result < 0)
		dev_err(&port->dev, "initial flowcontrol failed (error = %d)", result);

	/*--5: raise the dtr */
	dbg("%s:raising dtr",__FUNCTION__);
	result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
				 IPW_SIO_SET_PIN,
				 USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_DIR_OUT,
				 IPW_PIN_SETDTR,
				 0,
				 NULL,
				 0,
				 200000);
	if (result < 0)
		dev_err(&port->dev, "setting dtr failed (error = %d)", result);

	/*--6: raise the rts */
	dbg("%s:raising rts",__FUNCTION__);
	result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
				 IPW_SIO_SET_PIN,
				 USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_DIR_OUT,
				 IPW_PIN_SETRTS,
				 0,
				 NULL,
				 0,
				 200000);
	if (result < 0)
		dev_err(&port->dev, "setting dtr failed (error = %d)", result);

	kfree(buf_flow_init);
	return 0;
}

static void ipw_close(struct usb_serial_port *port, struct file * filp)
{
	struct usb_device *dev = port->serial->dev;
	int result;

	if (tty_hung_up_p(filp)) {
		dbg("%s: tty_hung_up_p ...", __FUNCTION__);
		return;
	}

	/*--1: drop the dtr */
	dbg("%s:dropping dtr",__FUNCTION__);
	result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
				 IPW_SIO_SET_PIN,
				 USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_DIR_OUT,
				 IPW_PIN_CLRDTR,
				 0,
				 NULL,
				 0,
				 200000);
	if (result < 0)
		dev_err(&port->dev, "dropping dtr failed (error = %d)", result);

	/*--2: drop the rts */
	dbg("%s:dropping rts",__FUNCTION__);
	result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
				 IPW_SIO_SET_PIN, USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_DIR_OUT,
				 IPW_PIN_CLRRTS,
				 0,
				 NULL,
				 0,
				 200000);
	if (result < 0)
		dev_err(&port->dev, "dropping rts failed (error = %d)", result);

	/*--3: purge */
	dbg("%s:sending purge",__FUNCTION__);
	result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
				 IPW_SIO_PURGE, USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_DIR_OUT,
				 0x03,
				 0,
				 NULL,
				 0,
				 200000);
	if (result < 0)
		dev_err(&port->dev, "purge failed (error = %d)", result);

	/* send RXBULK_off (tell modem to stop transmitting bulk data on rx chan) */
	result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
				 IPW_SIO_RXCTL,
				 USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_DIR_OUT,
				 IPW_RXBULK_OFF,
				 0, /* index */
				 NULL,
				 0,
				 100000);

	if (result < 0)
		dev_err(&port->dev, "Disabling bulk RxRead failed (error = %d)", result);

	/* shutdown any in-flight urbs that we know about */
	usb_kill_urb(port->read_urb);
	usb_kill_urb(port->write_urb);
}

static void ipw_write_bulk_callback(struct urb *urb)
{
	struct usb_serial_port *port = urb->context;

	dbg("%s", __FUNCTION__);

	port->write_urb_busy = 0;

	if (urb->status)
		dbg("%s - nonzero write bulk status received: %d", __FUNCTION__, urb->status);

	usb_serial_port_softint(port);
}

static int ipw_write(struct usb_serial_port *port, const unsigned char *buf, int count)
{
	struct usb_device *dev = port->serial->dev;
	int ret;

	dbg("%s: TOP: count=%d, in_interrupt=%ld", __FUNCTION__,
		count, in_interrupt() );

	if (count == 0) {
		dbg("%s - write request of 0 bytes", __FUNCTION__);
		return 0;
	}

	spin_lock_bh(&port->lock);
	if (port->write_urb_busy) {
		spin_unlock_bh(&port->lock);
		dbg("%s - already writing", __FUNCTION__);
		return 0;
	}
	port->write_urb_busy = 1;
	spin_unlock_bh(&port->lock);

	count = min(count, port->bulk_out_size);
	memcpy(port->bulk_out_buffer, buf, count);

	dbg("%s count now:%d", __FUNCTION__, count);

	usb_fill_bulk_urb(port->write_urb, dev,
			  usb_sndbulkpipe(dev, port->bulk_out_endpointAddress),
			  port->write_urb->transfer_buffer,
			  count,
			  ipw_write_bulk_callback,
			  port);

	ret = usb_submit_urb(port->write_urb, GFP_ATOMIC);
	if (ret != 0) {
		port->write_urb_busy = 0;
		dbg("%s - usb_submit_urb(write bulk) failed with error = %d", __FUNCTION__, ret);
		return ret;
	}

	dbg("%s returning %d", __FUNCTION__, count);
	return count;
}

static int ipw_probe(struct usb_serial_port *port)
{
	return 0;
}

static int ipw_disconnect(struct usb_serial_port *port)
{
	usb_set_serial_port_data(port, NULL);
	return 0;
}

static struct usb_serial_driver ipw_device = {
	.driver = {
		.owner =	THIS_MODULE,
		.name =		"ipw",
	},
	.description =		"IPWireless converter",
	.usb_driver = 		&usb_ipw_driver,
	.id_table =		usb_ipw_ids,
	.num_interrupt_in =	NUM_DONT_CARE,
	.num_bulk_in =		1,
	.num_bulk_out =		1,
	.num_ports =		1,
	.open =			ipw_open,
	.close =		ipw_close,
	.port_probe = 		ipw_probe,
	.port_remove =		ipw_disconnect,
	.write =		ipw_write,
	.write_bulk_callback =	ipw_write_bulk_callback,
	.read_bulk_callback =	ipw_read_bulk_callback,
};

static int usb_ipw_init(void)
{
	int retval;

	retval = usb_serial_register(&ipw_device);
	if (retval)
		return retval;
	retval = usb_register(&usb_ipw_driver);
	if (retval) {
		usb_serial_deregister(&ipw_device);
		return retval;
	}
	info(DRIVER_DESC " " DRIVER_VERSION);
	return 0;
}

static void usb_ipw_exit(void)
{
	usb_deregister(&usb_ipw_driver);
	usb_serial_deregister(&ipw_device);
}

module_init(usb_ipw_init);
module_exit(usb_ipw_exit);

/* Module information */
MODULE_AUTHOR( DRIVER_AUTHOR );
MODULE_DESCRIPTION( DRIVER_DESC );
MODULE_LICENSE("GPL");

module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug enabled or not");


text:
package sc.fiji.filamentdetector.exporter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.List;

import org.scijava.Context;
import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;

import sc.fiji.filamentdetector.Calibrations;
import sc.fiji.filamentdetector.model.Filament;
import sc.fiji.filamentdetector.model.Filaments;

public class JSONFilamentExporter extends FilamentsExporter<Filaments> {

	@Parameter
	private LogService log;

	public static String NAME = "JSON Exporter";
	public static String DESCRIPTION = "A JSON Exporter. Calibrations of the image will be"
			+ " applied to all spatial values.";
	public static String EXTENSION = "*.json";
	public static String EXTENSION_DESCRIPTION = "JSON File (*.json)";
	public static List<String> EXTENSION_FILTERS = Arrays.asList("*.json");

	private Calibrations calibrations;

	public JSONFilamentExporter(Context context, Calibrations calibrations) {
		super(context);
		this.calibrations = calibrations;
	}

	@Override
	public String getName() {
		return NAME;
	}

	@Override
	public String getExtension() {
		return EXTENSION;
	}

	@Override
	public List<String> getExtensionFilters() {
		return EXTENSION_FILTERS;
	}

	@Override
	public String getExtensionDescription() {
		return EXTENSION_DESCRIPTION;
	}

	@Override
	public String getDescription() {
		return DESCRIPTION;
	}

	@Override
	public String toString() {
		return NAME;
	}

	@Override
	public void export(Filaments filaments, File file) {
		JsonObject root = new JsonObject();

		JsonArray filamentsArray = new JsonArray();
		JsonObject filamentElement;

		double[] x;
		double[] y;

		for (Filament filament : filaments) {
			filamentElement = new JsonObject();

			filamentElement.add("id", new JsonPrimitive(filament.getId()));
			filamentElement.add("length", new JsonPrimitive(filament.getLength() * calibrations.getDx()));
			filamentElement.add("frame", new JsonPrimitive(filament.getFrame()));
			filamentElement.add("sinuosity", new JsonPrimitive(filament.getSinuosity()));
			filamentElement.add("size", new JsonPrimitive(filament.getSize()));
			filamentElement.add("color", new JsonPrimitive(filament.getColorAsHex()));

			x = filament.getXCoordinates();
			filamentElement.add("x", serializeCoordinates(x, calibrations.getDx()));

			y = filament.getYCoordinates();
			filamentElement.add("y", serializeCoordinates(y, calibrations.getDy()));

			filamentsArray.add(filamentElement);
		}

		root.add("filaments", filamentsArray);

		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		String json = gson.toJson(root);

		try {
			file.createNewFile();
			FileOutputStream fOut = new FileOutputStream(file);
			OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
			myOutWriter.append(json);
			myOutWriter.close();
			fOut.close();
		} catch (IOException e) {
			log.error(e);
		}
	}

}


text:
package ru.eaboimov;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
Умножение факториала.
*/
public class FactorialTest {
	/**
	@Test
	@factorial 5!=120
	*/
    @Test
    public void whenCalculateFactorialForFiveThenOneHundreedTwenty() {
		Factorial fac = new Factorial();
		assertThat(fac.calc(5), is(120));
    }
    /**
	@Test
	@factorial 0!=1
	*/
    @Test
    public void whenCalculateFactorialForZeroThenOne() {
		Factorial fac = new Factorial();
		assertThat(fac.calc(0), is(1));
    }
}


text:
package com.qualcomm.ftcrobotcontroller.opmodes.Torch.Auton;

import com.qualcomm.ftcrobotcontroller.opmodes.Torch.RobotSetup;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;

/**
 * Created by taand on 3/10/2016.
 */
public abstract class BaseAutonArm extends LinearOpMode {

    //static means these can't be modified by the program.
    static int FAR_TURN_ANGLE   = 120;
    static int CLOSE_TURN_ANGLE = 40;
    static int FAR_MOVE_DIST    = 124;
    static int CLOSE_MOVE_DIST  = 75;
    static int LIGHT_THRESHOLD  = 115;
    static int WAIT_TIME        = 17 * 1000; //ten seconds
    static int turnDir          = 1;
    static int MOVE_DEFENSE     = 60;
    static int TURN_DEFENSE     = 30;

    enum Wait {
        YES,NO
    }
    enum Alliance {
        RED,BLUE
    }
    enum Placement {
        CLOSE,FAR

    }
    enum Defense {
        YES, NO
    }

    abstract Wait      getWait();
    abstract Alliance  getAlliance();
    abstract Placement getPlacement();
    abstract Defense   getDefense();

    boolean wait = getWait() == Wait.YES;

    @Override
    public void runOpMode() throws InterruptedException {
        Alliance alliance = getAlliance();
        Placement placement = getPlacement();
        Defense defense = getDefense();
        RobotSetup fetty = new RobotSetup(hardwareMap,telemetry,this);

        waitForStart();
        //fetty.dumpArm(fetty.DUMP_DOWN);

        if (wait) {sleep(WAIT_TIME);}

        //if alliance.BLUE == true, then dist = 24, else dist = 73
        int firstdist   = placement == placement.FAR ? FAR_MOVE_DIST : CLOSE_MOVE_DIST;
        int turnAngle   = placement == placement.FAR ? FAR_TURN_ANGLE: CLOSE_TURN_ANGLE;
        int Dturn       = alliance  == alliance.BLUE  ? TURN_DEFENSE  : -TURN_DEFENSE;

        if (alliance == alliance.RED  && placement == placement.FAR  ) turnDir = -1;
        if (alliance == alliance.RED  && placement == placement.CLOSE) turnDir =  1;
        if (alliance == alliance.BLUE && placement == placement.CLOSE) turnDir = -1;
        if (alliance == alliance.BLUE && placement == placement.FAR)   turnDir =  1;

        telemetry.addData("Alliance",alliance);
        telemetry.addData("Placement",placement);
        telemetry.addData("Turn Angle", turnDir);

        while (!fetty.isTouched()) {
            fetty.arm(1);
            waitOneFullHardwareCycle();
        }
        fetty.arm(0);
        fetty.initializeServos();
        fetty.encoderMove(firstdist, 0.7);

        fetty.gTurn(turnAngle * turnDir, 0.7);
        fetty.move(4,0.7);
        while (fetty.floorIR.getLightDetectedRaw() < LIGHT_THRESHOLD && opModeIsActive()) {
            waitOneFullHardwareCycle();
            fetty.move(0.41, 0.4);
        }
        fetty.encoderMove(-3, -0.5);
        fetty.gTurn(75 * turnDir, 1);
        fetty.encoderMove(-2, -0.5);

        fetty.resetArm();
        while (fetty.armPos() > -3500) {
            if (fetty.isTouched()) fetty.resetArm();
            fetty.arm(-0.7);
            telemetry.addData("ARM",fetty.armPos());
            waitOneFullHardwareCycle();
        }
        fetty.arm(0);
        fetty.encoderMove(0.5, 0.5);
        sleep(100);
        while (fetty.armPos() < -20) {
            fetty.arm(0.7);
            telemetry.addData("ARM", fetty.armPos());
            waitOneFullHardwareCycle();
        }
        fetty.arm(0);

        if (defense == defense.YES) {
            fetty.gTurn(Dturn, 1);
            fetty.encoderMove(MOVE_DEFENSE,1);
        }

        fetty.servoController.pwmDisable();
        fetty.move(0, 0);
    }
}


text:
set -e
set -x

cd wishbone-tool
export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER="$CC"
cargo build --release

install -d $PREFIX/bin
install target/release/wishbone-tool $PREFIX/bin


text:
<?xml version="1.0" encoding="UTF-8"?>
<groups xmlns="http://www.isdc.ro/wro">

    <!-- CSS URL Rewriting fails when using webjar resource locator:
         https://github.com/alexo/wro4j/issues/127 -->
    <group name="main">
        <css>classpath:META-INF/resources/webjars/bootswatch/3.0.0/spacelab/bootstrap.min.css</css>
        <css>/styles/style.css</css>
        <js>classpath:META-INF/resources/webjars/jquery/1.8.3/jquery.min.js</js>
        <js>classpath:META-INF/resources/webjars/bootstrap/3.0.2/js/bootstrap.min.js</js>
        <js>classpath:META-INF/resources/webjars/jquery-cookie/1.3.1/jquery.cookie.js</js>
        <js>/scripts/script.js</js>
    </group>
</groups>


text:
// Copyright 2006, 2007, 2008 The Apache Software Foundation
//
// 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.

package org.apache.tapestry5.internal.services;

import org.apache.tapestry5.internal.structure.Page;

import java.io.IOException;

/**
 * Service responsible for writing a full page markup response.
 */
public interface PageResponseRenderer
{
    void renderPageResponse(Page page) throws IOException;
}


text:
#ifdef RTE_BACKTRACE
#include <execinfo.h>
#endif
#include <stdarg.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

#include <rte_log.h>
#include <rte_debug.h>
#include <rte_common.h>
#include <rte_eal.h>

#define BACKTRACE_SIZE 256

/* dump the stack of the calling core */
void rte_dump_stack(void)
{
#ifdef RTE_BACKTRACE
	void *func[BACKTRACE_SIZE];
	char **symb = NULL;
	int size;

	size = backtrace(func, BACKTRACE_SIZE);
	symb = backtrace_symbols(func, size);

	if (symb == NULL)
		return;

	while (size > 0) {
		rte_log(RTE_LOG_ERR, RTE_LOGTYPE_EAL,
			"%d: [%s]\n", size, symb[size - 1]);
		size --;
	}

	free(symb);
#endif /* RTE_BACKTRACE */
}


text: void rose_js_sys_extcmd(const v8::FunctionCallbackInfo<v8::Value>& args);