text:
#include "codegen/arrow_compute/ext/actions_impl.h"
#include "codegen/arrow_compute/ext/kernels_ext.h"
#include "codegen/arrow_compute/ext/window_sort_kernel.h"

namespace sparkcolumnarplugin {
namespace codegen {
namespace arrowcompute {
namespace extra {

class WindowAggregateFunctionKernel::ActionFactory {
 public:
  ActionFactory(std::shared_ptr<ActionBase> action) {
    action_ = action;
  }

  static arrow::Status Make(std::string action_name,
                            arrow::compute::FunctionContext *ctx,
                            std::shared_ptr<arrow::DataType> type,
                            std::shared_ptr<ActionFactory> *out) {
    std::shared_ptr<ActionBase> action;
    if (action_name == "sum") {
      RETURN_NOT_OK(MakeSumAction(ctx, type, &action));
    } else if (action_name == "avg") {
      RETURN_NOT_OK(MakeAvgAction(ctx, type, &action));
    } else {
      return arrow::Status::Invalid("window aggregate function: unsupported action name: " + action_name);
    }
    *out = std::make_shared<ActionFactory>(action);
    return arrow::Status::OK();
  }

  std::shared_ptr<ActionBase> Get() {
    return action_;
  }

 private:
  std::shared_ptr<ActionBase> action_;
};

arrow::Status WindowAggregateFunctionKernel::Make(arrow::compute::FunctionContext *ctx,
                                                  std::string function_name,
                                                  std::vector<std::shared_ptr<arrow::DataType>> type_list,
                                                  std::shared_ptr<arrow::DataType> result_type,
                                                  std::shared_ptr<KernalBase> *out) {
  if (type_list.size() != 1) {
    return arrow::Status::Invalid("given more than 1 input argument for window function: " + function_name);
  }
  std::shared_ptr<ActionFactory> action;

  if (function_name == "sum" || function_name == "avg") {
    RETURN_NOT_OK(ActionFactory::Make(function_name, ctx, type_list[0], &action));
  } else {
    return arrow::Status::Invalid("window function not supported: " + function_name);
  }
  auto accumulated_group_ids = std::vector<std::shared_ptr<arrow::Int32Array >>();
  *out = std::make_shared<WindowAggregateFunctionKernel>(ctx, type_list, result_type, accumulated_group_ids, action);
  return arrow::Status::OK();
}

WindowAggregateFunctionKernel::WindowAggregateFunctionKernel(arrow::compute::FunctionContext *ctx,
                                                             std::vector<std::shared_ptr<arrow::DataType>> type_list,
                                                             std::shared_ptr<arrow::DataType> result_type,
                                                             std::vector<std::shared_ptr<arrow::Int32Array>> accumulated_group_ids,
                                                             std::shared_ptr<ActionFactory> action) {
  ctx_ = ctx;
  type_list_ = type_list;
  result_type_ = result_type;
  accumulated_group_ids_ = accumulated_group_ids;
  action_ = action;
  kernel_name_ = "WindowAggregateFunctionKernel";
}

/**
 * | a | group |   | group | sum |          | result |
 * | 2 |     0 | + |     0 |   8 |   --->   |      8 |
 * | 3 |     1 |   |     1 |   3 |          |      3 |
 * | 6 |     0 |                            |      8 |
 */
arrow::Status WindowAggregateFunctionKernel::Evaluate(const ArrayList &in) {
  // abstract following code to do common inter-window processing

  int32_t max_group_id = 0;
  std::shared_ptr<arrow::Array> group_id_array = in[1];
  auto group_ids = std::dynamic_pointer_cast<arrow::Int32Array>(group_id_array);
  accumulated_group_ids_.push_back(group_ids);
  for (int i = 0; i < group_ids->length(); i++) {
    if (group_ids->IsNull(i)) {
      continue;
    }
    if (group_ids->GetView(i) > max_group_id) {
      max_group_id = group_ids->GetView(i);
    }
  }

  ArrayList action_input_data;
  action_input_data.push_back(in[0]);
  std::function<arrow::Status(int)> func;
  std::function<arrow::Status()> null_func;
  RETURN_NOT_OK(action_->Get()->Submit(action_input_data, max_group_id, &func, &null_func));

  for (int row_id = 0; row_id < group_id_array->length(); row_id++) {
    if (group_ids->IsNull(row_id)) {
      RETURN_NOT_OK(null_func());
      continue;
    }
    auto group_id = group_ids->GetView(row_id);
    RETURN_NOT_OK(func(group_id));
  }

  return arrow::Status::OK();
}

#define PROCESS_SUPPORTED_TYPES(PROCESS) \
  PROCESS(arrow::UInt8Type)              \
  PROCESS(arrow::Int8Type)               \
  PROCESS(arrow::UInt16Type)             \
  PROCESS(arrow::Int16Type)              \
  PROCESS(arrow::UInt32Type)             \
  PROCESS(arrow::Int32Type)              \
  PROCESS(arrow::UInt64Type)             \
  PROCESS(arrow::Int64Type)              \
  PROCESS(arrow::FloatType)              \
  PROCESS(arrow::DoubleType)

arrow::Status WindowAggregateFunctionKernel::Finish(ArrayList *out) {
  std::shared_ptr<arrow::DataType> value_type = result_type_;
  switch (value_type->id()) {
#define PROCESS(NUMERIC_TYPE)                                                      \
  case NUMERIC_TYPE::type_id: {                                                    \
    RETURN_NOT_OK(Finish0<NUMERIC_TYPE>(out));                                     \
  } break;
    PROCESS_SUPPORTED_TYPES(PROCESS)
#undef PROCESS
    default:return arrow::Status::Invalid("window function: unsupported input type");
  }
  return arrow::Status::OK();
}

template<typename ArrowType>
arrow::Status WindowAggregateFunctionKernel::Finish0(ArrayList *out) {
  ArrayList action_output;
  RETURN_NOT_OK(action_->Get()->Finish(&action_output));
  if (action_output.size() != 1) {
    return arrow::Status::Invalid("window function: got invalid result from corresponding action");
  }

  auto action_output_values = std::dynamic_pointer_cast<arrow::NumericArray<ArrowType >>(action_output.at(0));

  for (const auto &accumulated_group_ids_single_part : accumulated_group_ids_) {
    std::unique_ptr<arrow::NumericBuilder<ArrowType>> output_builder
        = std::make_unique<arrow::NumericBuilder<ArrowType >>(ctx_->memory_pool());

    for (int i = 0; i < accumulated_group_ids_single_part->length(); i++) {
      if (accumulated_group_ids_single_part->IsNull(i)) {
        RETURN_NOT_OK(output_builder->AppendNull());
        continue;
      }
      int32_t group_id = accumulated_group_ids_single_part->GetView(i);
      RETURN_NOT_OK(output_builder->Append(action_output_values->GetView(group_id)));
    }
    std::shared_ptr<arrow::Array> out_array;
    RETURN_NOT_OK(output_builder->Finish(&out_array));
    (*out).push_back(out_array);
  }
  return arrow::Status::OK();
}

WindowRankKernel::WindowRankKernel(arrow::compute::FunctionContext *ctx,
                                   std::vector<std::shared_ptr<arrow::DataType>> type_list,
                                   std::shared_ptr<WindowSortKernel::Impl> sorter,
                                   bool desc) {
  ctx_ = ctx;
  type_list_ = type_list;
  sorter_ = sorter;
  desc_ = desc;
}

arrow::Status WindowRankKernel::Make(arrow::compute::FunctionContext *ctx,
                                     std::string function_name,
                                     std::vector<std::shared_ptr<arrow::DataType>> type_list,
                                     std::shared_ptr<KernalBase> *out,
                                     bool desc) {
  std::vector<std::shared_ptr<arrow::Field>> key_fields;
  for (int i = 0; i < type_list.size(); i++) {
    key_fields.push_back(std::make_shared<arrow::Field>("sort_key" + std::to_string(i), type_list.at(i)));
  }
  std::shared_ptr<arrow::Schema> result_schema = std::make_shared<arrow::Schema>(key_fields);

  std::shared_ptr<WindowSortKernel::Impl> sorter;
  // fixme null ordering flag and collation flag
  bool nulls_first = false;
  bool asc = !desc;
  if (key_fields.size() == 1) {
    std::shared_ptr<arrow::Field> key_field = key_fields[0];
    if (key_field->type()->id() == arrow::Type::STRING) {
      sorter.reset(
          new WindowSortOnekeyKernel<arrow::StringType, std::string>(ctx, key_fields,
                                                                     result_schema, nulls_first, asc));
    } else {
      switch (key_field->type()->id()) {
#define PROCESS(InType)                                                       \
  case InType::type_id: {                                                     \
    using CType = typename arrow::TypeTraits<InType>::CType;                  \
    sorter.reset(new WindowSortOnekeyKernel<InType, CType>(ctx, key_fields, result_schema, nulls_first, asc));  \
  } break;
        PROCESS_SUPPORTED_TYPES(PROCESS)
#undef PROCESS
        default: {
          std::cout << "WindowSortOnekeyKernel type not supported, type is "
                    << key_field->type() << std::endl;
        }
          break;
      }
    }
  } else {
    sorter.reset(new WindowSortKernel::Impl(ctx, key_fields, result_schema, nulls_first, asc));
    auto status = sorter->LoadJITFunction(key_fields, result_schema);
    if (!status.ok()) {
      std::cout << "LoadJITFunction failed, msg is " << status.message() << std::endl;
      throw;
    }
  }
  *out = std::make_shared<WindowRankKernel>(ctx, type_list, sorter, desc);
  return arrow::Status::OK();
}

arrow::Status WindowRankKernel::Evaluate(const ArrayList &in) {
  input_cache_.push_back(in);
  return arrow::Status::OK();
}

arrow::Status WindowRankKernel::Finish(ArrayList *out) {
  std::vector<ArrayList> values;
  std::vector<std::shared_ptr<arrow::Int32Array>> group_ids;

  for (auto batch : input_cache_) {
    ArrayList values_batch;
    for (int i = 0; i < type_list_.size() + 1; i++) {
      auto column_slice = batch.at(i);
      if (i == type_list_.size()) {
        // we are at the column of partition ids
        group_ids.push_back(std::dynamic_pointer_cast<arrow::Int32Array>(column_slice));
        continue;
      }
      values_batch.push_back(column_slice);
    }
    values.push_back(values_batch);
  }

  int32_t max_group_id = 0;
  for (int i = 0; i < group_ids.size(); i++) {
    auto slice = group_ids.at(i);
    for (int j = 0; j < slice->length(); j++) {
      if (slice->IsNull(j)) {
        continue;
      }
      if (slice->GetView(j) > max_group_id) {
        max_group_id = slice->GetView(j);
      }
    }
  }
  // initialize partitions to be sorted
  std::vector<std::vector<std::shared_ptr<ArrayItemIndex>>> partitions_to_sort;
  for (int i = 0; i <= max_group_id; i++) {
    partitions_to_sort.emplace_back();
  }

  for (int i = 0; i < group_ids.size(); i++) {
    auto slice = group_ids.at(i);
    for (int j = 0; j < slice->length(); j++) {
      if (slice->IsNull(j)) {
        continue;
      }
      uint64_t partition_id = slice->GetView(j);
      partitions_to_sort.at(partition_id).push_back(std::make_shared<ArrayItemIndex>(i, j));
    }
  }
  std::vector<std::vector<std::shared_ptr<ArrayItemIndex>>> sorted_partitions;
  RETURN_NOT_OK(SortToIndicesPrepare(values));
  for (int i = 0; i <= max_group_id; i++) {
    std::vector<std::shared_ptr<ArrayItemIndex>> partition = partitions_to_sort.at(i);
    std::vector<std::shared_ptr<ArrayItemIndex>> sorted_partition;
    RETURN_NOT_OK(SortToIndicesFinish(partition, &sorted_partition));
    sorted_partitions.push_back(sorted_partition);
  }
  int32_t **rank_array = new int32_t*[group_ids.size()];
  for (int i = 0; i < group_ids.size(); i++) {
    *(rank_array + i) = new int32_t[group_ids.at(i)->length()];
  }
  for (int i = 0; i <= max_group_id; i++) {
    std::vector<std::shared_ptr<ArrayItemIndex>> sorted_partition = sorted_partitions.at(i);
    int assumed_rank = 0;
    for (int j = 0; j < sorted_partition.size(); j++) {
      ++assumed_rank; // rank value starts from 1
      std::shared_ptr<ArrayItemIndex> index = sorted_partition.at(j);
      if (j == 0) {
        rank_array[index->array_id][index->id] = 1; // rank value starts from 1
        continue;
      }
      std::shared_ptr<ArrayItemIndex> last_index = sorted_partition.at(j - 1);
      bool same = true;
      for (int column_id = 0; column_id < type_list_.size(); column_id++) {
        bool s;
        std::shared_ptr<arrow::DataType> type = type_list_.at(column_id);
        switch (type->id()) {
#define PROCESS(InType)                                                       \
  case InType::type_id: {                                                     \
    using ArrayType = typename arrow::TypeTraits<InType>::ArrayType;                  \
      RETURN_NOT_OK(AreTheSameValue<ArrayType>(values, column_id, index, last_index, &s));  \
  } break;
          PROCESS_SUPPORTED_TYPES(PROCESS)
#undef PROCESS
          default: {
            std::cout << "WindowRankKernel: type not supported: "
                      << type->ToString() << std::endl; // todo use arrow::Status
          }
            break;
        }
        if (!s) {
          same = false;
          break;
        }
      }
      if (same) {
        rank_array[index->array_id][index->id] = rank_array[last_index->array_id][last_index->id];
        continue;
      }
      rank_array[index->array_id][index->id] = assumed_rank;
    }
  }
  for (int i = 0; i < input_cache_.size(); i++) {
    auto batch = input_cache_.at(i);
    auto group_id_column_slice = batch.at(type_list_.size());
    int slice_length = group_id_column_slice->length();
    std::shared_ptr<arrow::Int32Builder> rank_builder = std::make_shared<arrow::Int32Builder>(ctx_->memory_pool());
    for (int j = 0; j < slice_length; j++) {
      RETURN_NOT_OK(rank_builder->Append(rank_array[i][j]));
    }
    std::shared_ptr<arrow::Int32Array> rank_slice;
    RETURN_NOT_OK(rank_builder->Finish(&rank_slice));
    out->push_back(rank_slice);
  }
  for (int i = 0; i < group_ids.size(); i++) {
    delete *(rank_array + i);
  }
  delete[] rank_array;
  return arrow::Status::OK();
}

static arrow::Status EncodeIndices( std::vector<std::shared_ptr<ArrayItemIndex>> in, std::shared_ptr<arrow::Array> *out){
  arrow::UInt64Builder builder;
  for (const auto& each : in) {
    uint64_t encoded = ((uint64_t) (each->array_id) << 16U) ^ ((uint64_t) (each->id));
    RETURN_NOT_OK(builder.Append(encoded));
  }
  RETURN_NOT_OK(builder.Finish(out));
  return arrow::Status::OK();
}

static arrow::Status DecodeIndices(std::shared_ptr<arrow::Array> in, std::vector<std::shared_ptr<ArrayItemIndex>> *out){
  std::vector<std::shared_ptr<ArrayItemIndex>> v;
  std::shared_ptr<arrow::UInt64Array> selected = std::dynamic_pointer_cast<arrow::UInt64Array>(in);
  for (int i = 0; i < selected->length(); i++) {
    uint64_t encoded = selected->GetView(i);
    uint16_t array_id = (encoded & 0xFFFF0000U) >> 16U;
    uint16_t id = encoded & 0xFFFFU;
    v.push_back(std::make_shared<ArrayItemIndex>(array_id, id));
  }
  *out = v;
  return arrow::Status::OK();
}

arrow::Status WindowRankKernel::SortToIndicesPrepare(std::vector<ArrayList> values) {
#ifdef DEBUG
  std::cout << "RANK: values to sort: " << values.at(0)->ToString() << std::endl;
#endif
  for (auto each_batch : values) {
    RETURN_NOT_OK(sorter_->Evaluate(each_batch));
  }
  return arrow::Status::OK();
  // todo sort algorithm
}

arrow::Status WindowRankKernel::SortToIndicesFinish(std::vector<std::shared_ptr<ArrayItemIndex>> elements_to_sort,
                                                    std::vector<std::shared_ptr<ArrayItemIndex>> *offsets) {
#ifdef DEBUG
  std::cout << "RANK: partition: " << elements_to_sort->ToString() << std::endl;
#endif
  std::shared_ptr<arrow::Array> in;
  std::shared_ptr<arrow::Array> out;
  RETURN_NOT_OK(EncodeIndices(elements_to_sort, &in));
  RETURN_NOT_OK(sorter_->Finish(in, &out));
  std::vector<std::shared_ptr<ArrayItemIndex>> decoded_out;
  RETURN_NOT_OK(DecodeIndices(out, &decoded_out));
  *offsets = decoded_out;
#ifdef DEBUG
  std::cout << "RANK: partition sorted: " << out->ToString() << std::endl;
#endif
  return arrow::Status::OK();
  // todo sort algorithm
}

template<typename ArrayType>
arrow::Status WindowRankKernel::AreTheSameValue(std::vector<ArrayList> values, int column, std::shared_ptr<ArrayItemIndex> i, std::shared_ptr<ArrayItemIndex> j, bool* out) {
  auto typed_array_i = std::dynamic_pointer_cast<ArrayType>(values.at(i->array_id).at(column));
  auto typed_array_j = std::dynamic_pointer_cast<ArrayType>(values.at(j->array_id).at(column));
  *out = (typed_array_i->GetView(i->id) == typed_array_j->GetView(j->id));
  return arrow::Status::OK();
}

}
}
}
}


