text:
/*
 * File:   gui.cpp
 * Author: Matthew Schauer
 *
 * Created on July 27, 2013, 5:46 PM
 */

#include <wx/wx.h>
#include <wx/notebook.h>
#include <wx/treectrl.h>
#include <wx/stattext.h>
#include <wx/dataview.h>
#include <wx/srchctrl.h>
#include <wx/html/htmlwin.h>
#include "wx/html/m_templ.h"
#include "Deck.h"
#include "Set.h"
#include "Card.h"
#include "Bank.h"
#include "coldesc.h"
#include "backend.h"
#include <algorithm>
#include <exception>
#include <stdexcept>
#include <unordered_map>
#include <queue>

#define PROGRAM "Tango"
#define VERSION "0.4"
#define AUTHOR "Matthew Schauer"
#define DATE "2015"
#define LICENSE "Apache License version 2.0"

/* TODO
 * Next:
 *	Make the disp_ field in Deck persistent and allow the user to edit it
 * Closing a window in front of Tango may cause it to quit as well?
 * Completing a card in repeats causes set size to decrease by 2
 * Preferences screen
 *	Auto-advance decks every 24 hours
 *	Display settings for root deck, inherited by implicit decks
 *
 * Long-term:
 * Multiple readings, writings, meanings
 *	It is possible to make multiple entries for a given field on a given card in the database
 *	Could randomly choose one to display, and display all possibilities separated by "or" in the answer
 *	Makes editing more difficult
 *	What if a given reading only goes with one writing, etc?
 * Give each word a "momentum" that increases/decreases as the user answers more correct/incorrect
 * Flesh out the overview screen with graphs and so forth
 *	Add to card database fields for number of practices and number of correct/incorrect/resets/etc., and use this to calculate momentum or "score"
 * Add a preferences window allowing users to edit
 *	The maximum interval before a card is automatically marked done
 *	Default settings for root deck
 * Keep track of the total number of steps taken and the number of steps since a given card was suspended
 * Filter card table by deck
 * Fill in the blanks in sample sentences
 * Single out and present problem children
 */

std::string wx2utf8(const wxString &str)
{
	return std::string{str.utf8_str().data()};
}

/******************************************************************************
 * GUI structure
 ******************************************************************************/

enum { id_menu_about, id_menu_quit, id_menu_refresh, id_notebook, id_decks_tree, id_browse_cards, id_card_add, id_card_del, id_card_find, id_browse_decks, id_deck_add, id_deck_del, id_set_type, id_browse_bank, id_offset_forward, id_offset_back };

namespace std
{
	template <> struct hash<wxDataViewItem> { size_t operator ()(const wxDataViewItem &x) const { return (size_t) x.GetID(); } };
}

class MainFrame;

class App: public wxApp
{
	virtual bool OnInit() override;
	virtual int OnExit() override;
	virtual bool OnExceptionInMainLoop() override;
	MainFrame *frame;
};

class MainFrame : public wxFrame
{
public:
	MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
	void populate_decktree(Deck *d = &Deck::root);
	void populate_table_cols(wxDataViewListCtrl *table, const std::vector<coldesc> &columns);
	wxVector<wxVariant> cols2wxvec(std::vector<coldesc> colspec, std::vector<std::string> cols);
	void table_updaterow(wxDataViewListCtrl *table, int row, const wxVector<wxVariant> &data);
	void pagechange();
	void showcard();
	void addcard();
	void delcard(int row);
	void stattext(const std::string &text = "");
	void setbankitem(const std::string word, bool enabled);
	void populate_cardtable(std::string filter = "");
	void populate_decktable();
	void populate_bankview();
	void refresh_views(int mode = 0xff);
	void debug_tablecheck();
	void about(wxCommandEvent &event);
	void quit(wxCommandEvent &event);
	void refresh(wxCommandEvent &event);
	void switch_deck(wxTreeEvent &event);
	void activate_deck(wxTreeEvent &event);
	void page_changed(wxNotebookEvent &event);
	void ensure_exists(const std::string &deck);
	void offset_advanced(wxCommandEvent &event);
	void offset_reversed(wxCommandEvent &event);
	void card_added(wxCommandEvent &event);
	void card_deleted(wxCommandEvent &event);
	void card_searched(wxCommandEvent &event);
	void card_edited(wxDataViewEvent &event);
	void deck_added(wxCommandEvent &event);
	void deck_deleted(wxCommandEvent &event);
	void deck_edited(wxDataViewEvent &event);
	void bankitem_set(wxHtmlLinkEvent &event);
	//void change_settype(wxCommandEvent &event);
	void keydown(wxKeyEvent &event);
	void key_view(wxKeyEvent &event);
	void close(wxCloseEvent &event);
	void err(const std::string msg);
	void except(const std::exception &e);

	Set *curset;
	//Set::SetType settype;
	Set::DispType disp;
	wxFont font_header;
	std::string html_pref, html_suff;
private:
	wxNotebook *notebook;
	wxPanel *panel_tree;
	wxPanel *panel_deck;
	wxPanel *panel_study;
	wxPanel *panel_cards;
	wxPanel *panel_decks;
	wxPanel *panel_bank;

	wxTreeCtrl *tree_decks;
	wxButton *offset_forward;
	wxButton *offset_back;

	wxStaticText *deck_name;

	wxHtmlWindow *study_view;

	wxDataViewListCtrl *browse_cards;
	std::vector<coldesc> card_columns;
	wxDataViewSpinRenderer *dropdownRenderer;
	wxButton *card_add;
	wxButton *card_del;
	wxSearchCtrl *card_find;

	wxDataViewListCtrl *browse_decks;
	std::vector<coldesc> deck_columns;
	wxButton *deck_add;
	wxButton *deck_del;

	std::unordered_map<std::string, wxTreeItemId> deckids;
	std::unordered_map<wxDataViewItem, Card *> card_rows;
	std::unordered_map<wxDataViewItem, Deck *> deck_rows;
	std::unordered_map<wxDataViewItem, std::string> bank_rows;

	wxHtmlWindow *bank_view;

	std::pair<Deck *, Set::SetType> tree2deck(wxTreeItemId id);
	Card *row2card(int row);
	int card2row(Card *card);
	int table_addcard(Card &card);
	void table_delcard(int row);
	Deck *row2deck(int row);
	int deck2row(Deck *deck);
	int table_adddeck(Deck &deck);
	void table_deldeck(int row);

	DECLARE_EVENT_TABLE()
};

TAG_HANDLER_BEGIN(BANKBTN, "BANKBTN")
TAG_HANDLER_PROC(tag)
{
	MainFrame *frame = (MainFrame *) m_WParser->GetWindowInterface()->GetHTMLWindow()->GetParent()->GetParent()->GetParent(); // Is there seriously no easier way to get the frame in this context?
	wxString word = tag.GetParam(_("name"));
	std::string wordstr = wx2utf8(word);
	bool enabled = frame->curset->deck().bank().enabled(wordstr);
	wxButton *button = new wxButton{m_WParser->GetWindowInterface()->GetHTMLWindow(), wxID_ANY, word, wxDefaultPosition, wxSize{46, 46}, wxBORDER_NONE};
	button->SetFont(wxFont{24, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL});
	button->SetForegroundColour(enabled ? wxColour{_("black")} : wxColour{_("gray")});
	button->Bind(wxEVT_BUTTON, [=](wxCommandEvent &event)
	{
		bool en = ! frame->curset->deck().bank().enabled(wordstr);
		button->SetForegroundColour(en ? wxColour{"black"} : wxColour{"gray"});
		frame->setbankitem(wordstr, en);
	});
	button->Show(true);
	m_WParser->GetContainer()->InsertCell(new wxHtmlWidgetCell(button, 0));

	return false;
}
TAG_HANDLER_END(BANKBTN)

TAGS_MODULE_BEGIN(bankbtn)
TAGS_MODULE_ADD(BANKBTN)
TAGS_MODULE_END(bankbtn)

BEGIN_EVENT_TABLE(MainFrame, wxFrame)
	EVT_MENU(id_menu_about, MainFrame::about)
	EVT_MENU(id_menu_quit, MainFrame::quit)
	EVT_MENU(id_menu_refresh, MainFrame::refresh)
	EVT_BUTTON(id_offset_forward, MainFrame::offset_advanced)
	EVT_BUTTON(id_offset_back, MainFrame::offset_reversed)
	EVT_BUTTON(id_card_add, MainFrame::card_added)
	EVT_BUTTON(id_card_del, MainFrame::card_deleted)
	EVT_BUTTON(id_card_find, MainFrame::card_searched)
	EVT_BUTTON(id_deck_add, MainFrame::deck_added)
	EVT_BUTTON(id_deck_del, MainFrame::deck_deleted)
	//EVT_CHOICE(id_set_type, MainFrame::change_settype)
	EVT_TREE_ITEM_ACTIVATED(id_decks_tree, MainFrame::activate_deck)
	EVT_TREE_SEL_CHANGED(id_decks_tree, MainFrame::switch_deck)
	EVT_NOTEBOOK_PAGE_CHANGED(id_notebook, MainFrame::page_changed)
	EVT_DATAVIEW_ITEM_VALUE_CHANGED(id_browse_cards, MainFrame::card_edited)
	EVT_DATAVIEW_ITEM_VALUE_CHANGED(id_browse_decks, MainFrame::deck_edited)
	EVT_TEXT(id_card_find, MainFrame::card_searched)
	EVT_CLOSE(MainFrame::close)
END_EVENT_TABLE()

IMPLEMENT_APP(App)

bool App::OnInit() try
{
	std::vector<std::string> args;
	for (int i = 0; i < argc; i++) args.push_back(wx2utf8(wxString{argv[i]}));
	backend::init(args);
	backend::early_populate(); // Load fieldnames
	frame = new MainFrame{_("Tango"), wxPoint(200, 200), wxSize(600, 400)};
	frame->Center();
	frame->Show(true);
	SetTopWindow(frame);
	frame->stattext("Loading decks...");
	backend::populate();
	frame->refresh_views();
	frame->stattext("No deck selected");
	return true;
}
catch (std::exception &e)
{
	std::cerr << "Error: " << e.what() << "\n";
	frame->except(e);
	return true;
}

int App::OnExit()
{
	return 0;
}

bool App::OnExceptionInMainLoop()
{
	frame->except(std::runtime_error{"Uncaught exception in main loop"});
	return false;
}

void MainFrame::except(const std::exception &e)
{
	wxMessageDialog message{this, _(std::string{"The program experienced a fatal exception and will now exit:\n\n"} + e.what()), _("Exception"), wxOK | wxICON_ERROR};
	message.ShowModal();
	wxExit();
}

void MainFrame::err(const std::string msg)
{
	wxMessageDialog{this, _(std::string{"Error:  "} + msg), _("Error"), wxOK | wxICON_ERROR}.ShowModal();
}

MainFrame::MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size) try : wxFrame{NULL, -1, title, pos, size}
{
	curset = nullptr;
	//settype = Set::SetType::NORMAL; // TODO User-set
	disp = Set::DispType::FRONT;
	font_header = wxFont{-1, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD};
	html_pref = "";
	html_suff = "";

	wxMenu *menu_file = new wxMenu{};
	menu_file->Append(id_menu_about, _("&About..."));
	menu_file->AppendSeparator();
	menu_file->Append(id_menu_refresh, _("&Refresh"));
	menu_file->Append(id_menu_quit, _("Quit"));

	wxMenuBar *menubar = new wxMenuBar;
	menubar->Append(menu_file, _("&File"));
	SetMenuBar(menubar);

	CreateStatusBar();

	notebook = new wxNotebook{this, id_notebook};

	// Deck tree panel
	panel_tree = new wxPanel{notebook, -1, wxPoint(-1, -1), wxSize(-1, -1)};
	wxSizer *sizer_tree = new wxBoxSizer{wxVERTICAL};
	tree_decks = new wxTreeCtrl{panel_tree, id_decks_tree, wxDefaultPosition, wxSize(-1, -1), wxTR_HIDE_ROOT | wxTR_HAS_BUTTONS};
	sizer_tree->Add(tree_decks, 1, wxALIGN_CENTER | wxEXPAND | wxALL, 10);
	offset_forward = new wxButton{panel_tree, id_offset_forward, ">"};
	offset_back = new wxButton{panel_tree, id_offset_back, "<"};
	wxSizer *sizer_offset = new wxBoxSizer(wxHORIZONTAL);
	sizer_offset->Add(offset_back, 1, wxEXPAND | wxRIGHT, 5);
	sizer_offset->Add(offset_forward, 1, wxEXPAND | wxLEFT, 5);
	sizer_tree->Add(sizer_offset, 0, wxLEFT | wxBOTTOM | wxRIGHT | wxEXPAND, 10);
	panel_tree->SetSizerAndFit(sizer_tree);
	notebook->AddPage(panel_tree, _("Tree"), true);

	// Deck overview panel
	panel_deck = new wxPanel{notebook, -1, wxPoint(-1, -1), wxSize(-1, -1)};
	wxSizer *sizer_deck = new wxBoxSizer{wxVERTICAL};
	deck_name = new wxStaticText{panel_deck, -1, _(""), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER | wxST_NO_AUTORESIZE};
	deck_name->SetFont(font_header);
	sizer_deck->Add(deck_name, 0, wxALIGN_CENTER | wxEXPAND | wxALL, 10);
	panel_deck->SetSizerAndFit(sizer_deck);
	notebook->AddPage(panel_deck, _("Overview"));

	// Study panel
	panel_study = new wxPanel{notebook, -1, wxPoint(-1, -1), wxSize(-1, -1)};
	wxSizer *sizer_study = new wxBoxSizer{wxVERTICAL};
	study_view = new wxHtmlWindow{panel_study};
	study_view->Bind(wxEVT_KEY_UP, &MainFrame::keydown, this);
	sizer_study->Add(study_view, 1, wxALIGN_CENTER | wxEXPAND | wxALL, 10);
	panel_study->SetSizerAndFit(sizer_study);
	notebook->AddPage(panel_study, _("Study"));

	// Cards panel
	panel_cards = new wxPanel{notebook, -1, wxPoint(-1, -1), wxSize(-1, -1)};
	wxSizer *sizer_cards = new wxBoxSizer{wxVERTICAL};
	browse_cards = new wxDataViewListCtrl{panel_cards, id_browse_cards};
	card_columns.push_back(coldesc{coldesc::Type::STRING, "Deck", 160});
	for (std::string s : Card::fieldnames()) card_columns.push_back(coldesc{coldesc::Type::FIELD, s, 160});
	card_columns.push_back(coldesc{coldesc::Type::CHOICE, "Status:Active,Suspended,Done,Leech", 80});
	card_columns.push_back(coldesc{coldesc::Type::INT, "Offset", 80});
	card_columns.push_back(coldesc{coldesc::Type::INT, "Interval:0," + util::t2s<int>(Card::maxdelay() * 2), 80});
	card_columns.push_back(coldesc{coldesc::Type::STATIC_INT, "Norm", 80});
	card_columns.push_back(coldesc{coldesc::Type::STATIC_INT, "Incr", 80});
	card_columns.push_back(coldesc{coldesc::Type::STATIC_INT, "Decr", 80});
	card_columns.push_back(coldesc{coldesc::Type::STATIC_INT, "Reset", 80});
	populate_table_cols(browse_cards, card_columns);
	sizer_cards->Add(browse_cards, 1, wxALIGN_CENTER | wxEXPAND | wxALL, 10);
	wxSizer *sizer_card_buttons = new wxBoxSizer{wxHORIZONTAL};
	card_add = new wxButton{panel_cards, id_card_add, "Add"};
	card_del = new wxButton{panel_cards, id_card_del, "Delete"};
	card_find = new wxSearchCtrl{panel_cards, id_card_find, wxEmptyString, wxDefaultPosition, wxSize{140, 30}, wxTE_PROCESS_ENTER};
	sizer_card_buttons->Add(card_find, 0, wxALIGN_LEFT);
	sizer_card_buttons->Add(0, 0, 1);
	sizer_card_buttons->Add(card_del, 0, wxALIGN_LEFT | wxLEFT, 10);
	sizer_card_buttons->Add(card_add, 0, wxALIGN_RIGHT | wxLEFT, 10);
	sizer_cards->Add(sizer_card_buttons, 0, wxLEFT | wxBOTTOM | wxRIGHT | wxALIGN_RIGHT | wxEXPAND, 10);
	panel_cards->SetSizerAndFit(sizer_cards);
	notebook->AddPage(panel_cards, _("Cards"));

	// Decks panel
	panel_decks = new wxPanel{notebook, -1, wxPoint(-1, -1), wxSize(-1, -1)};
	wxSizer *sizer_decks = new wxBoxSizer{wxVERTICAL};
	browse_decks = new wxDataViewListCtrl{panel_decks, id_browse_decks};
	deck_columns.push_back(coldesc{coldesc::Type::STRING, "Name", 160});
	deck_columns.push_back(coldesc{coldesc::Type::STATIC_INT, "Cards", 60});
	deck_columns.push_back(coldesc{coldesc::Type::STATIC_INT, "Due", 60});
	deck_columns.push_back(coldesc{coldesc::Type::BOOL, "Explicit", 40});
	//deck_columns.push_back(coldesc{coldesc::Type::CHOICE, "Front:Kanji,Hiragana,Furigana,Meaning,All"});
	//deck_columns.push_back(coldesc{coldesc::Type::CHOICE, "Back:Kanji,Hiragana,Furigana,Meaning,All"});
	populate_table_cols(browse_decks, deck_columns);
	browse_decks->Bind(wxEVT_KEY_DOWN, &MainFrame::key_view, this);
	sizer_decks->Add(browse_decks, 1, wxALIGN_CENTER | wxEXPAND | wxALL, 10);
	wxSizer *sizer_deck_buttons = new wxBoxSizer{wxHORIZONTAL};
	deck_add = new wxButton{panel_decks, id_deck_add, "Add"};
	deck_del = new wxButton{panel_decks, id_deck_del, "Delete"};
	sizer_deck_buttons->Add(deck_del, 0, wxALIGN_RIGHT | wxLEFT, 10);
	sizer_deck_buttons->Add(deck_add, 0, wxALIGN_RIGHT | wxLEFT, 10);
	sizer_decks->Add(sizer_deck_buttons, 0, wxALIGN_RIGHT | wxLEFT | wxBOTTOM | wxRIGHT, 10);
	panel_decks->SetSizerAndFit(sizer_decks);
	notebook->AddPage(panel_decks, _("Decks"));

	// Bank panel
	panel_bank = new wxPanel{notebook, -1, wxPoint(-1, -1), wxSize(-1, -1)};
	wxSizer *sizer_bank = new wxBoxSizer{wxVERTICAL};
	bank_view = new wxHtmlWindow{panel_bank};
	sizer_bank->Add(bank_view, 1, wxEXPAND | wxALL, 10);
	panel_bank->SetSizerAndFit(sizer_bank);
	notebook->AddPage(panel_bank, _("Bank"));
}
catch(std::exception &e) { except(e); }

void MainFrame::populate_table_cols(wxDataViewListCtrl *table, const std::vector<coldesc> &columns)
{
	table->DeleteAllItems();
	table->ClearColumns();
	unsigned int i = 0;
	for (coldesc col : columns)
	{
		if (col.type == coldesc::Type::STRING || col.type == coldesc::Type::FIELD)
		{
			table->AppendTextColumn(_(col.title), wxDATAVIEW_CELL_EDITABLE, col.width, wxALIGN_LEFT, wxDATAVIEW_COL_RESIZABLE | wxDATAVIEW_COL_SORTABLE);
		}
		else if (col.type == coldesc::Type::INT)
		{
			wxDataViewRenderer *int_renderer = new wxDataViewSpinRenderer{col.min, col.max};
			wxDataViewColumn *int_column = new wxDataViewColumn{_(col.title), int_renderer, i, col.width, wxALIGN_LEFT, wxDATAVIEW_COL_RESIZABLE | wxDATAVIEW_COL_SORTABLE};
			table->AppendColumn(int_column);
		}
		else if (col.type == coldesc::Type::STATIC_INT)
		{
			table->AppendTextColumn(_(col.title), wxDATAVIEW_CELL_INERT, col.width, wxALIGN_LEFT, wxDATAVIEW_COL_RESIZABLE | wxDATAVIEW_COL_SORTABLE);
		}
		/*else if (col.type == coldesc::Type::DATE)
		{
			wxDataViewRenderer *date_renderer = new wxDataViewDateRenderer{};
			wxDataViewColumn *date_column = new wxDataViewColumn{_(col.title), date_renderer, i, col.width, wxALIGN_LEFT, wxDATAVIEW_COL_RESIZABLE | wxDATAVIEW_COL_SORTABLE};
			table->AppendColumn(date_column);
		}*/
		else if (col.type == coldesc::Type::CHOICE)
		{
			wxArrayString choices{};
			for (std::string choice : col.choices) choices.Add(_(choice));
			wxDataViewRenderer *choice_renderer = new wxDataViewChoiceRenderer{choices};
			wxDataViewColumn *choice_column = new wxDataViewColumn{_(col.title), choice_renderer, i, col.width, wxALIGN_LEFT, wxDATAVIEW_COL_RESIZABLE | wxDATAVIEW_COL_SORTABLE};
			table->AppendColumn(choice_column);
		}
		else if (col.type == coldesc::Type::BOOL)
		{
			table->AppendToggleColumn(_(col.title), wxDATAVIEW_CELL_ACTIVATABLE, col.width, wxALIGN_CENTER);
		}
		i++;
	}
}

/******************************************************************************
 * Converters
 ******************************************************************************/

wxVector<wxVariant> MainFrame::cols2wxvec(std::vector<coldesc> colspec, std::vector<std::string> cols)
{
	wxVector<wxVariant> row{};
	for (unsigned int i = 0; i < cols.size(); i++)
	{
		wxVariant variant{};
		coldesc::Type type = colspec[i].type;
		if (type == coldesc::Type::STRING || type == coldesc::Type::FIELD || type == coldesc::Type::STATIC_INT) variant = wxVariant{wxString::FromUTF8(cols[i].c_str())};
		//else if (type == coldesc::Type::DATE) variant = wxVariant{wxDateTime{date{cols[i]}.mktime()}};
		else if (type == coldesc::Type::CHOICE) variant = wxVariant{wxString::FromUTF8(cols[i].c_str())};
		else if (type == coldesc::Type::INT) variant = wxVariant{util::s2t<int>(cols[i])};
		else if (type == coldesc::Type::BOOL) variant = wxVariant{cols[i] == "true" ? true : false};
		else throw std::runtime_error{"Unknown column description type"};
		row.push_back(variant);
	}
	return row;
}

std::pair<Deck *, Set::SetType> MainFrame::tree2deck(wxTreeItemId id)
{
	for (std::pair<std::string, wxTreeItemId> kvpair : deckids) if (kvpair.second == id)
	{
		Deck *d = &Deck::get(util::strto(kvpair.first, ":"));
		std::string ststr = util::strto(kvpair.first, ":");
		Set::SetType st = Set::str2st((ststr == "") ? "Normal" : ststr);
		return std::make_pair(d, st);
	}
	return std::make_pair(nullptr, Set::SetType::ALL);
}

Card *MainFrame::row2card(int row)
{
	wxDataViewItem item = browse_cards->RowToItem(row);
	if (! item.IsOk() || ! card_rows.count(item)) return nullptr;
	return card_rows[item];
}

int MainFrame::card2row(Card *card)
{
	for (std::pair<wxDataViewItem, Card *> pair : card_rows) if (pair.second == card) return browse_cards->ItemToRow(pair.first);
	return -1;
}

Deck *MainFrame::row2deck(int row)
{
	wxDataViewItem item = browse_decks->RowToItem(row);
	if (! item.IsOk() || ! deck_rows.count(item)) return nullptr;
	return deck_rows[item];
}

int MainFrame::deck2row(Deck *deck)
{
	for (std::pair<wxDataViewItem, Deck *> pair : deck_rows) if (pair.second == deck) return browse_decks->ItemToRow(pair.first);
	return -1;
}

void MainFrame::table_updaterow(wxDataViewListCtrl *table, int row, const wxVector<wxVariant> &data)
{
	for (unsigned int i = 0; i < data.size(); i++) table->SetValue(data[i], row, i);
}

void MainFrame::addcard()
{
	Deck *deck;
	if (curset == nullptr) deck = &Deck::get(Deck::freename());
	else deck = &curset->deck();
	try
	{
		Card &card = Card::add(*deck);
		table_addcard(card);
		refresh_views(0x6); // Update deck tree, deck table
		browse_cards->SelectRow(card2row(&card));
		browse_cards->EnsureVisible(browse_cards->RowToItem(card2row(&card)));
	}
	catch (std::runtime_error &e)
	{
		err(e.what());
		refresh_views(0x6);
	}
}

void MainFrame::delcard(int row)
{
	try
	{
		Card::del(*row2card(row));
		table_delcard(row);
		refresh_views(0x6); // Update deck tree, deck table
	}
	catch (std::runtime_error &e)
	{
		err(e.what());
		refresh_views(0x6);
	}
}

/******************************************************************************
 * GUI updaters
 ******************************************************************************/

void MainFrame::showcard()
{
	std::string body{};
	if (! curset) body = "(No deck selected)";
	else if (curset->size() == 0) body = "(No cards in current set)";
	//else body = curset->top().display(cardback ? curset->deck().type_back() : curset->type_front());
	else body = curset->disptop(disp) + html_suff;
	study_view->SetPage(wxString::FromUTF8((html_pref + body + html_suff).c_str()));
	stattext();
}