text:
using App.Controller;
using App.Entity;
using App.UI;
using System;
using System.Windows.Forms;
using System.Linq;
using App.Factory;
using App.UI.PhaseThree;
using App.UI.PhaseTwo;
using ListenerMain = App.UI.PhaseTwo.ListenerMain;

namespace App
{
    /// <summary>
    ///
    /// Login Form
    /// Author: Dezsi Razvan
    ///
    /// </summary>
    public partial class Login : Form
    {
        private LoginController loginController;
        private Form parentForm;

        public Login(Form parentForm)
        {
            InitializeComponent();

            loginController = ApplicationFactory.getLoginController();
            this.parentForm = parentForm;
        }

        private void LoginButton_Click(object sender, EventArgs e)
        {
            string username = UserNameTextBox.Text;
            string password = PasswordTextBox.Text;

            User loggedUser = loginController.GetUser(username, password);
            if (loggedUser == null)
            {
                MessageBox.Show("The credentials are not valid");
            }
            else
            {
                if (loginController.IsConferenceActive() == true)
                {
                    string activePhaseName = loginController.ActiveConference().ActivePhase.Name;
                    Form toBeShown = null;
                    switch (activePhaseName)
                    {
                        case "PRELIMINARY":
                            if (loginController.GetUserRoles(loggedUser).Select(role => role.Slug).Contains("chair") ||
                                loginController.GetUserRoles(loggedUser).Select(role => role.Slug).Contains("reviewer"))
                            {
                                toBeShown = new PreliminaryPhase(this, loggedUser);
                            }
                            else
                            {
                                //User is a non-chair member and is restricted to access the website
                                MessageBox.Show("The conference is yet in preliminary phase!\nPlease wait until the set up is complete!");
                                return;
                            }
                            break;
                        case "PHASEONE":
                            toBeShown = new UserAccount(this, loggedUser);
                            break;
                        case "PHASETWO":
                            if (loginController.GetUserRoles(loggedUser).Select(role => role.Slug).Contains("chair"))
                            {
                                toBeShown = new ChairMain(this, loggedUser);
                            }
                            else if (loginController.GetUserRoles(loggedUser).Select(role => role.Slug).Contains("reviewer"))
                            {
                                toBeShown = new PCMemberMain(this, loggedUser);
                            }
                            else if (loginController.GetUserRoles(loggedUser).Select(role => role.Slug).Contains("author")
                                || loginController.GetUserRoles(loggedUser).Select(role => role.Slug).Contains("speaker"))
                            {
                                toBeShown = new AuthorMain(this, loggedUser);
                            }
                            else if (loginController.GetUserRoles(loggedUser).Select(role => role.Slug).Contains("listner"))
                            {
                                toBeShown = new ListenerMain(this, loggedUser);
                            }
                            break;
                        case "PHASETHREE":
                            if (loginController.GetUserRoles(loggedUser).Select(role => role.Slug).Contains("listner"))
                            {
                                toBeShown = new UI.PhaseThree.ListenerMain(this, loggedUser);
                            }
                            else if (loginController.GetUserRoles(loggedUser).Select(role => role.Slug).Contains("chair"))
                            {
                                toBeShown = new RoomsDistribution(this);
                            }
                            else
                            {
                                MessageBox.Show("Conference is current commencing", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            break;
                    }
                    if (toBeShown != null)
                    {
                        toBeShown.Location = new System.Drawing.Point(Location.X, Location.Y);
                        toBeShown.Show();
                        Hide();
                    }
                }
                else
                {
                    if (loginController.GetUserRoles(loggedUser).Select(role => role.Slug).ToArray().Contains("chair"))
                    {
                        //User is a chair and is shown the preliminary phase
                        PreliminaryPhase preliminaryPhase = new PreliminaryPhase(this, loggedUser);
                        preliminaryPhase.Location = new System.Drawing.Point(Location.X, Location.Y);
                        preliminaryPhase.Show();
                        Hide();
                    }
                    else
                    {
                        //User is a non-chair member and is restricted to access the website
                        MessageBox.Show("There is no active conference for the moment!");
                    }
                }
            }
        }

        private void buttonBack_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void Login_Load(object sender, EventArgs e)
        {
            AcceptButton = LoginButton;
        }

        private void Login_FormClosing(object sender, FormClosingEventArgs e)
        {
            parentForm.Location = new System.Drawing.Point(Location.X, Location.Y);
            parentForm.Show();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ResetPassword resetPasswordForm = new ResetPassword(this, loginController);
            resetPasswordForm.Location = new System.Drawing.Point(Location.X, Location.Y);
            Hide();
            resetPasswordForm.Show();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
from copy import copy

class SortingUtilClass:

	@staticmethod
	def list_to_string(values):
		count = len(values) - 1
		res = ''
		for n in values:
			fmt_string = '{:<3}'
			res += fmt_string.format(n)
		return res

	@staticmethod
	def print_results(comparisons, swaps):
		print()
		print('Analysis: ')
		print('\t{0:<12}  {1:>3}'.format('Comarisons:', comparisons))
		print('\t{0:<12}  {1:>3}'.format('Swaps:', swaps))
		print('\t{0:<12}  {1:>3}'.format('Work:', comparisons + (5 * swaps)))
		print()

	@staticmethod
	def print_title(assign_num, title):
		print('Tyberius Enders')
		print('Assignment {} - {}'.format(assign_num, title))
		print()

	@staticmethod
	def print_loop_position(num, array):
		print('Loop #{0}    Array = {1}'.format(num, SortingUtilClass.list_to_string(array)))

	@staticmethod
	def print_comparison_level(array, comparison, spacing, print_list, adjust):
		print('Comparison'.rjust(14), end=' ')
		print('#{}'.format(comparison).ljust(spacing), end='')
		print('{}'.format(SortingUtilClass.list_to_string(print_list)).rjust(adjust))

	@staticmethod
	def print_comparison_simple(comparison, values, low, high, **kwargs):
		fmt = 'Comparison #{}'.format(comparison)
		end_char = '\n'
		if kwargs['stop']:
			end_char = ''
		if (comparison / 10) < 1:
			print(fmt.rjust(18), end='')
		else:
			print(fmt.rjust(19), end='')

		base_spaces = 3*low + 6

		print('{}'.format(values[low]).rjust(base_spaces), end=end_char)
		if kwargs['stop']:
			print('{}'.format('(Stop)').rjust(8))

	@staticmethod
	def print_swap_simple(swap, values, low, high):
		fmt = 'Swap #{}'.format(swap)
		if (swap / 10) < 1:
			print(fmt.rjust(12), end='')
		else:
			print(fmt.rjust(13), end='')
		print('{}'.format(values[low]).rjust(3*low+12), end='')
		print('{}'.format(values[high]).rjust(3*(high-low)))

	@staticmethod
	def print_swap_level(array, swap, spacing, print_list, adjust):
		print('Swap'.rjust(8), end=' ')
		print('#{}'.format(swap).ljust(spacing), end='')
		print('{}'.format(SortingUtilClass.list_to_string(print_list).rjust(adjust)))

	@staticmethod
	def print_pivot_level(pivot):
		pivot_spaces = 14
		if (pivot / 10) >= 1:
			pivot_spaces = 15
		print('Pivot = {}'.format(pivot).rjust(pivot_spaces))

	@staticmethod
	def print_level_with_array(level, array):
		print('Level {}:'.format(level), end='')
		print('Array = {}'.format(SortingUtilClass.list_to_string(array)).rjust(15 + len(array) * 3))

	@staticmethod
	def print_high_low(high, low):
		low_spaces = 12
		if (low / 10) >= 1:
			low_spaces = 11
		print('Low = {}'.format(low).rjust(low_spaces))

		high_spaces = 13
		if (high / 10) >= 1:
			high_spaces = 14
		print('High = {}'.format(high).rjust(high_spaces))

	@staticmethod
	def print_qs_fn(low, high, index):
		a = low
		b = index - 1
		c = index + 1
		d = high
		if a > b:
			a, b = b, a
		if c > d:
			c, d = d, c
		print('Calling QS ({}-{}) and ({}-{})'.format(a, b, c, d))

	@staticmethod
	def print_char_line(char):
		for i in range(1,55):
			print(char, end='')
		print()

	@staticmethod
	def print_algorithm_title(title):
		SortingUtilClass.print_char_line('#')
		print(title)
		print()

class SortingClass:

	def __init__(self, to_print=True):
		self.comparisons = 1
		self.swaps = 1
		self.level = 1
		self.print = to_print

	def set_defaults(self):
		self.comparisons = 1
		self.swaps = 1
		self.level = 1

	def finish(self):
		if self.print:
			SortingUtilClass.print_results(self.comparisons, self.swaps)
		work = self.comparisons+(5*self.swaps)
		return dict(comparisons=self.comparisons, swaps=self.swaps, work=work, level=self.level)

	def get_analysis(self):
		work = self.comparisons + (5*self.swaps)
		return dict(comparisons=self.comparisons, swaps=self.swaps, work=work)

	def bubble_sort(self, values):
		n = len(values)
		for i in range(n):
			# print loop level
			if self.print:
				SortingUtilClass.print_loop_position(i+1,values)
			for j in range(1,n):
				# print comparison
				if self.print:
					SortingUtilClass.print_comparison_level(values, self.comparisons, 3*(j - 2) + 7, [values[j-1], values[j]], j)
				self.comparisons += 1
				if values[j-1] > values[j]:
					values[j-1], values[j] = values[j], values[j-1]
					# print swaps
					if self.print:
						SortingUtilClass.print_swap_level(values, self.swaps, 3*(j - 2) + 13, [values[j-1], values[j]], j)
					self.swaps += 1
		return self

	def insertion_sort(self, values):
		n = len(values)
		for i in range(1,n):
			j = i
			if self.print:
				SortingUtilClass.print_loop_position(j, values)
			while j > 0 and values[j-1] > values[j]:
				# print comparison
				if self.print:
					SortingUtilClass.print_comparison_level(values, self.comparisons, 3*(j - 1) + 4, [values[j-1], values[j]], j)
				self.comparisons += 1
				# swap values
				values[j-1], values[j] = values[j], values[j-1]
				# print swaps
				if self.print:
					SortingUtilClass.print_swap_level(values, self.swaps, 3*(j - 1) + 10, [values[j-1], values[j]], j)
				self.swaps += 1
				j -= 1
			else:
				# print comparison
				if self.print:
					SortingUtilClass.print_comparison_level(values, self.comparisons, 3*(j - 1) + 4, [values[j-1], values[j]], j)
				self.comparisons += 1
		return self

	def selection_sort(self, values):
		n = len(values)
		count = 1

		for i in range(n-1, 0, -1):
			# print loop level
			if self.print:
				SortingUtilClass.print_loop_position(count, values)
			maximum = self.max_key(0, i, values)
			# swap values
			values[maximum], values[i] = values[i], values[maximum]
			# print swaps
			if self.print:
				SortingUtilClass.print_swap_level(values, self.swaps, 3*(i-1) + 10, [values[maximum], values[i]], i)
			self.swaps += 1
			count += 1
		return self

	def max_key(self, low, high, values):
		largest = low
		for j in range(low+1, high+1):
			# print comparison
			if self.print:
				SortingUtilClass.print_comparison_level(values, self.comparisons, 3*(j - 1) + 4, [values[j-1], values[j]], j)
			self.comparisons += 1
			if values[largest] < values[j]:
				largest = j
			# print max and array
			if self.print:
				pass
		return largest

	# Assignment 4 methods
	def partition(self, values, low, high):
		pivot = values[high]
		i = low

		# print pivot
		if self.print:
			SortingUtilClass.print_pivot_level(pivot)
		for j in range(low, high):
			# print comparison
			if self.print:
				to_stop = False
				if values[j] >= pivot:
					to_stop = True
				SortingUtilClass.print_comparison_simple(self.comparisons, values, j, high, stop=to_stop)
			self.comparisons += 1
			if values[j] <= pivot:
				if self.print:
					print('Moving high...')
				values[i], values[j] = values[j], values[i]
				i += 1

		# swap values
		values[i], values[high] = values[high], values[i]
		if self.print:
			SortingUtilClass.print_swap_simple(self.swaps, values, i, high)
			print('{}'.format('Moving low...').rjust(18))
		self.swaps += 1
		return i

	def quick_sort(self, values, low, high):
		# print level
		# print array
		# print low
		# print high
		if self.print:
			SortingUtilClass.print_level_with_array(self.level, values)
			SortingUtilClass.print_high_low(high, low)
		if low < high:
			p = self.partition(values, low, high)
			self.level += 1
			# print 'Calling QS'...
			if self.print:
				SortingUtilClass.print_qs_fn(low, high, p)
			self.quick_sort(values, low, p - 1)
			self.quick_sort(values, p + 1, high)
		return self

	# Heap sort methods (Extra)
	def heap_sort(self, values, count):
		self.heapify(values, count)
		end = count - 1
		while end > 0:
			values[end], values[0] = values[0], values[end]
			self.swaps += 1
			end -= 1
			self.sift_down(values, 0, end)
		return self

	def heapify(self, values, count):
		start = int((count - 2) / 2)

		while start >= 0:
			self.sift_down(values, start, count - 1)
			start -= 1

	def sift_down(self, values, start, end):
		root = start

		while root * 2 + 1 <= end:
			child = root * 2 + 1

			if child + 1 <= end and values[child] < values[child + 1]:
				child += 1
				self.comparisons += 1
			if values[root] < values[child]:
				values[root], values[child] = values[child], values[root]
				self.swaps += 1
				root = child
				self.comparisons += 1
			else:
				return

	def all(self, orig):
		values = copy(orig)
		self.set_defaults()
		if self.print:
			SortingUtilClass.print_algorithm_title('Bubble Sort')
		self.bubble_sort(values).finish()

		values = copy(orig)
		self.set_defaults()
		if self.print:
			SortingUtilClass.print_algorithm_title('Insertion Sort')
		self.insertion_sort(values).finish()

		values = copy(orig)
		self.set_defaults()
		if self.print:
			SortingUtilClass.print_algorithm_title('Selection Sort')
		self.selection_sort(values).finish()

		values = copy(orig)
		self.set_defaults()
		if self.print:
			SortingUtilClass.print_algorithm_title('Quick Sort')
		self.quick_sort(values, 0, len(values) - 1).finish()

		values = copy(orig)
		self.set_defaults()
		if self.print:
			SortingUtilClass.print_algorithm_title('Heap Sort')
		self.heap_sort(values, len(values)).finish()


text:
/*! \file MemoryRaceDetector.h
	\date Wednesday March 24, 2010
	\author Gregory Diamos <gregory.diamos@gatech.edu>
	\brief The header file for the MemoryRaceDetector class.
*/

#ifndef MEMORY_RACE_DETECTOR_H_INCLUDED
#define MEMORY_RACE_DETECTOR_H_INCLUDED

// Ocelot includes
#include <ocelot/ir/interface/Dim3.h>
#include <ocelot/trace/interface/TraceGenerator.h>

namespace executive
{
	class EmulatedKernel;
}

namespace trace
{
	/*! \brief A trace generator for checking memory races */
	class MemoryRaceDetector : public TraceGenerator
	{
		public:
			/*! \brief A vector of integers */
			typedef std::vector< int > IntVector;
			/*! \brief A vector of bytes */
			typedef std::vector< char > ByteVector;

		private:
			/*! \brief The block dimensions */
			ir::Dim3 _dim;
			/*! \brief The last writer to each byte in shared memory */
			IntVector _writers;
			/*! \brief The last reader from each byte in shared memory */
			IntVector _readers;
			/*! \brief The data in shared memory before the last write */
			ByteVector _previousData;
			/*! \brief A pointer to the executable kernel */
			const executive::EmulatedKernel* _kernel;
			/*! \brief Always check writes even if the data matches */
			bool _alwaysCheckWrites;

		private:
			/*! \brief Check a shared memory write */
			void _write( const TraceEvent& event );
			/*! \brief Check after the data has been written */
			void _postWrite( const TraceEvent& event );
			/*! \brief Check a shared memory read */
			void _read( const TraceEvent& event );
			/*! \brief Encounter a barrier */
			void _barrier();

		public:
			/*! \brief The constructor initializes the cached allocations */
			MemoryRaceDetector();

			/*! \brief Determine whether writes should be checked regardless
				of whether or not the previous data matches */
			void checkAllWrites( bool check );

		public:
			/*! \brief Set the cache and get a pointer to the memory mappings */
			virtual void initialize(
				const executive::ExecutableKernel& kernel );

			/*! \brief Called whenever an event takes place.

				Note, the const reference 'event' is only valid until event()
				returns
			*/
			virtual void event( const TraceEvent& event );

			/*! \brief Called whenever an event takes place.

				Note, the const reference 'event' is only valid until event()
				returns
			*/
			virtual void postEvent( const TraceEvent& event );

			/*!  \brief Called when a kernel is finished. There will be no more
					events for this kernel.
			*/
			virtual void finish();

	};
}

#endif


text:
import {TaskQueue} from './task-queue.js';
import { Task } from './task.js';

/**
 * An object that controls when tasks are executed from a queue or set of
 * queues.
 */
export interface QueueScheduler<Q extends TaskQueue<T>, T extends Task<any>> {
  schedule(queue: Q): void;
}


text:
var W=window,E=W.Element,P="prototype";

W.$$ = function(s, c){
    return (c ? c : document)['querySelectorAll'](s);
};

W.NodeList[P].each = Array[P].forEach;
W.NodeList[P].forEach = Array[P].forEach;

E[P].find=function(q){
    return $$(q, this);
};

E[P].attr=function(key, value){
    if(value){
        this.setAttribute(key, value);
        return this;
    }else{
        return this.getAttribute(key);
    }
};

E[P].css=function(prop, value){
    if(value){
        this.style[prop]=value;
        return this;
    }else{
        return this.style[prop];
    }
};

E[P].on=function(type, callback){
    this.addEventListener(type, callback);
    return this;
};


text:
var gutil   = require('gulp-util')

// Require browserify and watchify from the parent so that their versions are
// not tied to gulp-watchify
try {
  var browserify = module.parent.require('browserify'),
      watchify = module.parent.require('watchify');
} catch(e) {
  var parentFile = module.parent.id
  throw new Error([
    gutil.colors.red('Local browserify or watchify not found in ' + parentFile),
    gutil.colors.red('Try running: ' + 'npm install browserify watchify')
  ].join("\n"))
}

function log() {
  var args = Array.prototype.slice.call(arguments)
  var prefix = [gutil.colors.magenta('[gulp-watchify]')]
  args[0] = prefix + ' ' + args[0]
  return gutil.log.apply(this,args);
}

function rebundle(opts) {
  var _  = require('underscore'),
  source = require('vinyl-source-stream');

  var stream = opts.stream,
  bundler    = opts.bundler;

  bundler.compiles = bundler.compiles || 0
  bundler.compiles++

  if (typeof bundler.start_time !== "undefined" && bundler.start_time !== null) {
    log('time since last execution: ' + gutil.colors.cyan(Date.now() - bundler.start_time + 'ms'))
  }
  bundler.start_time = Date.now()

  // Form bundle
  bundle = bundler.bundle()

  // Catch errors
  bundle.on('error', (function(_this) {
    return function(err) {
      gutil.log(gutil.colors.red("" + (err.annotated || err.message)))
      return stream.emit('end')
    }
  })(this))

  var browserifyStream = bundle.pipe(source(opts.filename))
  browserifyStream.on('data', (function(_this) {
    return function(data) {
      // Forward data returned to opts.stream
      stream.emit('data', data)

      // Log compilation time
      var start_time = bundler.start_time
      var end_time = Date.now()

      if (end_time - start_time > 0) {
        log('compiled in ' + gutil.colors.cyan((end_time - start_time) + 'ms'))
      }

      if (bundler.compiles >= 1 && opts.watch === false) {
        // Close stream if not in watch mode
        stream.emit('end')
        return bundler.close()
      }
    }
  })(this))
  return bundle;
}

module.exports = function(opts) {
  var _       = require('underscore'),
  eventStream = require('event-stream');

  var ctx = {rebundle: rebundle}

  opts = _.defaults(opts, {watch: false, filename: 'app.js'})

  var stream = eventStream.writeArray(function(err, files) {
    var entries = _.pluck(files, 'path')

    var browserifyOpts = _.omit(_.extend(opts, {
      cache: {},
      packageCache: {},
      entries: entries,
    }), 'watch', 'filename')

    var bundler = watchify(browserify(browserifyOpts))
    stream.emit('prebundle', bundler)

		// Compile files once, as well as whenever the bundle changes
    var rebundle = this.rebundle.bind(null, _.extend(
      opts, {
        stream: stream,
        bundler: bundler
      }
    ))
    bundler.on('update', rebundle)
    return rebundle();
  }.bind(ctx))

  return stream;
};


text:
from nose.tools import eq_, ok_
from mock import Mock, patch

from jenks.data import JenksData

config_dict = {
    'localhost': {
        'url': 'http://localhost:8080',
        'jobs': [
            'foo',
            'bar'
        ]
    }
}

class TestData(object):

    def setUp(self):
        self.data = JenksData(config_dict)

    def test_job_keys(self):
        """ job_keys() should return a list of sorted one-character keys"""
        result_keys = ('0', '1')
        for return_key, result_key in zip(self.data.job_keys(), result_keys):
            eq_(return_key, result_key)

    def test_get_jobs_from_arguments(self):
        """ get_jobs_from_arguments(":<keys>") should return all JenksJob objects """
        jobs = self.data.get_jobs_from_argument(":01")
        ok_(any(map(lambda x: x.name == 'foo', jobs)))
        ok_(any(map(lambda x: x.name == 'bar', jobs)))

    def test_add_job(self):
        """ add_job(<host>, <job_name>) should add the job to the JenksData object """
        self.data.add_job("localhost", "baz")
        ok_(self.data.has_job('localhost', 'baz'))

    def test_add_job_host_url(self):
        """ add_job(<host_url>, <job_name>) should add the job to the JenksData object """
        self.data.add_job("http://localhost:8080", "baz")
        ok_(self.data.has_job('localhost', 'baz'))

    def test_get_host(self):
        """ get_host(<host>) should return a host object """
        with patch('jenkinsapi.jenkins.Jenkins') as jenkins:
            host = self.data.get_host('localhost')
            isinstance(host, Mock)
            jenkins.assert_called_with('http://localhost:8080')

    def test_hosts(self):
        """" hosts() should return a list of hosts """
        eq_(list(self.data.hosts()), ['localhost'])

    # TODO test sort order of jobs


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

<TITLE>
Uses of Package simpledb.record
</TITLE>

<META NAME="date" CONTENT="2008-07-30">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
simpledb.record

Packages that use simpledb.record

simpledb.index

simpledb.index.btree

simpledb.index.hash

simpledb.index.query

simpledb.materialize

simpledb.metadata

simpledb.multibuffer

simpledb.parse

simpledb.query

simpledb.record

simpledb.remote

Classes in simpledb.record used by simpledb.index

RID

          An identifier for a record within a file.

Classes in simpledb.record used by simpledb.index.btree

RID

          An identifier for a record within a file.

Schema

          The record schema of a table.

TableInfo

          The metadata about a table and its records.

Classes in simpledb.record used by simpledb.index.hash

RID

          An identifier for a record within a file.

Schema

          The record schema of a table.

Classes in simpledb.record used by simpledb.index.query

Schema

          The record schema of a table.

Classes in simpledb.record used by simpledb.materialize

Schema

          The record schema of a table.

TableInfo

          The metadata about a table and its records.

Classes in simpledb.record used by simpledb.metadata

Schema

          The record schema of a table.

TableInfo

          The metadata about a table and its records.

Classes in simpledb.record used by simpledb.multibuffer

Schema

          The record schema of a table.

TableInfo

          The metadata about a table and its records.

Classes in simpledb.record used by simpledb.parse

Schema

          The record schema of a table.

Classes in simpledb.record used by simpledb.query

RID

          An identifier for a record within a file.

Schema

          The record schema of a table.

TableInfo

          The metadata about a table and its records.

Classes in simpledb.record used by simpledb.record

RID

          An identifier for a record within a file.

Schema

          The record schema of a table.

TableInfo

          The metadata about a table and its records.

Classes in simpledb.record used by simpledb.remote

Schema

          The record schema of a table.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
package armhelpers

import (
	"github.com/Azure/azure-sdk-for-go/arm/resources/resources"
	"github.com/Azure/go-autorest/autorest"
	"github.com/prometheus/common/log"
)

// EnsureResourceGroup ensures the named resouce group exists in the given location.
func (az *AzureClient) EnsureResourceGroup(name, location string) (resourceGroup *resources.Group, err error) {
	log.Debugf("Ensuring resource group exists. resourcegroup=%q", name)
	response, err := az.groupsClient.CreateOrUpdate(name, resources.Group{
		Name:     &name,
		Location: &location,
	})
	if err != nil {
		return &response, err
	}

	return &response, nil
}

// CheckResourceGroupExistence return if the resource group exists
func (az *AzureClient) CheckResourceGroupExistence(name string) (result autorest.Response, err error) {
	return az.groupsClient.CheckExistence(name)
}

// DeleteResourceGroup delete the named resource group
func (az *AzureClient) DeleteResourceGroup(name string, cancel chan struct{}) (<-chan autorest.Response, <-chan error) {
	return az.groupsClient.Delete(name, cancel)
}


text: def do_stuff(): print("the good stuff")


text:
LDFLAGS		:=

LDFLAGS_vmlinux	:=-p --no-undefined -X
ifeq ($(CONFIG_CPU_ENDIAN_BE8),y)
LDFLAGS_vmlinux	+= --be8
LDFLAGS_MODULE	+= --be8
endif

OBJCOPYFLAGS	:=-O binary -R .comment -S
GZFLAGS		:=-9
#KBUILD_CFLAGS	+=-pipe

# Never generate .eh_frame
KBUILD_CFLAGS	+= $(call cc-option,-fno-dwarf2-cfi-asm)

# Do not use arch/arm/defconfig - it's always outdated.
# Select a platform tht is kept up-to-date
KBUILD_DEFCONFIG := versatile_defconfig

# defines filename extension depending memory management type.
ifeq ($(CONFIG_MMU),)
MMUEXT		:= -nommu
KBUILD_CFLAGS	+= $(call cc-option,-mno-unaligned-access)
endif

ifeq ($(CONFIG_FRAME_POINTER),y)
KBUILD_CFLAGS	+=-fno-omit-frame-pointer -mapcs -mno-sched-prolog
endif

ifeq ($(CONFIG_CC_STACKPROTECTOR),y)
KBUILD_CFLAGS	+=-fstack-protector
endif

ifeq ($(CONFIG_CPU_BIG_ENDIAN),y)
KBUILD_CPPFLAGS	+= -mbig-endian
AS		+= -EB
LD		+= -EB
else
KBUILD_CPPFLAGS	+= -mlittle-endian
AS		+= -EL
LD		+= -EL
endif

comma = ,

#
# The Scalar Replacement of Aggregates (SRA) optimization pass in GCC 4.9 and
# later may result in code being generated that handles signed short and signed
# char struct members incorrectly. So disable it.
# (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65932)
#
KBUILD_CFLAGS	+= $(call cc-option,-fno-ipa-sra)

# This selects which instruction set is used.
# Note that GCC does not numerically define an architecture version
# macro, but instead defines a whole series of macros which makes
# testing for a specific architecture or later rather impossible.
arch-$(CONFIG_CPU_32v7)		:=-D__LINUX_ARM_ARCH__=7 $(call cc-option,-march=armv7-a,-march=armv5t -Wa$(comma)-march=armv7-a)
arch-$(CONFIG_CPU_32v6)		:=-D__LINUX_ARM_ARCH__=6 $(call cc-option,-march=armv6,-march=armv5t -Wa$(comma)-march=armv6)
# Only override the compiler option if ARMv6. The ARMv6K extensions are
# always available in ARMv7
ifeq ($(CONFIG_CPU_32v6),y)
arch-$(CONFIG_CPU_32v6K)	:=-D__LINUX_ARM_ARCH__=6 $(call cc-option,-march=armv6k,-march=armv5t -Wa$(comma)-march=armv6k)
endif
arch-$(CONFIG_CPU_32v5)		:=-D__LINUX_ARM_ARCH__=5 $(call cc-option,-march=armv5te,-march=armv4t)
arch-$(CONFIG_CPU_32v4T)	:=-D__LINUX_ARM_ARCH__=4 -march=armv4t
arch-$(CONFIG_CPU_32v4)		:=-D__LINUX_ARM_ARCH__=4 -march=armv4
arch-$(CONFIG_CPU_32v3)		:=-D__LINUX_ARM_ARCH__=3 -march=armv3

# This selects how we optimise for the processor.
tune-$(CONFIG_CPU_ARM7TDMI)	:=-mtune=arm7tdmi
tune-$(CONFIG_CPU_ARM720T)	:=-mtune=arm7tdmi
tune-$(CONFIG_CPU_ARM740T)	:=-mtune=arm7tdmi
tune-$(CONFIG_CPU_ARM9TDMI)	:=-mtune=arm9tdmi
tune-$(CONFIG_CPU_ARM940T)	:=-mtune=arm9tdmi
tune-$(CONFIG_CPU_ARM946E)	:=$(call cc-option,-mtune=arm9e,-mtune=arm9tdmi)
tune-$(CONFIG_CPU_ARM920T)	:=-mtune=arm9tdmi
tune-$(CONFIG_CPU_ARM922T)	:=-mtune=arm9tdmi
tune-$(CONFIG_CPU_ARM925T)	:=-mtune=arm9tdmi
tune-$(CONFIG_CPU_ARM926T)	:=-mtune=arm9tdmi
tune-$(CONFIG_CPU_FA526)	:=-mtune=arm9tdmi
tune-$(CONFIG_CPU_SA110)	:=-mtune=strongarm110
tune-$(CONFIG_CPU_SA1100)	:=-mtune=strongarm1100
tune-$(CONFIG_CPU_XSCALE)	:=$(call cc-option,-mtune=xscale,-mtune=strongarm110) -Wa,-mcpu=xscale
tune-$(CONFIG_CPU_XSC3)		:=$(call cc-option,-mtune=xscale,-mtune=strongarm110) -Wa,-mcpu=xscale
tune-$(CONFIG_CPU_FEROCEON)	:=$(call cc-option,-mtune=marvell-f,-mtune=xscale)
tune-$(CONFIG_CPU_V6)		:=$(call cc-option,-mtune=arm1136j-s,-mtune=strongarm)
tune-$(CONFIG_CPU_V6K)		:=$(call cc-option,-mtune=arm1136j-s,-mtune=strongarm)

ifeq ($(CONFIG_AEABI),y)
CFLAGS_ABI	:=-mabi=aapcs-linux -mno-thumb-interwork
else
CFLAGS_ABI	:=$(call cc-option,-mapcs-32,-mabi=apcs-gnu) $(call cc-option,-mno-thumb-interwork,)
endif

ifeq ($(CONFIG_ARM_UNWIND),y)
CFLAGS_ABI	+=-funwind-tables
endif

ifeq ($(CONFIG_THUMB2_KERNEL),y)
AFLAGS_AUTOIT	:=$(call as-option,-Wa$(comma)-mimplicit-it=always,-Wa$(comma)-mauto-it)
AFLAGS_NOWARN	:=$(call as-option,-Wa$(comma)-mno-warn-deprecated,-Wa$(comma)-W)
CFLAGS_ISA	:=-mthumb $(AFLAGS_AUTOIT) $(AFLAGS_NOWARN)
AFLAGS_ISA	:=$(CFLAGS_ISA) -Wa$(comma)-mthumb
# Work around buggy relocation from gas if requested:
ifeq ($(CONFIG_THUMB2_AVOID_R_ARM_THM_JUMP11),y)
CFLAGS_MODULE	+=-fno-optimize-sibling-calls
endif
else
CFLAGS_ISA	:=$(call cc-option,-marm,)
AFLAGS_ISA	:=$(CFLAGS_ISA)
endif

# Need -Uarm for gcc < 3.x
KBUILD_CFLAGS	+=$(CFLAGS_ABI) $(CFLAGS_ISA) $(arch-y) $(tune-y) $(call cc-option,-mshort-load-bytes,$(call cc-option,-malignment-traps,)) -msoft-float -Uarm
KBUILD_AFLAGS	+=$(CFLAGS_ABI) $(AFLAGS_ISA) $(arch-y) $(tune-y) -include asm/unified.h -msoft-float

CHECKFLAGS	+= -D__arm__

#Default value
head-y		:= arch/arm/kernel/head$(MMUEXT).o
textofs-y	:= 0x00008000
textofs-$(CONFIG_ARCH_CLPS711X) := 0x00028000
# We don't want the htc bootloader to corrupt kernel during resume
textofs-$(CONFIG_PM_H1940)      := 0x00108000
# SA1111 DMA bug: we don't want the kernel to live in precious DMA-able memory
ifeq ($(CONFIG_ARCH_SA1100),y)
textofs-$(CONFIG_SA1111) := 0x00208000
endif
textofs-$(CONFIG_ARCH_MSM7X30) := 0x00208000
textofs-$(CONFIG_ARCH_MSM8X60) := 0x00208000
textofs-$(CONFIG_ARCH_MSM8960) := 0x00208000

# Machine directory name.  This list is sorted alphanumerically
# by CONFIG_* macro name.
machine-$(CONFIG_ARCH_AT91)		+= at91
machine-$(CONFIG_ARCH_BCM)		+= bcm
machine-$(CONFIG_ARCH_BCM2835)		+= bcm2835
machine-$(CONFIG_ARCH_CLPS711X)		+= clps711x
machine-$(CONFIG_ARCH_CNS3XXX)		+= cns3xxx
machine-$(CONFIG_ARCH_DAVINCI)		+= davinci
machine-$(CONFIG_ARCH_DOVE)		+= dove
machine-$(CONFIG_ARCH_EBSA110)		+= ebsa110
machine-$(CONFIG_ARCH_EP93XX)		+= ep93xx
machine-$(CONFIG_ARCH_GEMINI)		+= gemini
machine-$(CONFIG_ARCH_HIGHBANK)		+= highbank
machine-$(CONFIG_ARCH_INTEGRATOR)	+= integrator
machine-$(CONFIG_ARCH_IOP13XX)		+= iop13xx
machine-$(CONFIG_ARCH_IOP32X)		+= iop32x
machine-$(CONFIG_ARCH_IOP33X)		+= iop33x
machine-$(CONFIG_ARCH_IXP4XX)		+= ixp4xx
machine-$(CONFIG_ARCH_KIRKWOOD)		+= kirkwood
machine-$(CONFIG_ARCH_KS8695)		+= ks8695
machine-$(CONFIG_ARCH_LPC32XX)		+= lpc32xx
machine-$(CONFIG_ARCH_MMP)		+= mmp
machine-$(CONFIG_ARCH_MSM)		+= msm
machine-$(CONFIG_ARCH_MV78XX0)		+= mv78xx0
machine-$(CONFIG_ARCH_MXC)		+= imx
machine-$(CONFIG_ARCH_MXS)		+= mxs
machine-$(CONFIG_ARCH_MVEBU)		+= mvebu
machine-$(CONFIG_ARCH_NETX)		+= netx
machine-$(CONFIG_ARCH_NOMADIK)		+= nomadik
machine-$(CONFIG_ARCH_OMAP1)		+= omap1
machine-$(CONFIG_ARCH_OMAP2PLUS)	+= omap2
machine-$(CONFIG_ARCH_ORION5X)		+= orion5x
machine-$(CONFIG_ARCH_PICOXCELL)	+= picoxcell
machine-$(CONFIG_ARCH_PRIMA2)		+= prima2
machine-$(CONFIG_ARCH_PXA)		+= pxa
machine-$(CONFIG_ARCH_REALVIEW)		+= realview
machine-$(CONFIG_ARCH_RPC)		+= rpc
machine-$(CONFIG_ARCH_S3C24XX)		+= s3c24xx
machine-$(CONFIG_ARCH_S3C64XX)		+= s3c64xx
machine-$(CONFIG_ARCH_S5P64X0)		+= s5p64x0
machine-$(CONFIG_ARCH_S5PC100)		+= s5pc100
machine-$(CONFIG_ARCH_S5PV210)		+= s5pv210
machine-$(CONFIG_ARCH_EXYNOS)		+= exynos
machine-$(CONFIG_ARCH_SA1100)		+= sa1100
machine-$(CONFIG_ARCH_SHARK)		+= shark
machine-$(CONFIG_ARCH_SHMOBILE) 	+= shmobile
machine-$(CONFIG_ARCH_TEGRA)		+= tegra
machine-$(CONFIG_ARCH_U300)		+= u300
machine-$(CONFIG_ARCH_U8500)		+= ux500
machine-$(CONFIG_ARCH_VERSATILE)	+= versatile
machine-$(CONFIG_ARCH_VEXPRESS)		+= vexpress
machine-$(CONFIG_ARCH_VT8500)		+= vt8500
machine-$(CONFIG_ARCH_W90X900)		+= w90x900
machine-$(CONFIG_FOOTBRIDGE)		+= footbridge
machine-$(CONFIG_ARCH_SOCFPGA)		+= socfpga
machine-$(CONFIG_PLAT_SPEAR)		+= spear
machine-$(CONFIG_ARCH_VIRT)		+= virt
machine-$(CONFIG_ARCH_ZYNQ)		+= zynq
machine-$(CONFIG_ARCH_SUNXI)		+= sunxi

# Platform directory name.  This list is sorted alphanumerically
# by CONFIG_* macro name.
plat-$(CONFIG_ARCH_OMAP)	+= omap
plat-$(CONFIG_ARCH_S3C64XX)	+= samsung
plat-$(CONFIG_PLAT_IOP)		+= iop
plat-$(CONFIG_PLAT_ORION)	+= orion
plat-$(CONFIG_PLAT_PXA)		+= pxa
plat-$(CONFIG_PLAT_S3C24XX)	+= samsung
plat-$(CONFIG_PLAT_S5P)		+= samsung
plat-$(CONFIG_PLAT_VERSATILE)	+= versatile

ifeq ($(CONFIG_ARCH_EBSA110),y)
# This is what happens if you forget the IOCS16 line.
# PCMCIA cards stop working.
CFLAGS_3c589_cs.o :=-DISA_SIXTEEN_BIT_PERIPHERAL
export CFLAGS_3c589_cs.o
endif

# The byte offset of the kernel image in RAM from the start of RAM.
TEXT_OFFSET := $(textofs-y)

# The first directory contains additional information for the boot setup code
ifneq ($(machine-y),)
MACHINE  := arch/arm/mach-$(word 1,$(machine-y))/
else
MACHINE  :=
endif
ifeq ($(CONFIG_ARCH_MULTIPLATFORM),y)
MACHINE  :=
endif

machdirs := $(patsubst %,arch/arm/mach-%/,$(machine-y))
platdirs := $(patsubst %,arch/arm/plat-%/,$(plat-y))

ifneq ($(CONFIG_ARCH_MULTIPLATFORM),y)
ifeq ($(KBUILD_SRC),)
KBUILD_CPPFLAGS += $(patsubst %,-I%include,$(machdirs) $(platdirs))
else
KBUILD_CPPFLAGS += $(patsubst %,-I$(srctree)/%include,$(machdirs) $(platdirs))
endif
endif

export	TEXT_OFFSET GZFLAGS MMUEXT

# Do we have FASTFPE?
FASTFPE		:=arch/arm/fastfpe
ifeq ($(FASTFPE),$(wildcard $(FASTFPE)))
FASTFPE_OBJ	:=$(FASTFPE)/
endif

core-$(CONFIG_FPE_NWFPE)	+= arch/arm/nwfpe/
core-$(CONFIG_FPE_FASTFPE)	+= $(FASTFPE_OBJ)
core-$(CONFIG_VFP)		+= arch/arm/vfp/
core-$(CONFIG_XEN)		+= arch/arm/xen/
core-$(CONFIG_KVM_ARM_HOST) 	+= arch/arm/kvm/

# If we have a machine-specific directory, then include it in the build.
core-y				+= arch/arm/kernel/ arch/arm/mm/ arch/arm/common/
core-y				+= arch/arm/net/
core-y				+= arch/arm/crypto/
core-y				+= $(machdirs) $(platdirs)

drivers-$(CONFIG_OPROFILE)      += arch/arm/oprofile/

libs-y				:= arch/arm/lib/ $(libs-y)

# Default target when executing plain make
ifeq ($(CONFIG_XIP_KERNEL),y)
KBUILD_IMAGE := xipImage
else ifeq ($(CONFIG_BUILD_ARM_APPENDED_DTB_IMAGE),y)
KBUILD_IMAGE := zImage-dtb.$(CONFIG_BUILD_ARM_APPENDED_DTB_IMAGE_NAME)
else
KBUILD_IMAGE := zImage
endif

# Build the DT binary blobs if we have OF configured
ifeq ($(CONFIG_USE_OF),y)
KBUILD_DTBS := dtbs
endif

all:	$(KBUILD_IMAGE) $(KBUILD_DTBS)

boot := arch/arm/boot

archprepare:
	$(Q)$(MAKE) $(build)=arch/arm/tools include/generated/mach-types.h

# Convert bzImage to zImage
bzImage: zImage

zImage Image xipImage bootpImage uImage: vmlinux
	$(Q)$(MAKE) $(build)=$(boot) MACHINE=$(MACHINE) $(boot)/$@

zinstall uinstall install: vmlinux
	$(Q)$(MAKE) $(build)=$(boot) MACHINE=$(MACHINE) $@

%.dtb: scripts
	$(Q)$(MAKE) $(build)=$(boot)/dts MACHINE=$(MACHINE) $(boot)/dts/$@

dtbs: scripts
	$(Q)$(MAKE) $(build)=$(boot)/dts MACHINE=$(MACHINE) dtbs

# We use MRPROPER_FILES and CLEAN_FILES now
archclean:
	$(Q)$(MAKE) $(clean)=$(boot)

# My testing targets (bypasses dependencies)
bp:;	$(Q)$(MAKE) $(build)=$(boot) MACHINE=$(MACHINE) $(boot)/bootpImage
i zi:;	$(Q)$(MAKE) $(build)=$(boot) MACHINE=$(MACHINE) $@

define archhelp
  echo  '* zImage        - Compressed kernel image (arch/$(ARCH)/boot/zImage)'
  echo  '  Image         - Uncompressed kernel image (arch/$(ARCH)/boot/Image)'
  echo  '* xipImage      - XIP kernel image, if configured (arch/$(ARCH)/boot/xipImage)'
  echo  '  uImage        - U-Boot wrapped zImage'
  echo  '  bootpImage    - Combined zImage and initial RAM disk'
  echo  '                  (supply initrd image via make variable INITRD=<path>)'
  echo  '* dtbs          - Build device tree blobs for enabled boards'
  echo  '  install       - Install uncompressed kernel'
  echo  '  zinstall      - Install compressed kernel'
  echo  '  uinstall      - Install U-Boot wrapped compressed kernel'
  echo  '                  Install using (your) ~/bin/$(INSTALLKERNEL) or'
  echo  '                  (distribution) /sbin/$(INSTALLKERNEL) or'
  echo  '                  install to $$(INSTALL_PATH) and run lilo'
endef


text:
#pragma once
#include <aws/lightsail/Lightsail_EXPORTS.h>
#include <aws/lightsail/LightsailRequest.h>

namespace Aws
{
namespace Lightsail
{
namespace Model
{

  /**
   */
  class AWS_LIGHTSAIL_API PeerVpcRequest : public LightsailRequest
  {
  public:
    PeerVpcRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "PeerVpc"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

  };

} // namespace Model
} // namespace Lightsail
} // namespace Aws


text:
//
//  DropboxRelinquishFolderMembershipArg.h
//  Pods
//
//  Created by Михаил Мотыженков on 26.04.16.
//
//

#import <Foundation/Foundation.h>

@interface DropboxRelinquishFolderMembershipArg : NSObject

/**
 *  The ID for the shared folder.
 */
@property (nonatomic, nonnull) NSString *sharedFolderID;

- (nonnull instancetype)initWithSharedFolderID:(NSString * _Nonnull)sharedFolderID;

@end


text:
package cz.fg.issuetracking.procedure.requirements;

import cz.fg.issuetracking.api.Issue;
import cz.fg.issuetracking.api.IssueManager;
import cz.fg.issuetracking.api.procedure.CheckProcedure;
import cz.fg.issuetracking.api.procedure.ProcedureContext;

import java.util.List;

/**
 * Check all issues solved
 *
 * @author Michal Franc, FG Forrest a.s. (c) 2013
 *         18.8.13 22:16
 */
public class CheckAllIssuesSolvedInCurrentVersion implements CheckProcedure {

    IssueManager issueManager;

    @Override
    public void check(ProcedureContext context) {
        List<Issue> issues = issueManager.getUnderDevelopmentIssues();
        if (issues.size()>0) {
            throw new IllegalStateException("There are unsolved issues for current version");
        }
    }
}


text:
		<md-toolbar class="md-primary md-info">

I'm looking for an over-the-counter medication...

		</md-toolbar>

				<md-input-container layout="row" layout-sm="column" md-no-float>

						<md-icon md-svg-src="../../images/heart-outline.svg" style="fill:#3F51B5"></md-icon>

					<md-chips flex flex-sm="flex" class="include-chips md-display-1" ng-model="vm.purposes" md-on-append="vm.addChip($chip)"
					ng-keypress="vm.checkChipAdd($event, 'purpose')">
						<md-autocomplete md-autofocus="false" required md-selected-item="vm.selectedPurpose" input-name="purposeAutoComplete" md-search-text-change
						md-selected-item-change="vm.selectedItemChange(item)" md-search-text="vm.purposeText" md-items="item in vm.query(vm.purposeText, 'purpose')"
						md-item-text="item.value" md-delay="150" placeholder="For the purpose of">
							<md-item-template>

{{item.value}}

e.g., {{item.example}}

							</md-item-template>
							<md-not-found>

No matches found for "{{vm.purposeText}}".

							</md-not-found>
						</md-autocomplete>
						<md-chip-template>

								{{$chip.name}}

						</md-chip-template>
						<button md-chip-remove="" class="md-primary includechip">
							<md-icon md-svg-icon="md-close"></md-icon>
						</button>
					</md-chips>
				</md-input-container>
				<md-input-container layout="row" layout-sm="column" md-no-float>

						<md-icon md-svg-src="../../images/beaker-outline.svg" style="fill:#E91E63"></md-icon>

					<md-chips flex flex-sm="flex" class="exclude-chips" ng-model="vm.ingredients" md-on-append="vm.addChip($chip)" ng-keypress="vm.checkChipAdd($event, 'ingredient')">
						<md-autocomplete md-autofocus="false" md-search-text-change md-selected-item-change md-selected-item-change="vm.selectedItemChange(item)"
						md-selected-item="vm.selectedIngredient" md-search-text="vm.ingredientText" md-items="item in vm.query(vm.ingredientText, 'ingredient')"
						md-item-text="item.value" md-delay="150" placeholder="Without the ingredient">
							<md-item-template>

									{{item.value}}

									e.g., {{item.example}}

							</md-item-template>
							<md-not-found>

No matches found for "{{vm.ingredientText}}".

							</md-not-found>
						</md-autocomplete>
						<md-chip-template>

								{{$chip.name}}

						</md-chip-template>
						<button md-chip-remove="" class="md-primary excludechip">
							<md-icon md-svg-icon="md-close"></md-icon>
						</button>
					</md-chips>
				</md-input-container>
				<md-input-container>
					<md-button flex class="md-primary md-raised" ng-disabled="vm.productCount === 0" ng-click="vm.viewResults()">
						View
						{{ vm.productCount === undefined ? 0 : vm.productCount }}
						Matching Drugs
					</md-button>
				</md-input-container>


text:
package com.intellij.openapi.roots.impl;

import com.intellij.openapi.roots.ModuleFileIndex;
import com.intellij.openapi.roots.ModulePackageIndex;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.FilteredQuery;
import com.intellij.util.Query;
import org.jetbrains.annotations.NotNull;

public class ModulePackageIndexImpl extends ModulePackageIndex {
  private final ModuleFileIndex myModuleFileIndex;
  private final DirectoryIndex myDirectoryIndex;

  public ModulePackageIndexImpl(ModuleRootManager moduleRootManager, DirectoryIndex directoryIndex) {
    myModuleFileIndex = moduleRootManager.getFileIndex();
    myDirectoryIndex = directoryIndex;
  }

  private final Condition<VirtualFile> myDirCondition = new Condition<VirtualFile>() {
    @Override
    public boolean value(final VirtualFile dir) {
      return dir.isValid() && myModuleFileIndex.getOrderEntryForFile(dir) != null;
    }
  };

  @Override
  public Query<VirtualFile> getDirsByPackageName(@NotNull String packageName, boolean includeLibrarySources) {
    return new FilteredQuery<>(myDirectoryIndex.getDirectoriesByPackageName(packageName, includeLibrarySources), myDirCondition);
  }

  @Override
  public VirtualFile[] getDirectoriesByPackageName(@NotNull String packageName, boolean includeLibrarySources) {
    return getDirsByPackageName(packageName, includeLibrarySources).toArray(VirtualFile.EMPTY_ARRAY);
  }
}


text:
#ifndef XENIA_KERNEL_XBOXKRNL_XBOXKRNL_ORDINALS_H_
#define XENIA_KERNEL_XBOXKRNL_XBOXKRNL_ORDINALS_H_

#include "xenia/cpu/export_resolver.h"

// Build an ordinal enum to make it easy to lookup ordinals.
#include "xenia/kernel/util/ordinal_table_pre.inc"
namespace ordinals {
enum {
#include "xenia/kernel/xboxkrnl/xboxkrnl_table.inc"
};
}  // namespace ordinals
#include "xenia/kernel/util/ordinal_table_post.inc"

#endif  // XENIA_KERNEL_XBOXKRNL_XBOXKRNL_ORDINALS_H_


text:
package de.mhus.hair.jack.action;

import de.mhus.cap.core.CapCore;
import de.mhus.hair.jack.JackApplication;
import de.mhus.hair.jack.JackElement;
import de.mhus.lib.MActivator;
import de.mhus.lib.cao.CaoAction;
import de.mhus.lib.cao.CaoActionList;
import de.mhus.lib.cao.CaoException;
import de.mhus.lib.cao.CaoList;
import de.mhus.lib.cao.CaoOperation;
import de.mhus.lib.form.MForm;

public class DefaultOpenAction extends CaoAction {

	public DefaultOpenAction(MActivator activator, String resourceName) {
		super(activator, resourceName);
	}

	@Override
	public String getName() {
		return CapCore.ACTION_OPEN_WITH_SELECT;
	}

	@Override
	public MForm createConfiguration(CaoList list, Object... initConfig)
			throws CaoException {

		return null;
	}

	@Override
	public boolean canExecute(CaoList list, Object... initConfig) {
		if (list==null || list.size() != 1 || ! (list.getApplication() instanceof JackApplication) ) return false;

		return true;
	}

	@Override
	public CaoOperation execute(CaoList list, Object configuration)
			throws CaoException {

		CaoActionList actionList = new CaoActionList();
		CapCore.getInstance().getFactory().fillWithActions(null,list, actionList);

		JackElement element = (JackElement)list.getElements().next();
		CaoAction action = null;
		try {
			if (element.getNode().getPrimaryNodeType().getPrimaryItemName().equals("jcr:content")) {
				action = actionList.getAction("select.open");
			}
		} catch (Exception e) {
			//e.printStackTrace();
		}

		if (action == null) {
			try {
				if (element.getNode().getNodes().hasNext()) {
					action = actionList.getAction("select.open.list");
				} else {
					action = actionList.getAction("select.open.attributes");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (action != null && action.canExecute(list)) {
			MForm config = action.createConfiguration(list);
			return action.execute(list, config);
		}
		return null;
	}

}


text:
'use strict';

angular.module('myApp',
	[
		'ui.router',
		'myApp.wood'
	])

	.config(function ($urlRouterProvider) {

		$urlRouterProvider.otherwise('/wood');

	})
;


text:
package app.coronawarn.verification.model;

import io.swagger.v3.oas.annotations.media.Schema;

@Schema(
  description = "The TeleTan Type model."
)
public enum TeleTanType {

  @Schema(description = "TeleTan is issued because of a positive PCR Test")
  TEST,

  @Schema(description = "TeleTan is issued because of a confirmed infection at an event.")
  EVENT
}


text:
Form-Elements with Validation
            <?php
            $message=$this->session->userdata('message');
            if(isset($message))
            {
                echo "--".$message;
                $this->session->unset_userdata('message');

            }
            ?>

    <form  class="block-content form" action="<?php echo base_url();?>super_admin/update_moto" method="post">

Moto Title<input id="textfield" name="moto_title" class="required" type="text" value="<?php echo $moto_info->moto_title;?>" />
                <input id="textfield" name="moto_id" class="required" type="hidden" value="<?php echo $moto_info->moto_id;?>" />

Moto Description<textarea id="textarea" name="moto_description" class="required" rows="5" cols="40"><?php echo $moto_info->moto_description;?></textarea>

                Moto Logo
                <input id="textfield" name="moto_logo" class="required" type="file" value="<?php echo $moto_info->moto_logo;?>" />

                Publication Status
                <?php
                if($moto_info->publication_status==1)
                {
                ?>
                <input checked="checked" type="radio" name="publication_status" value="1" />Published
                <input type="radio" name="publication_status" value="0" />Unpublished
               <?php
                }
                else{
               ?>
                <input  type="radio" name="publication_status" value="1" />Published
                <input checked="checked" type="radio" name="publication_status" value="0" />Unpublished
                <?php } ?>

Reset

<input type="submit" class="button" value="Update Moto">

    </form>


text:
'use strict';
var gulp = require('gulp')
  , ngNewRouterTemplates = require('gulp-ng-new-router-templates');

gulp.task('templates', function () {
  return gulp.src(['**/*.tpl.html'])
    .pipe(ngNewRouterTemplates({
      extension: '.tpl.html',
      moduleName: 'angularNewRouterExample'
    }))
    .pipe(gulp.dest('./app'));
});


text:
let mongoose = require("../db");
let Schema = mongoose.Schema;
let ObjectId = Schema.Types.ObjectId

let navSchema = new Schema ({
    list:{
        type:Array
    }
})

let nav = mongoose.model("nav", navSchema);

nav.findNavList = () => {
    return nav.findOne()
    .exec()
}
nav.findNavUp = () => {
    return nav.findOne()
    .exec()
}
nav.addFindNav = (data) => {
    return nav.create(data)
    .exec()
}
module.exports = nav


text:
package com.github.drunlin.guokr.bean;

/**
 * 搜索结果的单个数据。
 *
 * @author drunlin@outlook.com
 */
public class SearchEntry {
    public String url;
    public String content;
    public String datetime;
}


text:
package GAL::Storage::SQLite;

use strict;
use vars qw($VERSION);

$VERSION = 0.2.0;
use base qw(GAL::Storage);

=head1 NAME

GAL::Storage::SQLite - SQLite feature storage for GAL

=head1 VERSION

This document describes GAL::Storage::SQLite version 0.2.0

=head1 SYNOPSIS

    use GAL::Storage::SQLite;
    my $storage = GAL::Storage::SQLite->new(dsn => 'dbi:SQLite:db_name');

=head1 DESCRIPTION

The L<GAL::Storage::SQLite> class provides SQLite based storage to
GAL.

=head1 CONSTRUCTOR

New GAL::Storage::SQLite objects are created by the class method new.
Arguments should be passed to the constructor as a list (or reference)
of key value pairs.  All attributes of the Storage object can be set
in the call to new. An simple example of object creation would look
like this:

    my $parser = GAL::Storage::SQLite->new(dsn => 'dbi:SQLite:db_name);

The constructor recognizes the following parameters which will set the
appropriate attributes:

=over 4

=item * C<scheme>

This is a read only parameter that is set to 'DBI';

=item * C<driver >

This is a read only parameter that is set to 'SQLite';

=item * C<database>

database => 'db_name'

This optional parameter defines the database name.  You don't need to
specify both the database name and the dsn as they both contain the
database name. Since the driver and the scheme are set by the class
you could give either the dsn or the database name and it will work.

B<The following attributes are inherited from> L<GAL::Storage>

=item * C<annotation>

This is a read only attribute that provides access to a weakened
version of the L<GAL::Annotation> object that created this storage

=item * C<dsn => 'dbi:SQLite:db_name'>

dsn => 'dbi:SQLite:db_name

This optional parameter defines the data source name of the database
to open.  By default Storage will use and SQLite database with a
random filename, but see the comment for the database attribute below.

=item * C<user => 'user_name'>

This optional parameter defines the user name for connecting to the
database.

=item * C<password => 'password'>

This optional parameter defines the password for connecting to the
database.

=back

=head1 CONSTRUCTOR

=cut

#-----------------------------------------------------------------------------

=head2 new

     Title   : new
     Usage   : GAL::Storage::SQLite->new();
     Function: Creates a Storage object;
     Returns : A L<GAL::Storage::SQLite> object
     Args    : See the attributes described above.

=cut

sub new {
	my ($class, @args) = @_;
	my $self = $class->SUPER::new(@args);
	return $self;
}

#-----------------------------------------------------------------------------

sub _initialize_args {
	my ($self, @args) = @_;

	######################################################################
	# This block of code handels class attributes.  Use the
	# @valid_attributes below to define the valid attributes for
	# this class.  You must have identically named get/set methods
	# for each attribute.  Leave the rest of this block alone!
	######################################################################
	my $args = $self->SUPER::_initialize_args(@args);
	# Set valid class attributes here
	my @valid_attributes = qw();
	$self->set_attributes($args, @valid_attributes);
	######################################################################
}

=head1 Attributes

=cut

#-----------------------------------------------------------------------------

=head2 mode

     Title   : mode
     Usage   : GAL::Storage::SQLite->mode('append');
     Function: Get/set the value of mode. This defines
               whether the database is overwritten or
               appended.
     Returns : The value of mode
     Args    : The valude append or the default overwrite.

=cut

sub mode {

  my ($self, $mode) = @_;

  $self->{mode} = $mode if $mode;
  $self->{mode} ||= 'overwrite';
  return $self->{mode};
}

#-----------------------------------------------------------------------------

=head2 scheme

 Title   : scheme
 Usage   : $a = $self->scheme();
 Function: Return the RDMS scheme.
 Returns : DBI
 Args    : N/A

=cut

sub scheme {'dbi'}

#-----------------------------------------------------------------------------

=head2 driver

 Title   : driver
 Usage   : $a = $self->driver();
 Function: Get the value of driver.
 Returns : SQLite
 Args    : N/A

=cut

sub driver {'SQLite'}

#-----------------------------------------------------------------------------

=head2 dbh

 Title   : dbh
 Usage   : $a = $self->dbh();
 Function: Get/Set the database handle
 Returns : The a DBI::SQLite object
 Args    : A DBI::SQLite object

=cut

sub dbh {
  my $self = shift;
  $self->{dbh} ||= $self->_open_or_create_database;
  return $self->{dbh};
}

#-----------------------------------------------------------------------------

=head2 database

 Title   : database
 Usage   : $a = $self->database();
 Function: Get/Set the database name.
 Returns : A database name.
 Args    : A database name.

=cut

sub database {
  my ($self, $database) = @_;

  if (! $database && ! $self->{database}) {
    $database = $self->random_string . '.sqlite';
  }
  $self->{database} = $database if $database;
  return $self->{database};
}

#-----------------------------------------------------------------------------

# Title   : _load_schema
# Usage   : $a = $self->_load_schema();
# Function: Load the database schema
# Returns : N/A
# Args    : N/A

sub _load_schema {
  my ($self, $dbh) = @_;

  $dbh->do("DROP TABLE IF EXISTS feature");
  $dbh->do("DROP TABLE IF EXISTS attribute");
  $dbh->do("DROP TABLE IF EXISTS relationship");
  $dbh->do("CREATE TABLE feature ("    .
	   "feature_idx INTEGER PRIMARY KEY AUTOINCREMENT, " .
	   "feature_id 	TEXT, "    .
	   "seqid      	TEXT, "    .
	   "source     	TEXT, "    .
	   "type       	TEXT, "    .
	   "start      	INTEGER, " .
	   "end        	INTEGER, " .
	   "score      	TEXT, "    .
	   "strand     	TEXT, "    .
	   "phase      	TEXT,"     .
	   "bin        	TEXT)"
	  );
  $dbh->do("CREATE TABLE attribute ("  .
	   "feature_idx  TEXT, " .
	   "att_key      TEXT, " .
	   "att_value    TEXT)"
	  );
  $dbh->do("CREATE TABLE relationship ("  .
	   "parent TEXT, " .
	   "child  TEXT, " .
	   "UNIQUE(parent, child) " .
	   "ON CONFLICT REPLACE)"
	  );
}

#-----------------------------------------------------------------------------

=head2 drop_database

  Title   : drop_database
  Usage   : $self->drop_database();
  Function: Drop the database;
  Returns : N/A
  Args    : N/A

=cut

sub drop_database {

  my $self = shift;

  my $database = $self->database;
  if (-e $database) {
    $self->warn('dropping_database', $database);
    `rm $database`;
  }
}

#-----------------------------------------------------------------------------

# Title   : _open_or_create_database
# Usage   : $self->_open_or_create_database();
# Function: Create the database if it doesnt exists.
# Returns : A DBD::SQLite object
# Args    : Nothing

sub _open_or_create_database {
  my $self = shift;

  my $dbh;
  my $dsn = $self->dsn;
  my $database = $self->database;

  if (! -e $database) {
    $dbh = DBI->connect($self->dsn);
    # This one is supposed to speed up write significantly, but doesn't
    # $dbh->do('PRAGMA default_synchronous = OFF');
    # $dbh->do('PRAGMA synchronous = 0');
    $self->_load_schema($dbh);
    # http://search.cpan.org/~adamk/DBD-SQLite-1.29/lib/DBD/SQLite.pm#Transactions
    # $dbh->{AutoCommit} = 0;
  }
  else {
    $self->warn('using_existing_database',
		("A database by the name $database already " .
		 "existed, so I'll use it as is."),
	       );
    $dbh = DBI->connect($self->dsn);
    # $dbh = DBI->connect("dbi:SQLite:dbname=:memory");
    # $dbh->sqlite_backup_from_file($self->database);
  }
  return $dbh
}

#-----------------------------------------------------------------------------

=head2 index_database

 Title   : index_database
 Usage   : $self->index_database();
 Function: Create indeces on the database.
 Returns : Nothing
 Args    : None

=cut

sub index_database {

  my $self = shift;
  my $dbh  = $self->dbh;

  $self->info('indexing_database', $self->database);
  # Create feature indeces
  $self->info('indexing_feature_id', $self->database);
  $dbh->do("CREATE INDEX feat_id_index ON feature (feature_id)");
  $self->info('indexing_locus', $self->database);
  $dbh->do("CREATE INDEX feat_locus_index ON feature (bin, seqid, start, end)");
  $self->info('indexing_feature_type', $self->database);
  $dbh->do("CREATE INDEX feat_type_index ON feature (type)");

  # Create attribute indeces
  $self->info('indexing_feature_attributes', $self->database);
  $dbh->do("CREATE INDEX att_feature_idx_index ON attribute (feature_idx, att_key, att_value)");

  # Create relationship indeces
  $self->info('indexing_relationships', $self->database);
  $dbh->do("CREATE INDEX rel_parent_child_index ON relationship (parent, child)");
  $dbh->do("CREATE INDEX rel_child_parent_index ON relationship (child, parent)");

  # Analyze
  $self->info('analyzing_database', $self->database);
  $dbh->do("ANALYZE");

  $self->info('finished_indexing_database', $self->database);
  return 1;
}

#-----------------------------------------------------------------------------

=head2 load_files

 Title   : load_files
 Usage   : $self->load_files();
 Function: Load a file(s) into the database
 Returns : Nothing
 Args    : An scalar string or array reference containing the name(s) of
	   files to load.

=cut

# TODO: Allow GAL::Storage::subclass::load_files to set the parser.

sub load_files {

  my ($self, $files) = @_;
  $files = ref $files eq 'ARRAY' ? $files : [$files];

  my $parser = $self->annotation->parser;

  $self->drop_database if $self->mode eq 'overwrite';

  for my $file (@{$files}) {
    $parser->file($file);
    $self->info('loading_database', $file);
    my $counter = 0;
    while (my $feature = $parser->next_feature_hash) {
      $self->add_features_to_buffer($feature);
      if (++$counter % 10000 == 0) {
	$self->info('loading_database', "Loaded $counter features");
      }
    }
    $self->flush_buffer;
    $self->info('finished_loading_database', $file);
  }
  $self->index_database;
}

#-----------------------------------------------------------------------------

=head2 add_features

 Title   : add_features
 Usage   : $self->add_features();
 Function: Add features to the database.
 Returns : Nothing
 Args    : An array reference of feature hashes.

=cut

sub add_features {
  my ($self, $features) = @_;

  my ($feat_rows, $att_rows, $rel_rows) = $self->prepare_features($features);
  my $dbh = $self->dbh;

  # "feature_idx INT, " .
  # "feature_id  VARCHAR(255), " .
  # "seqid       VARCHAR(255), " .
  # "source      VARCHAR(255), " .
  # "type        VARCHAR(255), " .
  # "start       INT, "          .
  # "end         INT, "          .
  # "score       VARCHAR(255), " .
  # "strand      VARCHAR(1), "   .
  # "phase       VARCHAR(1),"    .
  # "bin         VARCHAR(15))"

  my $feat_stmt = "INSERT INTO feature VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
  my $feat_sth  = $dbh->prepare($feat_stmt);

  my %feat_idx_map;

  # http://search.cpan.org/~adamk/DBD-SQLite-1.29/lib/DBD/SQLite.pm#Transactions
  $dbh->begin_work;
  for my $feat_row (@{$feat_rows}) {
    my $old_feat_idx = $feat_row->[0];
    $feat_row->[0] = undef;
    my $rv = $feat_sth->execute(@{$feat_row});
    if ($rv) {
      my ($auto_inc) = $dbh->selectrow_array('SELECT last_insert_rowid()');
      $feat_idx_map{$old_feat_idx} = $auto_inc;
    }
    else {
      my $warn_message = ('The following data failed to insert into the ' .
			  'feature table : ');
      my $warn_code = 'bad_feature_table_insert :';
      my $data = join ', ', @{$feat_row};
      $warn_message .= $data;
      $self->warn($warn_code,
		  $warn_message);
    }
  }

  # Removed # "attribute_id INT NOT NULL AUTO_INCREMENT, " .
  # "feature_idx VARCHAR(255), " .
  # "att_key     VARCHAR(255), "    .
  # "att_value   TEXT, "  .

  #my $att_stmt = "INSERT INTO attribute VALUES (?, ?, ?, ?)";
  my $att_stmt = "INSERT INTO attribute VALUES (?, ?, ?)";
  my $att_sth = $dbh->prepare($att_stmt);

  for my $att_row (@{$att_rows}) {
    next unless exists $feat_idx_map{$att_row->[0]};
    $att_row->[0] = $feat_idx_map{$att_row->[0]};
    my $rv = $att_sth->execute(@{$att_row});
    unless ($rv) {
      my $warn_message = ('The following data failed to insert into the ' .
			  'attribute table : ');
      my $warn_code = 'bad_attribute_table_insert :';
      my $data = join ', ', @{$att_row};
      $warn_message .= $data;
      $warn_code    .= $data;
      $self->warn($warn_code,
		  $warn_message);
    }
  }

  # "parent   VARCHAR(255), " .
  # "child    VARCHAR(255), "    .
  # REMOVED # "relationship VARCHAR(255)) "

  my $rel_stmt = "INSERT INTO relationship VALUES (?, ?)";
  my $rel_sth = $dbh->prepare($rel_stmt);

  for my $rel_row (@{$rel_rows}) {
    my $rv = $rel_sth->execute(@{$rel_row});
    unless ($rv) {
      my $warn_message = ('The following data failed to insert into the ' .
			  'relationship table : ');
      my $warn_code = 'bad_relationship_table_insert :';
      my $data = join ', ', @{$rel_row};
      $warn_message .= $data;
      $warn_code    .= $data;
      $self->warn($warn_code,
		  $warn_message);
    }
  }
  $dbh->commit;
}

#-----------------------------------------------------------------------------
#
#=head2 get_children
#
# Title   : get_children
# Usage   : $self->get_children();
# Function: Get/Set value of get_children.
# Returns : Value of get_children.
# Args    : Value to set get_children to.
#
#=cut
#
#sub get_children {
#	my $self = shift;
#	$self->not_implemented('get_children');
#}
#
##-----------------------------------------------------------------------------
#
#=head2 get_children_recursively
#
# Title   : get_children_recursively
# Usage   : $self->get_children_recursively();
# Function: Get/Set value of get_children_recursively.
# Returns : Value of get_children_recursively.
# Args    : Value to set get_children_recursively to.
#
#=cut
#
#sub get_children_recursively {
#  my $self = shift;
#  $self->not_implemented('get_children_recursively');
#}
#
##-----------------------------------------------------------------------------
#
#=head2 get_parents
#
# Title   : get_parents
# Usage   : $self->get_parents();
# Function: Get/Set value of get_parents.
# Returns : Value of get_parents.
# Args    : Value to set get_parents to.
#
#=cut
#
#sub get_parents {
#  my $self = shift;
#  $self->not_implemented('get_parents');
#}
#
##-----------------------------------------------------------------------------
#
#=head2 get_parents_recursively
#
# Title   : get_parents_recursively
# Usage   : $self->get_parents_recursively();
# Function: Get/Set value of get_parents_recursively.
# Returns : Value of get_parents_recursively.
# Args    : Value to set get_parents_recursively to.
#
#=cut
#
#sub get_parents_recursively {
#  my $self = shift;
#  $self->not_implemented('get_parents_recursively');
#}
#
##-----------------------------------------------------------------------------
#
#=head2 get_all_features
#
# Title   : get_all_features
# Usage   : $self->get_all_features();
# Function: Get/Set value of get_all_features.
# Returns : Value of get_all_features.
# Args    : Value to set get_all_features to.
#
#=cut
#
#sub get_all_features {
#  my $self = shift;
#  $self->not_implemented('get_all_features');
#}
#
##-----------------------------------------------------------------------------
#
#=head2 get_features_by_type
#
# Title   : get_features_by_type
# Usage   : $self->get_features_by_type();
# Function: Get/Set value of get_features_by_type.
# Returns : Value of get_features_by_type.
# Args    : Value to set get_features_by_type to.
#
#=cut
#
#sub get_features_by_type {
#  my $self = shift;
#  $self->not_implemented('get_features_by_type');
#}
#
##-----------------------------------------------------------------------------
#
#=head2 get_recursive_features_by_type
#
# Title   : get_recursive_features_by_type
# Usage   : $self->get_recursive_features_by_type();
# Function: Get/Set value of get_recursive_features_by_type.
# Returns : Value of get_recursive_features_by_type.
# Args    : Value to set get_recursive_features_by_type to.
#
#=cut
#
#sub get_recursive_features_by_type {
#  my $self = shift;
#  $self->not_implemented('get_recursive_features_by_type');
#}
#
##-----------------------------------------------------------------------------
#
#=head2 get_feature_by_id
#
# Title   : get_feature_by_id
# Usage   : $self->get_feature_by_id();
# Function: Get/Set value of get_feature_by_id.
# Returns : Value of get_feature_by_id.
# Args    : Value to set get_feature_by_id to.
#
#=cut
#
#sub get_feature_by_id {
#  my $self = shift;
#  $self->not_implemented('get_feature_by_id');
#}
#
##-----------------------------------------------------------------------------
#
#=head2 filter_features
#
# Title   : filter_features
# Usage   : $self->filter_features();
# Function: Get/Set value of filter_features.
# Returns : Value of filter_features.
# Args    : Value to set filter_features to.
#
#=cut
#
#sub filter_features {
#  my $self = shift;
#  $self->not_implemented('filter_features');
#}
#
##-----------------------------------------------------------------------------
#
#=head2 foo
#
# Title   : foo
# Usage   : $a = $self->foo();
# Function: Get/Set the value of foo.
# Returns : The value of foo.
# Args    : A value to set foo to.
#
#=cut
#
#sub foo {
#	my ($self, $value) = @_;
#	$self->{foo} = $value if defined $value;
#	return $self->{foo};
#}
#
##-----------------------------------------------------------------------------

=head1 DIAGNOSTICS

=over

=item C<using_existing_database>

A database by the same name specified already existed and you haven't
asked for it to be overwritten, so it will be used and possible
appended to.  If you want to overwrite this database you should use
the attribute C<mode => overwrite> when you create the storage object.

=item C<bad_feature_table_insert>

An error occured while trying to insert data into the feature table.
The offending data is given as a comma separated list.  Make sure that
all of the data is compatible with the database schema.  This may be a
problem in the parser you are using, or more likely the incoming data
is not in the correct format.

=item C<bad_attribute_table_insert>

Same problem as C<bad_feature_table_insert> above, but for the
attribute table.

=item C<bad_relationship_table_insert>

Same problem as C<bad_feature_table_insert> above, but for the
attribute table.

=back

=head1 CONFIGURATION AND ENVIRONMENT

<GAL::Storage::SQLite> requires no configuration files or environment
variables.

=head1 DEPENDENCIES

L<GAL::Storage>
L<DBI>
L<DBD::SQLite>

=head1 INCOMPATIBILITIES

None reported.

=head1 BUGS AND LIMITATIONS

No bugs have been reported.

Please report any bugs or feature requests to:
barry.moore@genetics.utah.edu

=head1 AUTHOR

Barry Moore <barry.moore@genetics.utah.edu>

=head1 LICENCE AND COPYRIGHT

Copyright (c) 2010-2014, Barry Moore <barry.moore@genetics.utah.edu>.  All
rights reserved.

    This module is free software; you can redistribute it and/or
    modify it under the same terms as Perl itself (See LICENSE).

=head1 DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT
WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE
TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.

=cut

1;