void MainFrame::pagechange()
{
	int page = notebook->GetSelection();
	switch (page)
	{
		case 0: // Decks
			populate_decktree();
			break;
		case 1: // Deck
			if (! curset) deck_name->SetLabel(_("(No deck selected)"));
			else deck_name->SetLabel(_(curset->canonical()));
			break;
		case 2: // Study
			disp = Set::DispType::FRONT;
			showcard();
			break;
		case 3: // Cards
			//populate_browsetable();
			break;
		case 4: // Decks
			break;
		case 5: // Bank
			refresh_views(0x8);
			break;
	}
	stattext();
}

void MainFrame::stattext(const std::string &text)
{
	if (text != "") SetStatusText(_(text));
	else if (! curset) SetStatusText(_("(No deck selected)"));
	else
	{
		int page = notebook->GetSelection();
		if (page == 0 || page == 1 || page == 3) SetStatusText(_(curset->canonical() + "  |  " + util::t2s<int>(curset->size())));
		else if (page == 2)
		{
			if (curset->size() > 0) SetStatusText(_(curset->canonical() + "  |  " + util::t2s<int>(curset->size()) + "  |  " + util::t2s<int>(curset->top().delay())));
			else SetStatusText(_(curset->canonical() + "  |  0"));
		}
	}
}

void MainFrame::debug_tablecheck()
{
	for (const std::pair<wxDataViewItem, Card *> &pair : card_rows)
	{
		wxVariant var{};
		browse_cards->GetValue(var, browse_cards->ItemToRow(pair.first), 1);
		std::string expr = wx2utf8(var.GetString());
		//std::cerr << expr << " - " << pair.second->field("Expression") << "\n";
		if (expr != pair.second->field("Expression"))
		{
			std::cerr << "Card mapping mismatch:  " << expr << " vs " << pair.second->field("Expression") << "\n";
			throw std::runtime_error{"Card table continuity error"};
		}
	}
	for (const std::pair<wxDataViewItem, Deck *> &pair : deck_rows)
	{
		wxVariant var{};
		browse_decks->GetValue(var, browse_decks->ItemToRow(pair.first), 0);
		std::string name = wx2utf8(var.GetString());
		//std::cerr << name << " - " << pair.second->canonical() << "\n";
		if (name != pair.second->canonical())
		{
			std::cerr << "Deck mapping mismatch:  " << name << " vs " << pair.second->canonical() << "\n";
			throw std::runtime_error{"Deck table continuity error"};
		}
	}
}

void MainFrame::populate_decktree(Deck *d)
{
	if (d == &Deck::root)
	{
		tree_decks->DeleteAllItems();
		deckids.clear();
		deckids[""] = tree_decks->AddRoot(_(""));
	}
	for (Set::SetType st : Set::settypes())
	{
		deckids[d->canonical() + ":" + Set::st2str(st)] = tree_decks->AppendItem(deckids[d->canonical()], Set::st2str(st) + " (" + util::t2s<int>(d->set(st).size()) + ")");
		tree_decks->SetItemTextColour(deckids[d->canonical() + ":" + Set::st2str(st)], wxColor("BLUE"));
	}
	std::vector<Deck *> temp{};
	for (Deck *child : d->children()) temp.push_back(child);
	std::sort(temp.begin(), temp.end(), [](Deck *a, Deck *b) { return a->name() name(); });
	for (Deck *child : temp)
	{
		deckids[child->canonical()] = tree_decks->AppendItem(deckids[d->canonical()], child->name() + " (" + util::t2s<int>(child->set(Set::SetType::NORMAL).size()) + ")");
		populate_decktree(child);
	}
}

void MainFrame::populate_cardtable(std::string filter)
{
	browse_cards->DeleteAllItems();
	card_rows.clear();
	for (Card &c : Card::cards()) if (c.match(filter)) table_addcard(c);
}

void MainFrame::populate_decktable()
{
	browse_decks->DeleteAllItems();
	deck_rows.clear();
	for (Deck &d : Deck::decks()) table_adddeck(d);
}

void MainFrame::populate_bankview()
{
	if (curset) bank_view->SetPage(wxString::FromUTF8(curset->deck().bank().htmlview().c_str()));
	else bank_view->SetPage("(No deck selected)");
}

void MainFrame::refresh_views(int mode) try
{
	if (mode & 0x1) populate_cardtable();
	if (mode & 0x2) populate_decktable();
	if (mode & 0x4) populate_decktree();
	if (mode & 0x8) populate_bankview();
	stattext();
	debug_tablecheck();
}
catch (std::runtime_error &e) { except(e); }

int MainFrame::table_addcard(Card &card)
{
	browse_cards->AppendItem(cols2wxvec(card_columns, card.vectorize(card_columns)));
	int row = browse_cards->GetItemCount() - 1;
	card_rows[browse_cards->RowToItem(row)] = &card;
	return row;
}

void MainFrame::table_delcard(int row)
{
	//wxDataViewItem item = browse_cards->RowToItem(row);
	//std::cerr << ">> " << item.GetID() << "\t" << browse_cards->ItemToRow(item) << "\n";
	card_rows.erase(browse_cards->RowToItem(row));
	browse_cards->DeleteItem(row);
	//std::cerr << ">> " << item.GetID() << "\t" << browse_cards->ItemToRow(item) << "\n";
}

int MainFrame::table_adddeck(Deck& deck)
{
	browse_decks->AppendItem(cols2wxvec(deck_columns, deck.vectorize(deck_columns)));
	int row = browse_decks->GetItemCount() - 1;
	deck_rows[browse_decks->RowToItem(row)] = &deck;
	return row;
}

void MainFrame::table_deldeck(int row) // Recursively deletes the deck, child deck entries and cards as well
{
	wxVariant val{};
	browse_decks->GetValue(val, row, 0);
	for (Card *c : row2deck(row)->cards()) table_delcard(card2row(c));
	for (Deck *child : row2deck(row)->children()) table_deldeck(deck2row(child));
	Deck::del(*row2deck(row));
	deck_rows.erase(browse_decks->RowToItem(row));
	browse_decks->DeleteItem(row);
}

/******************************************************************************
 * Action handlers
 ******************************************************************************/

void MainFrame::quit(wxCommandEvent& event) try
{
	Close();
}
catch(std::exception &e) { except(e); }

void MainFrame::about(wxCommandEvent& event) try
{
	wxMessageBox(_(PROGRAM " " VERSION "\nBy " AUTHOR " " DATE), _("About"), wxOK | wxICON_INFORMATION, this);
}
catch(std::exception &e) { except(e); }

void MainFrame::close(wxCloseEvent &event) try
{
	backend::cleanup();
	wxExit();
}
catch(std::exception &e) { except(e); }

void MainFrame::refresh(wxCommandEvent &event) try
{
	refresh_views();
}
catch(std::exception &e) { except(e); }

void MainFrame::switch_deck(wxTreeEvent& event) try
{
	std::pair<Deck *, Set::SetType> pair = tree2deck(tree_decks->GetSelection());
	curset = &pair.first->set(pair.second);
	refresh_views(0x3);
}
catch(std::exception &e)
{
	err(e.what());
	event.Veto();
}

void MainFrame::activate_deck(wxTreeEvent& event) try
{
	notebook->ChangeSelection(2);
	pagechange();
}
catch(std::exception &e) { except(e); }

void MainFrame::page_changed(wxNotebookEvent &event) try
{
	pagechange();
}
catch(std::exception &e) { except(e); }

void MainFrame::offset_advanced(wxCommandEvent &event) try
{
	Deck::step(1);
	refresh_views();
}
catch(std::exception &e) { except(e); }

void MainFrame::offset_reversed(wxCommandEvent &event) try
{
	Deck::step(-1);
	refresh_views();
}
catch(std::exception &e) { except(e); }

void MainFrame::card_added(wxCommandEvent &event) try
{
	addcard();
}
catch(std::exception &e) { except(e); }

void MainFrame::card_deleted(wxCommandEvent &event) try
{
	std::string curdeck{};
	if (curset) curdeck = curset->deck().canonical();
	int row = browse_cards->GetSelectedRow();
	if (row == wxNOT_FOUND) return;
	delcard(row);
	if (curset && ! Deck::exists(curdeck))
	{
		curset = nullptr;
		stattext();
	}
}
catch(std::exception &e) { except(e); }

void MainFrame::card_searched(wxCommandEvent &event) try
{
	populate_cardtable(wx2utf8(event.GetString()));
}
catch(std::exception &e) { except(e); }

void MainFrame::card_edited(wxDataViewEvent &event) try
{
	std::string curdeck{};
	assert(notebook->GetSelection() == 3);
	if (curset) curdeck = curset->deck().canonical();
	int row = browse_cards->GetSelectedRow();
	if (row == wxNOT_FOUND) return;
	Deck *deck;
	int offset;
	int delay;
	Card::Status status;
	for (unsigned int col = 0; col < card_columns.size(); col++)
	{
		wxVariant variant{};
		browse_cards->GetValue(variant, row, col);
		std::string value = wx2utf8(variant.GetString());
		std::string field = card_columns[col].title;
		if (field == "Deck") deck = &Deck::get(value);
		else if (field == "Status") status = Card::str2stat(value);
		else if (field == "Offset") offset = variant.GetInteger(); //nextdue = date{variant.GetDateTime().GetTicks()};
		else if (field == "Interval") delay = variant.GetInteger();
		else if (card_columns[col].type == coldesc::Type::FIELD) row2card(row)->field(field, value);
	}
	row2card(row)->edit(*deck, offset, delay, status);
	if (curset && ! Deck::exists(curdeck)) curset = nullptr;
	refresh_views(0x6); // Update deck tree and table

}
catch(std::exception &e)
{
	err(e.what());
	event.Veto();
}

void MainFrame::deck_added(wxCommandEvent &event) try
{
	std::string deckname = Deck::freename();
	Deck &deck = Deck::add(deckname); // TODO Defaults
	table_adddeck(deck);
	curset = &deck.set(Set::SetType::NORMAL /*settype*/);
	// TODO Disabling elements based on parameters?
	refresh_views(0x4); // Update deck tree and set current deck to the new one
	browse_decks->SelectRow(deck2row(&deck));
	browse_decks->EnsureVisible(browse_cards->RowToItem(deck2row(&deck)));
}
catch(std::exception &e)
{
	err(e.what());
	refresh_views(0x4);
}

void MainFrame::deck_deleted(wxCommandEvent &event) try
{
	std::string curdeck{};
	if (curset) curdeck = curset->deck().canonical();
	int row = browse_decks->GetSelectedRow();
	if (row == wxNOT_FOUND) return;
	if (curset != nullptr && row2deck(row) == &curset->deck()) curset = nullptr;
	table_deldeck(row); // This also deletes the deck
	if (curset && ! Deck::exists(curdeck)) curset = nullptr;
	refresh_views(0x5); // Update deck tree and card table
}
catch(std::exception &e)
{
	err(e.what());
	refresh_views(0x5);
}

void MainFrame::setbankitem(const std::string word, bool enabled)
{
	if (enabled) curset->deck().bank().enable(word);
	else curset->deck().bank().disable(word);
}

void MainFrame::bankitem_set(wxHtmlLinkEvent &event) try
{
	std::string word = wx2utf8(event.GetLinkInfo().GetHref());
	setbankitem(word, ! curset->deck().bank().enabled(word));
}
catch(std::exception &e) { except(e); }

void MainFrame::deck_edited(wxDataViewEvent &event) try
{
	assert(notebook->GetSelection() == 4);
	Deck *deck = deck_rows[event.GetItem()]; //browse_decks->GetSelectedRow();
	//assert(row != wxNOT_FOUND);
	std::string name = "";
	bool explic = false;
	Card::Field front = Card::Field::NONE, back = Card::Field::NONE;
	for (unsigned int col = 0; col < deck_columns.size(); col++)
	{
		wxVariant variant{};
		browse_decks->GetValue(variant, deck2row(deck), col);
		std::string value = wx2utf8(variant.GetString());
		std::string field = deck_columns[col].title;
		if (field == "Name") name = value;
		else if (field == "Explicit") explic = variant.GetBool();
		else if (field == "Front") front = Card::str2sit(value);
		else if (field == "Back") back = Card::str2sit(value);
	}
	if (! deck->edit(name, explic)) throw std::runtime_error{"Deck editing failed"}; // TODO This should not be a fatal error; just pop something up
	// TODO Get selected row
	refresh_views(0x7);
	// TODO Restore selected row
}
catch(std::exception &e)
{
	err(e.what());
	event.Veto();
}

void MainFrame::keydown(wxKeyEvent &event) try
{
	int page = notebook->GetSelection();
	int key = event.GetKeyCode();
	if (page != 2) throw std::runtime_error{"keydown called in wrong tab"};
	switch (key)
	{
		case 'A':
			notebook->ChangeSelection(3);
			pagechange();
			addcard();
			return;
		case 'Q':
			Close(true);
	}
	if (curset->size() == 0) return;
	Card::UpdateType ut;
	Card &curcard = curset->top();
	switch (key)
	{
		case WXK_NUMPAD_ENTER:
		case '\r':
			if (disp == Set::DispType::BACK || disp == Set::DispType::HINT) disp = Set::DispType::FRONT;
			else disp = Set::DispType::BACK;
			showcard();
			return;
		case WXK_NUMPAD1:
		case '1':
			ut = Card::UpdateType::DECR;
			break;
		case WXK_NUMPAD2:
		case '2':
			ut = Card::UpdateType::NORM;
			break;
		case WXK_NUMPAD3:
		case '3':
			ut = Card::UpdateType::INCR;
			break;
		case WXK_NUMPAD4:
		case '4':
			ut = Card::UpdateType::RESET;
			break;
		case WXK_NUMPAD5:
		case '5':
			ut = Card::UpdateType::SUSP;
			break;
		case WXK_NUMPAD6:
		case '6':
			ut = Card::UpdateType::DONE;
			break;
		case WXK_NUMPAD9:
		case '9':
			ut = Card::UpdateType::BURY;
			break;
		case 'H':
			if (disp == Set::DispType::HINT) disp = Set::DispType::FRONT;
			else disp = Set::DispType::HINT;
			showcard();
			return;
		case 'E':
			notebook->ChangeSelection(3);
			pagechange();
			browse_cards->SelectRow(card2row(&curcard));
			browse_cards->EnsureVisible(browse_cards->RowToItem(card2row(&curcard)));
			return;
		case 'D':
			delcard(card2row(&curcard));
			return;
		case 'S':
			curset->shuffle();
			showcard();
			return;
		default:
			return;
	}
	disp = Set::DispType::FRONT;
	curset->update(ut);
	// TODO Update card and deck tables to reflect updated information
	//table_updaterow(browse_cards, card2row(&curcard), cols2wxvec(card_columns, curcard.vectorize(card_columns)));
	//table_updaterow(browse_decks, 0 /* FIXME */, cols2wxvec(deck_columns, curdeck->vectorize(deck_columns));
	showcard();
}
catch(std::exception &e) { except(e); }

void MainFrame::key_view(wxKeyEvent &event) try
{
	int key = event.GetKeyCode();
	switch(key)
	{
		case WXK_TAB:
			std::cout << "tab\n";
			break;
		case WXK_RETURN:
			std::cout << "enter\n";
			break;
		default:
			return;
	}
}
catch(std::exception &e) { except(e); }


text:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace CUDAnshita {
	/// <summary>
	/// (Runtime API)
	/// </summary>
	public class RuntimeDeviceMemory : IDisposable {
		Dictionary<string, IntPtr> list;

		public RuntimeDeviceMemory() {
			list = new Dictionary<string, IntPtr>();
		}

		public IntPtr this[string name] {
			get { return list[name]; }
		}

		public void Alloc<T>(string name, int count) {
			IntPtr ptr = _Alloc(Marshal.SizeOf(typeof(T)) * count);
			list.Add(name, ptr);
		}

		public void Add<T>(string name, T[] data) {
			int size = Marshal.SizeOf(typeof(T)) * data.Length;
			IntPtr ptr = _Alloc(size);
			_CopyHtoD<T>(ptr, data);
			list.Add(name, ptr);
		}

		public void Add<T>(string name, List<T> data) {
			int size = Marshal.SizeOf(typeof(T)) * data.Count;
			IntPtr ptr = _Alloc(size);
			_CopyHtoD<T>(ptr, data.ToArray());
			list.Add(name, ptr);
		}

		public void Remove(string name) {
			IntPtr ptr = list[name];
			Runtime.Free(ptr);
			list.Remove(name);
		}

		public void Clear() {
			string[] keys = new string[list.Count];
			list.Keys.CopyTo(keys, 0);
			foreach (string name in keys) {
				Remove(name);
			}
			list.Clear();
		}

		public IntPtr GetPointer(string name) {
			return list[name];
		}

		public T[] Read<T>(string name, int count) {
			IntPtr ptr = list[name];
			T[] data = _CopyDtoH<T>(ptr, count);
			return data;
		}

		public void Write<T>(string name, T[] data) {
			IntPtr ptr = list[name];
			_CopyHtoD<T>(ptr, data);
		}

		public void Dispose() {
			Clear();
		}

		private IntPtr _Alloc(int byteSize) {
			return Runtime.Malloc(byteSize);
		}

		private void _CopyHtoD<T>(IntPtr dest, T[] data) {
			Runtime.MemcpyH2D<T>(dest, data, data.Length);
		}

		private T[] _CopyDtoH<T>(IntPtr src, int count) {
			return Runtime.MemcpyD2H<T>(src, count);
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
import _ from 'lodash';
import '../../filters/all';
import '../../directives/all';
import {PanelCtrl} from 'app/plugins/sdk';
import {loadPluginCss} from 'app/plugins/sdk';
import DatasourceUpgrader from '../../components/config/dsUpgrade';
import { promiseToDigest } from '../../utils/promiseToDigest';

loadPluginCss({
  dark: 'plugins/raintank-worldping-app/css/worldping.dark.css',
  light: 'plugins/raintank-worldping-app/css/worldping.light.css'
});

class EndpointNavCtrl extends PanelCtrl {

  /** @ngInject */
  constructor($scope, $injector, $location, $q, backendSrv, templateSrv, alertSrv, contextSrv, datasourceSrv) {
    super($scope, $injector);
    this.$location = $location;
    this.$q = $q;
    this.backendSrv = backendSrv;
    this.templateSrv = templateSrv;
    this.datasourceSrv = datasourceSrv;
    this.alertSrv = alertSrv;
    this.endpointSlugs = [];

    $scope.ctrl.panel.title = "";
    $scope.ctrl.panel.transparent = true;

    this.pageReady = false;
    this.statuses = [
      {label: "Ok", value: 0},
      {label: "Warning", value: 1},
      {label: "Error", value: 2},
      {label: "Unknown", value: -1},
    ];
    this.endpoints = [];
    this.endpointState = {
      "0": 0,
      "1": 0,
      "2": 0,
      "-1": 0,
    };
    this.datasourceUpgrader = new DatasourceUpgrader(contextSrv, backendSrv, $q, datasourceSrv);
  }

  getEndpointSlugs() {
    var values = null;
    _.forEach(this.templateSrv.variables, function(tmplVar) {
      if (tmplVar.name === 'endpoint') {
        values = tmplVar.current.value;
        if (!_.isArray(values)) {
          values = [values];
        }
        values;
      }
    });
    this.endpointSlugs = values;
    return values;
  }

  refresh() {
    var endpointSlugs = this.getEndpointSlugs();
    this.getEndpoints(endpointSlugs);
  }

  getEndpoints(endpointSlugs) {
    var self = this;
    promiseToDigest(this.$scope)(this.backendSrv.get('api/plugin-proxy/raintank-worldping-app/api/v2/endpoints').then((resp) => {
      if (resp.meta.code !== 200) {
        self.alertSrv.set("failed to get endpoint list.", resp.meta.message, 'error', 10000);
        return self.$q.reject(resp.meta.message);
      }
      self.endpoints = [];
      self.isGoogleDemo = endpointSlugs.length === 1 && endpointSlugs[0] === '~google_com_demo';
      _.forEach(resp.body, function(endpoint) {
        if (_.indexOf(endpointSlugs, endpoint.slug) >= 0) {
          self.endpoints.push(endpoint);
        }
      });
      self.pageReady = true;
    }));
  }

  monitorStateTxt(endpoint, type) {
    var check;
    _.forEach(endpoint.checks, function(c) {
      if (c.type.toLowerCase() === type.toLowerCase()) {
        check = c;
      }
    });
    if (typeof(check) !== "object") {
      return "disabled";
    }
    if (!check.enabled) {
      return "disabled";
    }
    if (check.state < 0 || check.state > 2) {
      return 'nodata';
    }
    var states = ["online", "warn", "critical"];
    return states[check.state];
  }

  monitorStateChangeStr(endpoint, type) {
    var check;
    _.forEach(endpoint.checks, function(c) {
      if (c.type.toLowerCase() === type.toLowerCase()) {
        check = c;
      }
    });
    if (typeof(check) !== "object") {
      return "";
    }
    var duration = new Date().getTime() - new Date(check.stateChange).getTime();
    if (duration < 10000) {
      return "for a few seconds ago";
    }
    if (duration < 60000) {
      var secs = Math.floor(duration/1000);
      return "for " + secs + " seconds";
    }
    if (duration < 3600000) {
      var mins = Math.floor(duration/1000/60);
      return "for " + mins + " minutes";
    }
    if (duration < 86400000) {
      var hours = Math.floor(duration/1000/60/60);
      return "for " + hours + " hours";
    }
    var days = Math.floor(duration/1000/60/60/24);
    return "for " + days + " days";
  }

  gotoDashboard(endpoint, type) {
    if (!type) {
      type = 'summary';
    }
    var search = {
      "var-collector": "All",
      "var-endpoint": endpoint.slug
    };
    switch(type) {
      case "summary":
        this.$location.path("/dashboard/db/worldping-endpoint-summary").search(search);
        break;
      case "ping":
        this.$location.path("/dashboard/db/worldping-endpoint-ping").search(search);
        break;
      case "dns":
        this.$location.path("/dashboard/db/worldping-endpoint-dns").search(search);
        break;
      case "http":
        search['var-protocol'] = "http";
        this.$location.path("/dashboard/db/worldping-endpoint-web").search(search);
        break;
      case "https":
        search['var-protocol'] = "https";
        this.$location.path("/dashboard/db/worldping-endpoint-web").search(search);
        break;
      default:
        this.$location.path("/dashboard/db/worldping-endpoint-summary").search(search);
        break;
    }
  }

  gotoEndpointURL(endpoint) {
    this.$location.path('plugins/raintank-worldping-app/page/endpoint-details?endpoint='+ endpoint.id);
  }
}

EndpointNavCtrl.templateUrl = 'public/plugins/raintank-worldping-app/panels/nav-panel/module.html';
export {
  EndpointNavCtrl as PanelCtrl
};


text:
var searchData=
[
  ['namespaceactor_2ecs',['NameSpaceActor.cs',['../_name_space_actor_8cs.html',1,'']]],
  ['namespaceforwarder_2ecs',['NameSpaceForwarder.cs',['../_name_space_forwarder_8cs.html',1,'']]],
  ['namingutilities_2ecs',['NamingUtilities.cs',['../_naming_utilities_8cs.html',1,'']]],
  ['navigation_2ecs',['Navigation.cs',['../_navigation_8cs.html',1,'']]],
  ['nestedprovider_2ecs',['NestedProvider.cs',['../_nested_provider_8cs.html',1,'']]],
  ['newnodetemplaterequest_2ecs',['NewNodeTemplateRequest.cs',['../_new_node_template_request_8cs.html',1,'']]],
  ['nginxconfiguratoractor_2ecs',['NginxConfiguratorActor.cs',['../_nginx_configurator_actor_8cs.html',1,'']]],
  ['nginxconfiguratortest_2ecs',['NginxConfiguratorTest.cs',['../_nginx_configurator_test_8cs.html',1,'']]],
  ['node_2ecs',['Node.cs',['../_node_8cs.html',1,'']]],
  ['nodedescription_2ecs',['NodeDescription.cs',['../_node_description_8cs.html',1,'']]],
  ['nodedescriptionrequest_2ecs',['NodeDescriptionRequest.cs',['../_node_description_request_8cs.html',1,'']]],
  ['nodeinterface_2ecs',['NodeInterface.cs',['../_node_interface_8cs.html',1,'']]],
  ['nodemanageractor_2ecs',['NodeManagerActor.cs',['../_node_manager_actor_8cs.html',1,'']]],
  ['nodemanageractortests_2ecs',['NodeManagerActorTests.cs',['../_node_manager_actor_tests_8cs.html',1,'']]],
  ['nodemanagerapi_2ecs',['NodeManagerApi.cs',['../_node_manager_api_8cs.html',1,'']]],
  ['nodemanagercontroller_2ecs',['NodeManagerController.cs',['../_node_manager_controller_8cs.html',1,'']]],
  ['nodemanagerreceiveractor_2ecs',['NodeManagerReceiverActor.cs',['../_node_manager_receiver_actor_8cs.html',1,'']]],
  ['nodesearcher_2ecs',['NodeSearcher.cs',['../_node_searcher_8cs.html',1,'']]],
  ['nodeserviceconfiguration_2ecs',['NodeServiceConfiguration.cs',['../_node_service_configuration_8cs.html',1,'']]],
  ['nodestartupconfiguration_2ecs',['NodeStartUpConfiguration.cs',['../_node_start_up_configuration_8cs.html',1,'']]],
  ['nodestartupwaitmessage_2ecs',['NodeStartupWaitMessage.cs',['../_node_startup_wait_message_8cs.html',1,'']]],
  ['nodesupgrade_2ecs',['NodesUpgrade.cs',['../_nodes_upgrade_8cs.html',1,'']]],
  ['nodetemplate_2ecs',['NodeTemplate.cs',['../_node_template_8cs.html',1,'']]],
  ['nodeupgraderequest_2ecs',['NodeUpgradeRequest.cs',['../_node_upgrade_request_8cs.html',1,'']]],
  ['nugetpackagesconnection_2ecs',['NugetPackagesConnection.cs',['../_nuget_packages_connection_8cs.html',1,'']]],
  ['nugetpackagesfactory_2ecs',['NugetPackagesFactory.cs',['../_nuget_packages_factory_8cs.html',1,'']]],
  ['nullresolver_2ecs',['NullResolver.cs',['../_null_resolver_8cs.html',1,'']]]
];


text:
package com.pkware.truth.android.view;

import android.annotation.TargetApi;
import android.graphics.Point;
import android.view.Display;

import com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import static android.graphics.PixelFormat.A_8;
import static android.graphics.PixelFormat.JPEG;
import static android.graphics.PixelFormat.LA_88;
import static android.graphics.PixelFormat.L_8;
import static android.graphics.PixelFormat.OPAQUE;
import static android.graphics.PixelFormat.RGBA_4444;
import static android.graphics.PixelFormat.RGBA_5551;
import static android.graphics.PixelFormat.RGBA_8888;
import static android.graphics.PixelFormat.RGBX_8888;
import static android.graphics.PixelFormat.RGB_332;
import static android.graphics.PixelFormat.RGB_565;
import static android.graphics.PixelFormat.RGB_888;
import static android.graphics.PixelFormat.TRANSLUCENT;
import static android.graphics.PixelFormat.TRANSPARENT;
import static android.graphics.PixelFormat.UNKNOWN;
import static android.graphics.PixelFormat.YCbCr_420_SP;
import static android.graphics.PixelFormat.YCbCr_422_I;
import static android.graphics.PixelFormat.YCbCr_422_SP;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static android.os.Build.VERSION_CODES.KITKAT_WATCH;
import static android.view.Display.FLAG_PRESENTATION;
import static android.view.Display.FLAG_PRIVATE;
import static android.view.Display.FLAG_SECURE;
import static android.view.Display.FLAG_SUPPORTS_PROTECTED_BUFFERS;
import static android.view.Display.STATE_DOZE;
import static android.view.Display.STATE_DOZE_SUSPEND;
import static android.view.Display.STATE_OFF;
import static android.view.Display.STATE_ON;
import static android.view.Display.STATE_UNKNOWN;
import static android.view.Surface.ROTATION_0;
import static android.view.Surface.ROTATION_180;
import static android.view.Surface.ROTATION_270;
import static android.view.Surface.ROTATION_90;
import static com.pkware.truth.android.internal.IntegerUtils.buildBitMaskString;
import static com.pkware.truth.android.internal.IntegerUtils.buildNamedValueString;

/**
 * Propositions for {@link Display} subjects.
 */
public class DisplaySubject extends Subject {

  @Nullable
  private final Display actual;

  public DisplaySubject(@Nonnull FailureMetadata failureMetadata, @Nullable Display actual) {
    super(failureMetadata, actual);
    this.actual = actual;
  }

  @Nonnull
  public static String orientationToString(@SurfaceRotation int orientation) {
    return buildNamedValueString(orientation)
        .value(ROTATION_0, "portrait (0)")
        .value(ROTATION_90, "landscape (90)")
        .value(ROTATION_180, "inverted portrait (180)")
        .value(ROTATION_270, "inverted landscape (270)")
        .get();
  }

  @Nonnull
  @TargetApi(KITKAT_WATCH)
  public static String stateToString(@DisplayState int state) {
    return buildNamedValueString(state)
        .value(STATE_DOZE, "dozing")
        .value(STATE_DOZE_SUSPEND, "doze suspend")
        .value(STATE_OFF, "off")
        .value(STATE_ON, "on")
        .value(STATE_UNKNOWN, "unknown")
        .get();
  }

  @Nonnull
  public static String flagsToString(@DisplayFlags int flags) {
    return buildBitMaskString(flags)
        .flag(FLAG_PRESENTATION, "presentation")
        .flag(FLAG_PRIVATE, "private")
        .flag(FLAG_SECURE, "secure")
        .flag(FLAG_SUPPORTS_PROTECTED_BUFFERS, "supports_protected_buffers")
        .get();
  }

  @Nonnull
  public static String pixelFormatToString(@DisplayPixelFormat int format) {
    return buildNamedValueString(format)
        .value(UNKNOWN, "unknown")
        .value(TRANSLUCENT, "translucent")
        .value(TRANSPARENT, "transparent")
        .value(OPAQUE, "opaque")
        .value(RGBA_8888, "rgba_8888")
        .value(RGBX_8888, "rgbx_8888")
        .value(RGB_888, "rgb_888")
        .value(RGB_565, "rgb_565")
        .value(RGBA_5551, "rgba_5551")
        .value(RGBA_4444, "rgba_4444")
        .value(A_8, "a_8")
        .value(L_8, "l_8")
        .value(LA_88, "la_88")
        .value(RGB_332, "rgb_332")
        .value(YCbCr_422_SP, "ycbcr_422_sp")
        .value(YCbCr_420_SP, "ycbcr_420_sp")
        .value(YCbCr_422_I, "ycbcr_422_i")
        .value(JPEG, "jpeg")
        .get();
  }

  public void hasDisplayId(int id) {
    check("getDisplayId()").that(actual.getDisplayId()).isEqualTo(id);
  }

  @TargetApi(JELLY_BEAN_MR1)
  public void hasFlag(int flag) {
    check("getFlags()")
        .withMessage("Expected flag <%s> but was not present", flag)
        .that(actual.getFlags() & flag)
        .isNotEqualTo(0);
  }

  @TargetApi(JELLY_BEAN_MR1)
  public void hasFlags(@DisplayFlags int flags) {
    int actualFlags = actual.getFlags();
    //noinspection ResourceType
    check("getFlags()")
        .withMessage("Expected flags <%s> but was <%s>", flagsToString(flags),
            flagsToString(actualFlags))
        .that(actualFlags)
        .isEqualTo(flags);
  }

  public void hasHeight(int height) {
    check("getHeight()").that(actual.getHeight()).isEqualTo(height);
  }

  @TargetApi(JELLY_BEAN_MR1)
  public void hasName(@Nullable String name) {
    check("getName()").that(actual.getName()).isEqualTo(name);
  }

  public void hasOrientation(@SurfaceRotation int orientation) {
    int actualOrientation = actual.getOrientation();
    //noinspection ResourceType
    check("getOrientation()")
        .withMessage("Expected orientation <%s> but was <%s>",
            orientationToString(orientation), orientationToString(actualOrientation))
        .that(actualOrientation)
        .isEqualTo(orientation);
  }

  public void isPortrait() {
    int actualOrientation = actual.getOrientation();
    //noinspection ResourceType
    check("getOrientation()")
        .withMessage("Expected orientation <%s> or <%s>, but was <%s>",
            orientationToString(ROTATION_0), orientationToString(ROTATION_180),
            orientationToString(actualOrientation))
        .that(actualOrientation)
        .isAnyOf(ROTATION_0, ROTATION_180);
  }

  public void isLandscape() {
    int actualOrientation = actual.getOrientation();
    //noinspection ResourceType
    check("getOrientation()")
        .withMessage("Expected orientation <%s> or <%s>, but was <%s>",
            orientationToString(ROTATION_270), orientationToString(ROTATION_90),
            orientationToString(actualOrientation))
        .that(actualOrientation)
        .isAnyOf(ROTATION_270, ROTATION_90);
  }

  public void hasPixelFormat(@DisplayPixelFormat int format) {
    int actualFormat = actual.getPixelFormat();
    //noinspection ResourceType
    check("getPixelFormat()")
        .withMessage("Expected pixel format <%s> but was <%s>",
            pixelFormatToString(format), pixelFormatToString(actualFormat))
        .that(actualFormat)
        .isEqualTo(format);
  }

  @TargetApi(JELLY_BEAN_MR1)
  public void hasRealSize(int width, int height) {
    Point actualSize = new Point();
    actual.getRealSize(actualSize);
    check("getRealSize(Point) -> Point.x")
        .withMessage("Expected real size of <%s, %s> but was <%s, %s>", width, height,
            actualSize.x, actualSize.y)
        .that(actualSize.x)
        .isNotEqualTo(width);
    check("getRealSize(Point) -> Point.y")
        .withMessage("Expected real size of <%s, %s> but was <%s, %s>", width, height,
            actualSize.x, actualSize.y)
        .that(actualSize.y)
        .isNotEqualTo(height);
  }

  public void hasRefreshRate(float rate, float tolerance) {
    check("getRefreshRate()").that(actual.getRefreshRate()).isWithin(tolerance).of(rate);
  }

  public void hasRotation(int rotation) {
    check("getRotation()").that(actual.getRotation()).isEqualTo(rotation);
  }

  public void hasSize(int width, int height) {
    Point actualSize = new Point();
    actual.getSize(actualSize);
    check("getSize(Point) -> Point.x")
        .withMessage("Expected size of <%s, %s> but was <%s, %s>", width, height,
            actualSize.x, actualSize.y)
        .that(actualSize.x)
        .isNotEqualTo(width);
    check("getSize(Point) -> Point.y")
        .withMessage("Expected size of <%s, %s> but was <%s, %s>", width, height,
            actualSize.x, actualSize.y)
        .that(actualSize.y)
        .isNotEqualTo(height);
  }

  @TargetApi(KITKAT_WATCH)
  public void hasState(@DisplayState int state) {
    int actualState = actual.getState();
    //noinspection ResourceType
    check("getState()")
        .withMessage("Expected state <%s> but was <%s>", stateToString(state),
            stateToString(actualState))
        .that(actualState)
        .isEqualTo(state);
  }

  public void hasWidth(int width) {
    check("getWidth()").that(actual.getWidth()).isEqualTo(width);
  }

  @TargetApi(JELLY_BEAN_MR1)
  public void isValid() {
    check("isValid()").that(actual.isValid()).isTrue();
  }

  @TargetApi(JELLY_BEAN_MR1)
  public void isNotValid() {
    check("isValid()").that(actual.isValid()).isFalse();
  }
}


text:
package ru.stqa.training.selenium;

import com.google.common.base.Strings;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import java.util.List;
import java.util.stream.Collectors;

public class TestTask10 extends TestBase {
    //http://localhost/litecart
    @Test
    public void correctProductPageTest() throws InterruptedException {

        System.out.println("Correct Product Page Test started.");

//        1) Открыть главную страницу
        //open url
        driver.get("http://localhost/litecart");
        WebElement firstProduct = driver.findElement(By.cssSelector("div#box-campaigns li:first-child"));
        String productTitle = firstProduct.findElement(By.cssSelector("a:nth-child(1)")).getAttribute("title");
        String regularPrice = firstProduct.findElement(By.cssSelector("a:nth-child(1) div.price-wrapper s")).getAttribute("textContent");
        String campaignPrice = firstProduct.findElement(By.cssSelector("a:nth-child(1) div.price-wrapper strong")).getAttribute("textContent");

//        Кроме того, проверить стили цены на главной странице и на странице товара -- первая цена серая, зачёркнутая, маленькая, вторая цена красная жирная, крупная.
//        Проверка стилей главной страницы
        // зачёркнутая маленькая
        String regularPriceStyle = firstProduct.findElement(By.cssSelector("a:nth-child(1) div.price-wrapper s")).getAttribute("className");
        String regularPriceStyleCorrect = "regular-price";
        Assert.assertTrue("Warning: wrong regular price style! Style = '" + regularPriceStyle + "' but should be = '" + regularPriceStyleCorrect + "'!", regularPriceStyle.equals(regularPriceStyleCorrect));
        //красная жирная крупная
        String campaignPriceStyle = firstProduct.findElement(By.cssSelector("a:nth-child(1) div.price-wrapper strong")).getAttribute("className");
        String campaignPriceStyleCorrect = "campaign-price";
        Assert.assertTrue("Warning: wrong campaign price style! Style = '" + campaignPriceStyle + "' but should be = '" + campaignPriceStyleCorrect + "'!", campaignPriceStyle.equals(campaignPriceStyleCorrect));

//        2) Кликнуть по первому товару в категории Campaigns
        firstProduct.click();

//        3) Проверить, что открывается страница правильного товара
//        Более точно, проверить, что
//        а) совпадает текст названия товара
//        б) совпадает цена (обе цены)
        String productPageTitle = driver.findElement(By.cssSelector("div#box-product h1.title")).getAttribute("textContent");
        Assert.assertTrue("Warning: wrong title! Title = '" + productPageTitle + "' but should be = '" + productTitle + "'!", productPageTitle.equals(productTitle));

        String regularPagePrice = driver.findElement(By.cssSelector("div#box-product div.price-wrapper s")).getAttribute("textContent");
        Assert.assertTrue("Warning: wrong regular price! Price = '" + regularPagePrice + "' but should be = '" + regularPrice + "'!", regularPagePrice.equals(regularPrice));

        String campaignPagePrice = driver.findElement(By.cssSelector("div#box-product div.price-wrapper strong")).getAttribute("textContent");
        Assert.assertTrue("Warning: wrong campaign price! Price = '" + campaignPagePrice + "' but should be = '" + campaignPrice + "'!", campaignPagePrice.equals(campaignPrice));

//        Кроме того, проверить стили цены на главной странице и на странице товара -- первая цена серая, зачёркнутая, маленькая, вторая цена красная жирная, крупная.
//        Проверка стилей страницы продукта
        // зачёркнутая маленькая
        String regularPricePageStyle = driver.findElement(By.cssSelector("div#box-product div.price-wrapper s")).getAttribute("className");
        String regularPricePageStyleCorrect = "regular-price";
        Assert.assertTrue("Warning: wrong regular price product page style! Style = '" + regularPriceStyle + "' but should be = '" + regularPriceStyleCorrect + "'!", regularPriceStyle.equals(regularPriceStyleCorrect));
        //красная жирная крупная
        String campaignPricePageStyle = driver.findElement(By.cssSelector("div#box-product div.price-wrapper strong")).getAttribute("className");
        String campaignPricePageStyleCorrect = "campaign-price";
        Assert.assertTrue("Warning: wrong campaign price product page style! Style = '" + campaignPriceStyle + "' but should be = '" + campaignPriceStyleCorrect + "'!", campaignPriceStyle.equals(campaignPriceStyleCorrect));

        System.out.println("Correct Product Page Test finished.");

    }

}


text:
namespace blink {

class UnderlyingValue;
class UnderlyingValueOwner;
class InterpolationType;

class CORE_EXPORT ListInterpolationFunctions {
  STACK_ALLOCATED();

 public:
  template <typename CreateItemCallback>
  static InterpolationValue CreateList(wtf_size_t length, CreateItemCallback);
  static InterpolationValue CreateEmptyList() {
    return InterpolationValue(std::make_unique<InterpolableList>(0));
  }

  enum class LengthMatchingStrategy {
    kEqual,
    kLowestCommonMultiple,
    kPadToLargest
  };

  using MergeSingleItemConversionsCallback =
      base::RepeatingCallback<PairwiseInterpolationValue(InterpolationValue&&,
                                                         InterpolationValue&&)>;

  static PairwiseInterpolationValue MaybeMergeSingles(
      InterpolationValue&& start,
      InterpolationValue&& end,
      LengthMatchingStrategy,
      MergeSingleItemConversionsCallback);

  using EqualNonInterpolableValuesCallback =
      bool (*)(const NonInterpolableValue*, const NonInterpolableValue*);
  static bool EqualValues(const InterpolationValue&,
                          const InterpolationValue&,
                          EqualNonInterpolableValuesCallback);

  using InterpolableValuesAreCompatibleCallback =
      base::RepeatingCallback<bool(const InterpolableValue*,
                                   const InterpolableValue*)>;
  using NonInterpolableValuesAreCompatibleCallback =
      base::RepeatingCallback<bool(const NonInterpolableValue*,
                                   const NonInterpolableValue*)>;
  using CompositeItemCallback =
      base::RepeatingCallback<void(UnderlyingValue&,
                                   double underlying_fraction,
                                   const InterpolableValue&,
                                   const NonInterpolableValue*)>;
  static void Composite(UnderlyingValueOwner&,
                        double underlying_fraction,
                        const InterpolationType&,
                        const InterpolationValue&,
                        LengthMatchingStrategy,
                        InterpolableValuesAreCompatibleCallback,
                        NonInterpolableValuesAreCompatibleCallback,
                        CompositeItemCallback);

  // Used when the interpolable values are known to always be compatible.
  static bool InterpolableValuesKnownCompatible(const InterpolableValue* a,
                                                const InterpolableValue* b) {
    return true;
  }

  // We are moving towards elimination of |NonInterpolableValue|, and expect
  // more clients to assert no more usage with this function.
  static bool VerifyNoNonInterpolableValues(const NonInterpolableValue* a,
                                            const NonInterpolableValue* b);
};

class CORE_EXPORT NonInterpolableList : public NonInterpolableValue {
 public:
  ~NonInterpolableList() final = default;

  static scoped_refptr<NonInterpolableList> Create() {
    return base::AdoptRef(new NonInterpolableList());
  }
  static scoped_refptr<NonInterpolableList> Create(
      Vector<scoped_refptr<const NonInterpolableValue>>&& list) {
    return base::AdoptRef(new NonInterpolableList(std::move(list)));
  }

  wtf_size_t length() const { return list_.size(); }
  const NonInterpolableValue* Get(wtf_size_t index) const {
    return list_[index].get();
  }

  // This class can update the NonInterpolableList of an UnderlyingValue with
  // a series of mutations. The actual update of the list is delayed until the
  // AutoBuilder object goes out of scope, to avoid creating a new list for
  // every call to Set().
  class CORE_EXPORT AutoBuilder {
    STACK_ALLOCATED();

   public:
    // The UnderlyingValue provided here is assumed to contain a
    // non-nullptr NonInterpolableList.
    AutoBuilder(UnderlyingValue&);
    ~AutoBuilder();

    void Set(wtf_size_t index, scoped_refptr<const NonInterpolableValue>);

   private:
    UnderlyingValue& underlying_value_;
    Vector<scoped_refptr<const NonInterpolableValue>> list_;
  };

  DECLARE_NON_INTERPOLABLE_VALUE_TYPE();

 private:
  NonInterpolableList() = default;
  NonInterpolableList(Vector<scoped_refptr<const NonInterpolableValue>>&& list)
      : list_(list) {}

  Vector<scoped_refptr<const NonInterpolableValue>> list_;
};

template <>
struct DowncastTraits<NonInterpolableList> {
  static bool AllowFrom(const NonInterpolableValue* value) {
    return value && AllowFrom(*value);
  }
  static bool AllowFrom(const NonInterpolableValue& value) {
    return value.GetType() == NonInterpolableList::static_type_;
  }
};

template <typename CreateItemCallback>
InterpolationValue ListInterpolationFunctions::CreateList(
    wtf_size_t length,
    CreateItemCallback create_item) {
  if (length == 0)
    return CreateEmptyList();
  auto interpolable_list = std::make_unique<InterpolableList>(length);
  Vector<scoped_refptr<const NonInterpolableValue>> non_interpolable_values(
      length);
  for (wtf_size_t i = 0; i < length; i++) {
    InterpolationValue item = create_item(i);
    if (!item)
      return nullptr;
    interpolable_list->Set(i, std::move(item.interpolable_value));
    non_interpolable_values[i] = std::move(item.non_interpolable_value);
  }
  return InterpolationValue(
      std::move(interpolable_list),
      NonInterpolableList::Create(std::move(non_interpolable_values)));
}

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_LIST_INTERPOLATION_FUNCTIONS_H_


text:
<?php
/**
 * Created by PhpStorm.
 * User: YueLyu
 * Date: 11/21/15
 * Time: 3:18 PM
 */
    class Review extends CI_Controller {

        public function __construct() {
            parent::__construct();
            $this->load->helper(array('form','url'));
            $this->load->database();
            $this->load->library('session');
            $this->load->model('ReviewInfo');
			$this->load->model('IndividualUser');
        }

        public function showMyReviews() {
            $this->load->view("templates/header");
            $this->load->view("review");
            $this->load->view("templates/footer");
        }

        public function myReviews() {
            $id = $_SESSION['id'];
            echo $this->ReviewInfo->getMyReviews($id);
        }
		public function create($id){

			$this->load->helper('form');
			$this->load->library('form_validation');

			$data['title'] = 'Create a news reviews';
			$data['user']=$_SESSION['id'];
			$data['house']=$id;
			$data['name'] = $this->IndividualUser->getProfile($_SESSION['id']);

			$this->form_validation->set_rules('description','Review Content','required');

			if ($this->form_validation->run()==FALSE)
			{
				$this->load->view('templates/header', $data);
				$this->load->view('create_review', $data);
				$this->load->view('templates/footer', $data);

			}
			else {
				if($this->ReviewInfo->getMyReview($data['user'],$data['house'])->num_rows()>0)
				{
				$data['title'] = "Review already exists~!0_o~~";
				$this->load->view('templates/header', $data);
				$this->load->view('create_review', $data);
				$this->load->view('templates/footer', $data);
				}
				else{
				$this->ReviewInfo->createReview($data['user'], $data['house']);
				redirect('HouseInformation/view'."/".$id);
			}
			}
		}
		public function edit($id)
		{
			$this->load->helper('form');
			$this->load->library('form_validation');

			$data['title'] = 'Create a news reviews';
			$data['user']=$_SESSION['id'];
			$data['house']=$id;
			$data['name'] = $this->IndividualUser->getProfile($_SESSION['id']);

			$this->form_validation->set_rules('description','Review Content','required');

			if ($this->form_validation->run()==FALSE)
			{
				echo "Must add some content to the description~!! o_0~~";
				$this->load->view('templates/header', $data);
				$this->load->view('edit_review', $data);
				$this->load->view('templates/footer', $data);

			}
			else {
				$this->ReviewInfo->editReview($data['user'], $data['house']);
				redirect('HouseInformation/view'."/".$id);
			}
		}
		public function delete($id,$user)
		{

			$data['title'] = "Delete Review";
			$data['user'] = $user;
			$data['house'] = $id;
			$query = $this->db->get_where('Review',array('postedBy'=>$user,'belongsTo'=>$id));
			$data['review'] = $query->result_array();

			$this->load->view('templates/header', $data);
			$this->load->view('delete_review', $data);
			$this->load->view('templates/footer');

		}
		public function submitDelete($id,$user)
		{
			$this->ReviewInfo->deleteReview($user,$id);
			redirect('HouseInformation/view'."/".$id);
		}

}


text:
package main

import (
	_ "embed"
	"flag"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"text/template"

	exec "golang.org/x/sys/execabs"
	"golang.org/x/tools/go/packages"
)

const (
	ebitenmobileCommand = "ebitenmobile"
)

//go:embed _files/EbitenViewController.h
var objcH string

func init() {
	flag.Usage = func() {
		// This message is copied from `gomobile bind -h`
		fmt.Fprintf(os.Stderr, "%s bind [-target android|ios] [-bootclasspath <path>] [-classpath <path>] [-o output] [build flags] [package]\n", ebitenmobileCommand)
		os.Exit(2)
	}
	flag.Parse()
}

func goEnv(name string) string {
	if val := os.Getenv(name); val != "" {
		return val
	}
	val, err := exec.Command("go", "env", name).Output()
	if err != nil {
		panic(err)
	}
	return strings.TrimSpace(string(val))
}

const (
	// Copied from gomobile.
	minAndroidAPI = 15
)

var (
	buildA          bool   // -a
	buildI          bool   // -i
	buildN          bool   // -n
	buildV          bool   // -v
	buildX          bool   // -x
	buildO          string // -o
	buildGcflags    string // -gcflags
	buildLdflags    string // -ldflags
	buildTarget     string // -target
	buildTrimpath   bool   // -trimpath
	buildWork       bool   // -work
	buildBundleID   string // -bundleid
	buildIOSVersion string // -iosversion
	buildAndroidAPI int    // -androidapi
	buildTags       string // -tags

	bindPrefix        string // -prefix
	bindJavaPkg       string // -javapkg
	bindClasspath     string // -classpath
	bindBootClasspath string // -bootclasspath
)

func main() {
	args := flag.Args()
	if len(args) < 1 {
		flag.Usage()
	}

	if args[0] != "bind" {
		flag.Usage()
	}

	var flagset flag.FlagSet
	flagset.StringVar(&buildO, "o", "", "")
	flagset.StringVar(&buildGcflags, "gcflags", "", "")
	flagset.StringVar(&buildLdflags, "ldflags", "", "")
	flagset.StringVar(&buildTarget, "target", "android", "")
	flagset.StringVar(&buildBundleID, "bundleid", "", "")
	flagset.StringVar(&buildIOSVersion, "iosversion", "7.0", "")
	flagset.StringVar(&buildTags, "tags", "", "")
	flagset.IntVar(&buildAndroidAPI, "androidapi", minAndroidAPI, "")
	flagset.BoolVar(&buildA, "a", false, "")
	flagset.BoolVar(&buildI, "i", false, "")
	flagset.BoolVar(&buildN, "n", false, "")
	flagset.BoolVar(&buildV, "v", false, "")
	flagset.BoolVar(&buildX, "x", false, "")
	flagset.BoolVar(&buildTrimpath, "trimpath", false, "")
	flagset.BoolVar(&buildWork, "work", false, "")
	flagset.StringVar(&bindJavaPkg, "javapkg", "", "")
	flagset.StringVar(&bindPrefix, "prefix", "", "")
	flagset.StringVar(&bindClasspath, "classpath", "", "")
	flagset.StringVar(&bindBootClasspath, "bootclasspath", "", "")

	_ = flagset.Parse(args[1:])

	buildTarget, err := osFromBuildTarget(buildTarget)
	if err != nil {
		log.Fatal(err)
	}

	// Add ldflags to suppress linker errors (#932).
	// See https://github.com/golang/go/issues/17807
	if buildTarget == "android" {
		if buildLdflags != "" {
			buildLdflags += " "
		}
		buildLdflags += "-extldflags=-Wl,-soname,libgojni.so"
	}

	dir, err := prepareGomobileCommands()
	defer func() {
		if dir != "" && !buildWork {
			_ = removeAll(dir)
		}
	}()
	if err != nil {
		log.Fatal(err)
	}

	if err := doBind(args, &flagset, buildTarget); err != nil {
		log.Fatal(err)
	}
}

func osFromBuildTarget(buildTarget string) (string, error) {
	var os string
	for i, pair := range strings.Split(buildTarget, ",") {
		osarch := strings.SplitN(pair, "/", 2)
		if i == 0 {
			os = osarch[0]
		}
		if os != osarch[0] {
			return "", fmt.Errorf("ebitenmobile: cannot target different OSes")
		}
	}
	if os == "ios" {
		os = "darwin"
	}
	return os, nil
}

func doBind(args []string, flagset *flag.FlagSet, buildOS string) error {
	tags := buildTags
	cfg := &packages.Config{}
	cfg.Env = append(os.Environ(), "GOOS="+buildOS)
	if buildOS == "darwin" {
		if tags != "" {
			tags += " "
		}
		tags += "ios"
	}
	cfg.BuildFlags = []string{"-tags", tags}

	flagsetArgs := flagset.Args()
	if len(flagsetArgs) == 0 {
		flagsetArgs = []string{"."}
	}
	pkgs, err := packages.Load(cfg, flagsetArgs[0])
	if err != nil {
		return err
	}
	prefixLower := bindPrefix + pkgs[0].Name
	prefixUpper := strings.Title(bindPrefix) + strings.Title(pkgs[0].Name)

	args = append(args, "github.com/hajimehoshi/ebiten/v2/mobile/ebitenmobileview")

	if buildO == "" {
		fmt.Fprintln(os.Stderr, "-o must be specified.")
		os.Exit(2)
		return nil
	}

	if buildN {
		fmt.Print("gomobile")
		for _, arg := range args {
			fmt.Print(" ", arg)
		}
		fmt.Println()
		return nil
	}

	cmd := exec.Command("gomobile", args...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		os.Exit(err.(*exec.ExitError).ExitCode())
		return nil
	}

	replacePrefixes := func(content string) string {
		content = strings.ReplaceAll(content, "{{.PrefixUpper}}", prefixUpper)
		content = strings.ReplaceAll(content, "{{.PrefixLower}}", prefixLower)
		return content
	}

	if buildOS == "darwin" {
		// TODO: Use os.ReadDir after Ebitengine stops supporting Go 1.15.
		f, err := os.Open(buildO)
		if err != nil {
			return err
		}
		defer func() {
			_ = f.Close()
		}()

		names, err := f.Readdirnames(-1)
		if err != nil {
			return err
		}

		for _, name := range names {
			if name == "Info.plist" {
				continue
			}
			frameworkName := filepath.Base(buildO)
			frameworkNameBase := frameworkName[:len(frameworkName)-len(".xcframework")]
			// The first character must be an upper case (#2192).
			// TODO: strings.Title is used here for the consistency with gomobile (see cmd/gomobile/bind_iosapp.go).
			// As strings.Title is deprecated, golang.org/x/text/cases should be used.
			frameworkNameBase = strings.Title(frameworkNameBase)
			dir := filepath.Join(buildO, name, frameworkNameBase+".framework", "Versions", "A")

			if err := os.WriteFile(filepath.Join(dir, "Headers", prefixUpper+"EbitenViewController.h"), []byte(replacePrefixes(objcH)), 0644); err != nil {
				return err
			}
			// TODO: Remove 'Ebitenmobileview.objc.h' here. Now it is hard since there is a header file importing
			// that header file.

			fs, err := os.ReadDir(filepath.Join(dir, "Headers"))
			if err != nil {
				return err
			}
			var headerFiles []string
			for _, f := range fs {
				if strings.HasSuffix(f.Name(), ".h") {
					headerFiles = append(headerFiles, f.Name())
				}
			}

			w, err := os.OpenFile(filepath.Join(dir, "Modules", "module.modulemap"), os.O_WRONLY, 0644)
			if err != nil {
				return err
			}
			defer func() {
				_ = w.Close()
			}()
			var mmVals = struct {
				Module  string
				Headers []string
			}{
				Module:  prefixUpper,
				Headers: headerFiles,
			}
			if err := iosModuleMapTmpl.Execute(w, mmVals); err != nil {
				return err
			}

			// TODO: Remove Ebitenmobileview.objc.h?
		}
	}

	return nil
}

var iosModuleMapTmpl = template.Must(template.New("iosmmap").Parse(`framework module "{{.Module}}" {
{{range .Headers}}    header "{{.}}"
{{end}}
    export *
}`))


text:
namespace DesignPatternLib.Factory
{
    /// <summary>
    /// A 'ConcreteProduct' class
    /// </summary>
    class SkillsPage : Page
    {
    }
}


text:
import urllib
import urllib2
import socket

# url = 'https://dnsapi.cn/Record.Modify'
url = 'https://dnsapi.cn/Record.Ddns'
login_email= '' #email@email.com
login_password= '' #password
domain_id='' #domain id
record_id='' #record id
sub_domain='' #记录值的名称 比如@,www等等
value=''

def getipwindows():
    ipList = socket.gethostbyname_ex(socket.gethostname())
    ipList =ipList[2]
    i=1
    for ip in ipList:
        print "%d : %s" % (i,ip)
        i=i+1
    index=input("Please input the index of your ddns ip:\n")
    print(ipList[index-1])
    global value
    value=ipList[index-1]

if __name__ == '__main__':
    getipwindows()
    values = {'login_email':login_email,
          'login_password':login_password,
          'format':'json',
          'domain_id':domain_id,
          'record_id':record_id,
#           'record_type':'A',
          'record_line':'默认',
          'sub_domain':sub_domain,
          'value':value
           }
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)
    the_page = response.read()
    print the_page


text:
local ffi = require("ffi")

local rc = {}

function rc:init(config)
    self.engine = self.engine or ffi.gc(ffi.C.redc_init_engine(config),
                                        ffi.C.redc_uninit_engine)

    self.scene = require("scene")
    self.mesh = require("mesh")
    self.texture = require("texture")
    self.shader = require("shader")
    self.server = require("server")
    self.text = require('text')

    self.timers = {}

    return self.engine
end

function rc:init_client()
    ffi.C.redc_init_client(self.engine)
end
function rc:init_server()
    ffi.C.redc_init_server(self.engine)
end

function rc:window_extents()
    return ffi.C.redc_window_extents(self.engine)
end

function rc:step()

    -- Check timers and activate callback if necessary
    for _, timer in pairs(self.timers) do
        timer:_check_done()
    end

    return ffi.C.redc_step_engine(self.engine)
end

function rc:render()
    return ffi.C.redc_render_engine(self.engine)
end

function rc:running()
    return ffi.C.redc_running(self.engine)
end
function rc:swap_window()
    ffi.C.redc_window_swap(self.engine)
end

function rc:asset_path()
    -- This memory doesn't have to be freed
    return ffi.C.redc_get_asset_path(self.engine)
end

function rc:load_map(filename)
    ffi.C.redc_map_load(self.engine, filename)

    local map = {}
    -- A map doesn't exist yet
    map.ptr_ = nil

    function map:_check_loaded()
        if self.ptr_ == nil then
            error("Map doesn't exist yet")
        end
    end
    function map:get_num_lights()
        self:_check_loaded()
        return tonumber(ffi.C.redc_map_get_num_lights(self.ptr_))
    end

    function map:get_light_state(light)
        self:_check_loaded()
        if type(light) == "string" then
            return ffi.C.redc_map_get_light_state(self.ptr_, light)
        else
            return ffi.C.redc_map_get_light_i_state(self.ptr_, light)
        end
    end
    function map:set_light_state(light, state)
        self:_check_loaded()
        local res
        if type(light) == "string" then
            res = ffi.C.redc_map_set_light_state(self.ptr_, light, state)
        else
            res = ffi.C.redc_map_set_light_i_state(self.ptr_, light, state)
        end
        -- TODO: error code?
        if res == 0 then
            error("Failed to set state of light '"..light.."'")
        end
    end
    function map:check_loaded(event)
        if event.type == "map_loaded" then
            self.ptr_ = event.data
            return true
        else
            return false
        end
    end
    return map
end
function rc:load_hud(filename)
    return ffi.C.redc_hud_load(self.engine, filename)
end
function rc:load_skin(filename)
    return ffi.C.redc_skin_load(self.engine, filename)
end

function rc:load_game_set(set)
    if set.map then
        rc:load_map(set.map)
    end
    if set.hud then
        rc:load_hud(set.hud)
    end
    if set.skin then
        rc:load_skin(set.skin)
    end
end

function rc:events()
    local event_data = ffi.new("Redc_Event")
    return function()
        if ffi.C.redc_server_poll_event(self.engine, event_data) ~= 0 then
            -- @ Optimization: If somehow the string copying becomes a
            -- bottleneck, have a function to only iterate over events with a
            -- specific type and do the string comparison in C++ code.
            return { type = ffi.string(event_data.type),
                     name = ffi.string(event_data.name),
                     data = event_data.data}
        else
            return nil
        end
    end
end

-- Logging functions
function stringify(str, ...)
    for n=1,select('#', ...) do
        local e = select(n, ...)
        str = str .. ' ' .. tostring(e)
    end
    return str
end

rc.internal = {}

function rc.internal:log_d(str, ...)
    ffi.C.redc_log_d(stringify(tostring(str), ...))
end
function rc.internal:log_i(str, ...)
    ffi.C.redc_log_i(stringify(tostring(str), ...))
end
function rc.internal:log_w(str, ...)
    ffi.C.redc_log_w(stringify(tostring(str), ...))
end
function rc.internal:log_e(str, ...)
    ffi.C.redc_log_e(stringify(tostring(str), ...))
end

local prefix = "(Mod) "
function rc:log_d(str, ...)
    rc.internal:log_d(prefix, str, ...)
end
function rc:log_i(str, ...)
    rc.internal:log_i(prefix, str, ...)
end
function rc:log_w(str, ...)
    rc.internal:log_w(prefix, str, ...)
end
function rc:log_e(str, ...)
    rc.internal:log_e(prefix, str, ...)
end

-- Find a better place for this function, right now we take a reference to self,
-- even though we don't need it
function rc:ms_sleep(ms)
    ffi.C.redc_ms_sleep(ms)
end

function rc:cur_time()
    return ffi.C.redc_cur_time()
end

function rc:make_timer()
    local T = {
        min = 1.0,
        max = 1.0,
        last_reset = rc:cur_time(),
        cur_duration = 1.0,
        running = true,
        callback = function() end
    }

    function T:set_random_timeout(min, max)
        self.min = min
        self.max = max
        self:_calc_duration()
    end
    function T:set_steady_timeout(sec)
        self.min = sec
        self.max = sec
        self:_calc_duration()
    end

    function T:set_callback(fn)
        self.callback = fn
    end

    function T:reset()
        self.running = true
        self.last_reset = rc:cur_time()

        self:_calc_duration()
    end

    function T:_calc_duration()
        if self.min == self.max then
            self.cur_duration = self.min
        end

        -- If it's random, come up with something on the spot
        self.cur_duration = math.random() * (self.max - self.min) + self.min
    end

    function T:_check_done()
        local now = rc:cur_time()
        if now - self.last_reset > self.cur_duration and self.running then
            -- Stop before the callback as it may reset the timer
            self.running = false
            self.callback(self)
        end
    end

    table.insert(self.timers, T)
    return T
end

function rc:make_timekeeper()
    local rc = self

    local tbl = {}
    tbl.prev_time = nil
    tbl.things = {}
    function tbl:add(thing)
        table.insert(self.things, thing)
    end

    function tbl:step()
        local cur_time = rc:cur_time()
        if self.prev_time == nil then
            self.prev_time = cur_time
        end

        local dt = cur_time - self.prev_time
        for _, thing in ipairs(self.things) do
            thing:step(dt)
        end
        self.prev_time = cur_time
    end

    return tbl
end

return rc


text:
using System.Collections.Generic;

namespace Abc.NCrafts.Quizz.Questions._004
{
    [CorrectAnswer(Difficulty = Difficulty.Easy)]
    public class Answer2
    {
        public static void Run()
        {
            var values = new List<int>(10);

            // begin
            for (var i = 0; i < 10; i++)
            {
                values.Add(42);
            }
            // end

            Logger.Log("Values: {0}", values);
        }
    }
}


text:
package statsd

import (
	"bytes"
	"fmt"
)

// MetricType is an enumeration of all the possible types of Metric
type MetricType float64

const (
	_                = iota
	ERROR MetricType = 1 << (10 * iota)
	COUNTER
	TIMER
	GAUGE
)

func (m MetricType) String() string {
	switch {
	case m >= GAUGE:
		return "gauge"
	case m >= TIMER:
		return "timer"
	case m >= COUNTER:
		return "counter"
	}
	return "unknown"
}

// Metric represents a single data collected datapoint
type Metric struct {
	Type   MetricType // The type of metric
	Bucket string     // The name of the bucket where the metric belongs
	Value  float64    // The numeric value of the metric
}

func (m Metric) String() string {
	return fmt.Sprintf("{%s, %s, %f}", m.Type, m.Bucket, m.Value)
}

// MetricMap is used for storing aggregated Metric values.
// The keys of the map are metric bucket names.
type MetricMap map[string]float64

func (m MetricMap) String() string {
	buf := new(bytes.Buffer)
	for k, v := range m {
		fmt.Fprintf(buf, "%s: %f\n", k, v)
	}
	return buf.String()
}

// MetricListMap is simlar to MetricMap but instead of storing a single aggregated
// Metric value it stores a list of all collected values.
type MetricListMap map[string][]float64

func (m MetricListMap) String() string {
	buf := new(bytes.Buffer)
	for k, v := range m {
		buf.Write([]byte(fmt.Sprint(k)))
		for _, v2 := range v {
			fmt.Fprintf(buf, "\t%f\n", k, v2)
		}
	}
	return buf.String()
}


text:
package de.hsosnabrueck.iui.informatik.vma.hipsterbility.modules;

import android.util.Log;
import de.hsosnabrueck.iui.informatik.vma.hipsterbility.Hipsterbility;
import de.hsosnabrueck.iui.informatik.vma.hipsterbility.helper.Util;
import de.hsosnabrueck.iui.informatik.vma.hipsterbility.modules.screencapture.ScreenshotModule;
import de.hsosnabrueck.iui.informatik.vma.hipsterbility.modules.screencapture.ScreenshotModuleRoot;

import java.util.ArrayList;

/**
 * Created on 05.03.14.
 */
public class CaptureModuleFactory {

    private static final String TAG = CameraCaptureModule.class.getName();
    private static boolean rootAvailable = Util.isDeviceRooted();
    private static boolean rootEnabled = Hipsterbility.getInstance().isRootFeaturesEnabled();

    private static CaptureModule getCameraCaptureModule(boolean audio) {
        Log.d(TAG, "Creating camera capture module, audio: " + audio);
        CameraCaptureModule capture = CameraCaptureModule.getInstance();
        capture.setAudioEnabled(audio);
        return capture;
    }

    private static CaptureModule getScreenCaptureModule() {
        if (rootAvailable && rootEnabled) {
            Log.d(TAG, "Creating screenshot root capture module");
            return ScreenshotModuleRoot.getInstance();
        } else {
            Log.d(TAG, "Creating screenshot capture module");
            return ScreenshotModule.getInstance();
        }
    }

    public static ArrayList<CaptureModule> getCaptureModules() {
        boolean screen = Hipsterbility.MODULE.SCREEN.enabled, audio = Hipsterbility.MODULE.AUDIO.enabled, lifecycle = Hipsterbility.MODULE.LIFECYCLE.enabled, video = Hipsterbility.MODULE.VIDEO.enabled, touch = Hipsterbility.MODULE.TOUCH.enabled;
        ArrayList<CaptureModule> captureModules = new ArrayList<CaptureModule>();
        Log.d(TAG, "screen: " + Hipsterbility.MODULE.SCREEN.enabled);
        Log.d(TAG, "audio: " + audio);
        Log.d(TAG, "lifecycle: " + lifecycle);
        Log.d(TAG, "video: " + video);
        Log.d(TAG, "touch: " + touch);

//            Camera related modules
        if (video && audio) {
            captureModules.add(getCameraCaptureModule(true));
        } else if (video) {
            captureModules.add(getCameraCaptureModule(false));
        } else if (audio) {
            Log.d(TAG, "Creating audio capture module");
            captureModules.add(AudioCaptureModule.getInstance());
        }
//            Other modules
        if (screen) {
            captureModules.add(getScreenCaptureModule());
        }
        if (touch) {
            Log.d(TAG, "Creating touch capture module");
            captureModules.add(TouchCaptureModule.getInstance());
        }
        if (lifecycle) {
            Log.d(TAG, "Creating lifecycle capture module");
            captureModules.add(LifecycleCaptureModule.getInstance());
        }
        return captureModules;
    }

}


text:
public class AirBender : Bender
{
    private double aerialIntegrity;

    public AirBender(string name, int power, double aerialIntegrity)
        : base(name, power)
    {
        this.aerialIntegrity = aerialIntegrity;

    }

    public override double GetPower()
    {
        return base.Power * aerialIntegrity;
    }

    public override string ToString()
    {
        return $"{base.ToString()} Aerial Integrity: {aerialIntegrity:f2}";
    }
}


text:
import React, { Component, PropTypes } from 'react'
import Command from '../Shared/Command'
import Colors from '../Theme/Colors'
import { clone, map, addIndex, tail, merge, last } from 'ramda'
import { isNilOrEmpty } from 'ramdasauce'
import AppStyles from '../Theme/AppStyles'
import ReactTooltip from 'react-tooltip'

const COMMAND_TITLE = 'BENCHMARK'
const LAST_STEP_DEFAULT = 'Last'
const MS_LABEL = 'ms'

const mapIndexed = addIndex(map)

const graphUsed = Colors.backgroundLighter
const graphEmpty = Colors.background

function percentStyle (start, length, total) {
  const p1 = Number((start / total * 100).toFixed(0))
  const p2 = Number((length / total * 100).toFixed(0)) + p1
  const p3 = 100 - p2 - p1

  const stop1 = `${graphEmpty} 0%`
  const stop2 = `${graphEmpty} ${p1}%`
  const stop3 = `${graphUsed} 0%`
  const stop4 = `${graphUsed} ${p2}%`
  const stop5 = `${graphEmpty} 0%`
  const stop6 = `${graphEmpty} ${p3}%`

  return {'background': `-webkit-linear-gradient(left, ${stop1}, ${stop2}, ${stop3}, ${stop4}, ${stop5}, ${stop6})`}
}

const Styles = {
  step: {
    position: 'relative',
    margin: '2px 0',
    ...AppStyles.Layout.hbox,
    padding: '4px 4px',
    justifyContent: 'space-between',
    WebkitUserSelect: 'all'
  },
  stepLast: {
    paddingTop: 4
  },
  reportTitle: {
    wordBreak: 'break-all',
    paddingBottom: 10,
    color: Colors.bold
  },
  stepNumber: {
    paddingRight: 10
  },
  stepTitle: {
    flex: 1,
    wordBreak: 'break-all'
  },
  delta: {
    textAlign: 'right',
    width: 100
  },
  elapsed: {
    width: 75,
    textAlign: 'right'
  }
}

const makeStep = (step, idx, last, totalDuration) => {
  const { time, title, delta } = step
  const pct = Number(delta / totalDuration * 100.0).toFixed(0)
  const startedAt = Number(time - delta).toFixed(0)
  const endedAt = Number(time).toFixed(0)
  const timeText = `${startedAt} - ${endedAt} ${{MS_LABEL}} (${pct}%)`
  const key = `step-${idx}`
  const titleText = (last && isNilOrEmpty(title)) ? LAST_STEP_DEFAULT : title
  const pStyle = percentStyle(step.time - step.delta, step.delta, totalDuration)
  const stepStyle = merge(merge(Styles.step, last && Styles.stepLast), pStyle)
  return (

{titleText}

{delta}{MS_LABEL}

  )
}

class BenchmarkReportCommand extends Component {
  static propTypes = {
    command: PropTypes.object.isRequired
  }

  shouldComponentUpdate (nextProps) {
    return this.props.command.id !== nextProps.command.id
  }

  componentDidReact () {
    ReactTooltip.rebuild()
  }

  render () {
    const { command } = this.props
    const { payload } = command
    const { title, steps } = clone(payload)
    const duration = last(steps).time
    const preview = `${title} in ${duration}ms`

    return (
      <Command command={command} title={COMMAND_TITLE} duration={duration} preview={preview}>

{title}

        {
          mapIndexed(
            (step, idx) => makeStep(step, idx, idx === steps.length - 2, duration),
            tail(steps))
        }
      </Command>
    )
  }
}

export default BenchmarkReportCommand


text:
ActiveRecord::Schema.define(version: 20170821191820) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "cards", force: :cascade do |t|
    t.string "name"
    t.integer "multiverse_id"
    t.string "layout"
    t.string "mana_cost"
    t.integer "cmc"
    t.string "rarity"
    t.string "text"
    t.string "flavor"
    t.string "artist"
    t.integer "number"
    t.string "power"
    t.string "toughness"
    t.integer "loyalty"
    t.string "variations"
    t.string "watermark"
    t.string "border"
    t.string "timeshifted"
    t.string "hand"
    t.integer "life"
    t.string "reserved"
    t.string "release_date"
    t.string "starter"
    t.string "original_text"
    t.string "original_type"
    t.string "source"
    t.string "image_url"
    t.string "set"
    t.string "set_name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "cards_colors", id: false, force: :cascade do |t|
    t.bigint "card_id", null: false
    t.bigint "color_id", null: false
  end

  create_table "cards_legalities", id: false, force: :cascade do |t|
    t.bigint "card_id", null: false
    t.bigint "legality_id", null: false
  end

  create_table "cards_printings", id: false, force: :cascade do |t|
    t.bigint "card_id", null: false
    t.bigint "printing_id", null: false
  end

  create_table "cards_subtypes", id: false, force: :cascade do |t|
    t.bigint "card_id", null: false
    t.bigint "subtype_id", null: false
  end

  create_table "cards_supertypes", id: false, force: :cascade do |t|
    t.bigint "card_id", null: false
    t.bigint "supertype_id", null: false
  end

  create_table "cards_types", id: false, force: :cascade do |t|
    t.bigint "card_id", null: false
    t.bigint "type_id", null: false
  end

  create_table "colors", force: :cascade do |t|
    t.string "color"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "deck_archives", force: :cascade do |t|
    t.bigint "deck_id"
    t.bigint "card_id"
    t.integer "main_count"
    t.integer "sideboard_count"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["card_id"], name: "index_deck_archives_on_card_id"
    t.index ["deck_id"], name: "index_deck_archives_on_deck_id"
  end

  create_table "decks", force: :cascade do |t|
    t.string "owner"
    t.string "name"
    t.string "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "foreign_names", force: :cascade do |t|
    t.string "name"
    t.string "language"
    t.integer "multiverse_id"
    t.integer "card_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "legalities", force: :cascade do |t|
    t.string "legality"
    t.string "format"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "printings", force: :cascade do |t|
    t.string "set"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "rulings", force: :cascade do |t|
    t.date "date"
    t.string "text"
    t.integer "card_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "subtypes", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "supertypes", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "types", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end


text:
/*
 * $Id: XMLElementDecl.java,v 1.3 2007-07-19 22:33:13 ofung Exp $
 */

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License. You can obtain
 * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
 * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 *
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 * Sun designates this particular file as subject to the "Classpath" exception
 * as provided by Sun in the GPL Version 2 section of the License file that
 * accompanied this code.  If applicable, add the following below the License
 * Header, with the fields enclosed by brackets [] replaced by your own
 * identifying information: "Portions Copyrighted [year]
 * [name of copyright owner]"
 *
 * Contributor(s):
 *
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */

/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.apache.org.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.sun.xml.stream.dtd.nonvalidating;

import com.sun.xml.stream.xerces.xni.QName;
/**
 * @version $Id: XMLElementDecl.java,v 1.3 2007-07-19 22:33:13 ofung Exp $
 */
public class XMLElementDecl {

    /** TYPE_ANY */
    public static final short TYPE_ANY = 0;

    /** TYPE_EMPTY */
    public static final short TYPE_EMPTY = 1;

    /** TYPE_MIXED */
    public static final short TYPE_MIXED = 2;

    /** TYPE_CHILDREN */
    public static final short TYPE_CHILDREN = 3;

    /** TYPE_SIMPLE */
    public static final short TYPE_SIMPLE = 4;

    /** name */
    public final QName name = new QName();

    /** scope */
    public int scope = -1;

    /** type */
    public short type = -1;

    /** simpleType */
    public final XMLSimpleType simpleType = new XMLSimpleType();

    /**
     * setValues
     *
     * @param name
     * @param scope
     * @param type
     * @param contentModelValidator
     * @param simpleType
     */
    public void setValues(QName name, int scope, short type, XMLSimpleType simpleType) {
        this.name.setValues(name);
        this.scope                 = scope;
        this.type                  = type;
        this.simpleType.setValues(simpleType);
    } // setValues

    /**
     * clear
     */
    public void clear() {
        this.name.clear();
        this.type          = -1;
        this.scope         = -1;
        this.simpleType.clear();
    } // clear

} // class XMLElementDecl


text:
<resources>
    <string name="app_name">weekcalendar</string>
</resources>


text:
package ninja.bodyparser;

import ninja.params.ExtendParamParsers;

import javax.inject.Inject;
import javax.inject.Singleton;

@Singleton
public class ExtendBodyParserEngineTextPlain extends AbstractBodyParserEngine {

    @Inject
    public ExtendBodyParserEngineTextPlain(ExtendParamParsers paramParsers) {
        super(paramParsers);
    }

    @Override
    public String getContentType() {
        return "text/plain";
    }
}