text:
/*************************************************************************/
/*  project_manager.cpp                                                  */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include "version.h"
#include "project_manager.h"
#include "os/os.h"
#include "os/dir_access.h"
#include "os/file_access.h"
#include "editor_settings.h"
#include "scene/gui/separator.h"
#include "scene/gui/tool_button.h"
#include "io/config_file.h"

#include "scene/gui/line_edit.h"
#include "scene/gui/panel_container.h"

#include "scene/gui/texture_frame.h"
#include "scene/gui/margin_container.h"
#include "io/resource_saver.h"

#include "editor_icons.h"

class NewProjectDialog : public ConfirmationDialog {

	OBJ_TYPE(NewProjectDialog,ConfirmationDialog);

	bool import_mode;
	Label *pp,*pn;
	Label *error;
	LineEdit *project_path;
	LineEdit *project_name;
	FileDialog *fdialog;

	bool _test_path() {

		error->set_text("");
		get_ok()->set_disabled(true);
		DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
		if (project_path->get_text() != "" && d->change_dir(project_path->get_text())!=OK) {
			error->set_text("Invalid Path for Project, Path Must Exist!");
			memdelete(d);
			return false;
		}

		if (!import_mode) {

			if (d->file_exists("engine.cfg")) {

				error->set_text("Invalid Project Path (engine.cfg must not exist).");
				memdelete(d);
				return false;
			}

		} else {

			if (project_path->get_text() != "" && !d->file_exists("engine.cfg")) {

				error->set_text("Invalid Project Path (engine.cfg must exist).");
				memdelete(d);
				return false;
			}
		}

		memdelete(d);
		get_ok()->set_disabled(false);
		return true;

	}

	void _path_text_changed(const String& p_path) {

		if ( _test_path() ) {

			String sp=p_path;

			sp=sp.replace("\\","/");
			int lidx=sp.find_last("/");

			if (lidx!=-1) {
				sp=sp.substr(lidx+1,sp.length());
			}
			if (sp=="" && import_mode )
				sp="Imported Project";

			project_name->set_text(sp);
		}
	}

	void _file_selected(const String& p_path) {

		String p = p_path;
		if (import_mode) {
			if (p.ends_with("engine.cfg")) {

				p=p.get_base_dir();
			}
		}
		String sp = p.simplify_path();
		project_path->set_text(sp);
		_path_text_changed(p);
	}

	void _path_selected(const String& p_path) {

		String p = p_path;
		String sp = p.simplify_path();
		project_path->set_text(sp);
		_path_text_changed(p);

	}

	void _browse_path() {

		if (import_mode) {

			fdialog->set_mode(FileDialog::MODE_OPEN_FILE);
			fdialog->clear_filters();
			fdialog->add_filter("engine.cfg ; " _MKSTR(VERSION_NAME) " Project");
		} else {
			fdialog->set_mode(FileDialog::MODE_OPEN_DIR);
		}
		fdialog->popup_centered_ratio();
	}

	void _text_changed(const String& p_text) {
		_test_path();
	}

	void ok_pressed() {

		if (!_test_path())
			return;

		String dir;

		if (import_mode) {
			dir=project_path->get_text();

		} else {
			DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);

			if (d->change_dir(project_path->get_text())!=OK) {
				error->set_text("Invalid Path for Project (changed anything?)");
				memdelete(d);
				return;
			}

			dir=d->get_current_dir();
			memdelete(d);

			FileAccess *f = FileAccess::open(dir.plus_file("/engine.cfg"),FileAccess::WRITE);
			if (!f) {
				error->set_text("Couldn't create engine.cfg in project path");
			} else {

				f->store_line("; Engine configuration file.");
				f->store_line("; It's best to edit using the editor UI, not directly,");
				f->store_line("; becausethe parameters that go here are not obvious.");
				f->store_line("; ");
				f->store_line("; Format: ");
				f->store_line(";   [section] ; section goes between []");
				f->store_line(";   param=value ; assign values to parameters");
				f->store_line("\n");
				f->store_line("[application]");
				f->store_line("name=\""+project_name->get_text()+"\"");
				f->store_line("icon=\"res://icon.png\"");

				memdelete(f);

				ResourceSaver::save(dir.plus_file("/icon.png"),get_icon("DefaultProjectIcon","EditorIcons"));
			}

		}

		dir=dir.replace("\\","/");
		if (dir.ends_with("/"))
			dir=dir.substr(0,dir.length()-1);
		String proj=dir.replace("/","::");
		EditorSettings::get_singleton()->set("projects/"+proj,dir);
		EditorSettings::get_singleton()->save();

		hide();
		emit_signal("project_created");

	}

protected:

	static void _bind_methods() {

		ObjectTypeDB::bind_method("_browse_path",&NewProjectDialog::_browse_path);
		ObjectTypeDB::bind_method("_text_changed",&NewProjectDialog::_text_changed);
		ObjectTypeDB::bind_method("_path_text_changed",&NewProjectDialog::_path_text_changed);
		ObjectTypeDB::bind_method("_path_selected",&NewProjectDialog::_path_selected);
		ObjectTypeDB::bind_method("_file_selected",&NewProjectDialog::_file_selected);
		ADD_SIGNAL( MethodInfo("project_created") );
	}

public:

	void set_import_mode(bool p_import ) {

		import_mode=p_import;
	}

	void show_dialog() {

		project_path->clear();
		project_name->clear();

		if (import_mode) {
			set_title("Import Existing Project");
			get_ok()->set_text("Import");
			pp->set_text("Project Path: (Must exist)");
			pn->set_text("Project Name:");
			pn->hide();
			project_name->hide();

			popup_centered(Size2(500,125));

		} else {
			set_title("Create New Project");
			get_ok()->set_text("Create");
			pp->set_text("Project Path:");
			pn->set_text("Project Name:");
			pn->show();
			project_name->show();

			popup_centered(Size2(500,145));

		}

		_test_path();
	}

	NewProjectDialog() {

		VBoxContainer *vb = memnew( VBoxContainer );
		add_child(vb);
		set_child_rect(vb);

		Label* l = memnew(Label);
		l->set_text("Project Path:");
		vb->add_child(l);
		pp=l;

		project_path = memnew( LineEdit );
		MarginContainer *mc = memnew( MarginContainer );
		vb->add_child(mc);
		HBoxContainer *pphb = memnew( HBoxContainer );
		mc->add_child(pphb);
		pphb->add_child(project_path);
		project_path->set_h_size_flags(SIZE_EXPAND_FILL);

		Button* browse = memnew( Button );
		pphb->add_child(browse);
		browse->set_text("Browse");
		browse->connect("pressed", this,"_browse_path");

		l = memnew(Label);
		l->set_text("Project Name:");
		l->set_pos(Point2(5,50));
		vb->add_child(l);
		pn=l;

		project_name = memnew( LineEdit );
		mc = memnew( MarginContainer );
		vb->add_child(mc);
		mc->add_child(project_name);
		project_name->set_text("New Game Project");

		l = memnew(Label);
		l->set_text("That's a BINGO!");
		vb->add_child(l);
		error=l;
		l->add_color_override("font_color",Color(1,0.4,0.3,0.8));
		l->set_align(Label::ALIGN_CENTER);

		DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
		project_path->set_text(d->get_current_dir());
		memdelete(d);

		fdialog = memnew( FileDialog );
		add_child(fdialog);
		fdialog->set_access(FileDialog::ACCESS_FILESYSTEM);
		fdialog->set_current_dir( EditorSettings::get_singleton()->get("global/default_project_path") );
		project_name->connect("text_changed", this,"_text_changed");
		project_path->connect("text_changed", this,"_path_text_changed");
		fdialog->connect("dir_selected", this,"_path_selected");
		fdialog->connect("file_selected", this,"_file_selected");
		set_hide_on_ok(false);
		import_mode=false;
	}

};

struct ProjectItem {
	String project;
	String path;
	String conf;
	uint64_t last_modified;
	bool favorite;
	ProjectItem() {}
	ProjectItem(const String &p_project, const String &p_path, const String &p_conf, uint64_t p_last_modified, bool p_favorite=false) {
		project = p_project; path = p_path; conf = p_conf; last_modified = p_last_modified; favorite=p_favorite;
	}
	_FORCE_INLINE_ bool operator <(const ProjectItem& l) const { return last_modified > l.last_modified; }
	_FORCE_INLINE_ bool operator ==(const ProjectItem& l) const { return project==l.project; }
};

void ProjectManager::_notification(int p_what) {

	if (p_what==NOTIFICATION_ENTER_TREE) {

		get_tree()->set_editor_hint(true);
	}
}

void ProjectManager::_panel_draw(Node *p_hb) {

	HBoxContainer *hb = p_hb->cast_to<HBoxContainer>();

	hb->draw_line(Point2(0,hb->get_size().y+1),Point2(hb->get_size().x-10,hb->get_size().y+1),get_color("guide_color","Tree"));

	if (selected_list.has(hb->get_meta("name"))) {
		hb->draw_style_box(get_stylebox("selected","Tree"),Rect2(Point2(),hb->get_size()-Size2(10,0)));
	}
}

void ProjectManager::_panel_input(const InputEvent& p_ev,Node *p_hb) {

	if (p_ev.type==InputEvent::MOUSE_BUTTON && p_ev.mouse_button.pressed && p_ev.mouse_button.button_index==BUTTON_LEFT) {

		String clicked = p_hb->get_meta("name");
		String clicked_main_scene = p_hb->get_meta("main_scene");

		if (p_ev.key.mod.shift && selected_list.size()>0 && last_clicked!="" && clicked != last_clicked) {

			int clicked_id = -1;
			int last_clicked_id = -1;
			for(int i=0;i<scroll_childs->get_child_count();i++) {
				HBoxContainer *hb = scroll_childs->get_child(i)->cast_to<HBoxContainer>();
				if (!hb) continue;
				if (hb->get_meta("name") == clicked) clicked_id = i;
				if (hb->get_meta("name") == last_clicked) last_clicked_id = i;
			}

			if (last_clicked_id!=-1 && clicked_id!=-1) {
				int min = clicked_id < last_clicked_id? clicked_id : last_clicked_id;
				int max = clicked_id > last_clicked_id? clicked_id : last_clicked_id;
				for(int i=0; i<scroll_childs->get_child_count(); ++i) {
					HBoxContainer *hb = scroll_childs->get_child(i)->cast_to<HBoxContainer>();
					if (!hb) continue;
					if (i!=clicked_id && (i<min || i>max) && !p_ev.key.mod.control) {
						selected_list.erase(hb->get_meta("name"));
					} else if (i>=min && i<=max) {
						selected_list.insert(hb->get_meta("name"), hb->get_meta("main_scene"));
					}
				}
			}

		} else if (selected_list.has(clicked) && p_ev.key.mod.control) {

			selected_list.erase(clicked);

		} else {

			last_clicked = clicked;
			if (p_ev.key.mod.control || selected_list.size()==0) {
				selected_list.insert(clicked, clicked_main_scene);
			} else {
				selected_list.clear();
				selected_list.insert(clicked, clicked_main_scene);
			}
		}

		String single_selected = "";
		if (selected_list.size() == 1) {
			single_selected = selected_list.front()->key();
		}

		single_selected_main = "";
		for(int i=0;i<scroll_childs->get_child_count();i++) {
			CanvasItem *item = scroll_childs->get_child(i)->cast_to<CanvasItem>();
			item->update();

			if (single_selected!="" && single_selected == item->get_meta("name"))
				single_selected_main = item->get_meta("main_scene");
		}

		erase_btn->set_disabled(selected_list.size()<1);
		open_btn->set_disabled(selected_list.size()<1);
		run_btn->set_disabled(selected_list.size()<1 || (selected_list.size()==1 && single_selected_main==""));

		if (p_ev.mouse_button.doubleclick)
			_open_project(); //open if doubleclicked

	}
}

void ProjectManager::_favorite_pressed(Node *p_hb) {

	String clicked = p_hb->get_meta("name");
	bool favorite = !p_hb->get_meta("favorite");
	String proj=clicked.replace(":::",":/");
	proj=proj.replace("::","/");

	if (favorite) {
		EditorSettings::get_singleton()->set("favorite_projects/"+clicked,proj);
	} else {
		EditorSettings::get_singleton()->erase("favorite_projects/"+clicked);
	}
	EditorSettings::get_singleton()->save();
	call_deferred("_load_recent_projects");
}

void ProjectManager::_load_recent_projects() {

	ProjectListFilter::FilterOption filter_option = project_filter->get_filter_option();
	String search_term = project_filter->get_search_term();

	while(scroll_childs->get_child_count()>0) {
		memdelete( scroll_childs->get_child(0));
	}

	List<PropertyInfo> properties;
	EditorSettings::get_singleton()->get_property_list(&properties);

	Color font_color = get_color("font_color","Tree");

	List<ProjectItem> projects;
	List<ProjectItem> favorite_projects;

	for(List<PropertyInfo>::Element *E=properties.front();E;E=E->next()) {

		String _name = E->get().name;
		if (!_name.begins_with("projects/") && !_name.begins_with("favorite_projects/"))
			continue;

		String path = EditorSettings::get_singleton()->get(_name);
		if (filter_option == ProjectListFilter::FILTER_PATH && search_term!="" && path.findn(search_term)==-1)
			continue;

		String project = _name.get_slice("/",1);
		String conf=path.plus_file("engine.cfg");
		bool favorite = (_name.begins_with("favorite_projects/"))?true:false;

		uint64_t last_modified = 0;
		if (FileAccess::exists(conf)) {
			last_modified = FileAccess::get_modified_time(conf);

			String fscache = path.plus_file(".fscache");
			if (FileAccess::exists(fscache)) {
				uint64_t cache_modified = FileAccess::get_modified_time(fscache);
				if ( cache_modified > last_modified )
					last_modified = cache_modified;
			}

			ProjectItem item(project, path, conf, last_modified, favorite);
			if (favorite)
				favorite_projects.push_back(item);
			else
				projects.push_back(item);
		} else {
			//project doesn't exist on disk but it's in the XML settings file
			EditorSettings::get_singleton()->erase(_name); //remove it
		}
	}

	projects.sort();
	favorite_projects.sort();

	for(List<ProjectItem>::Element *E=projects.front();E;) {
		List<ProjectItem>::Element *next = E->next();
		if (favorite_projects.find(E->get()) != NULL)
			projects.erase(E->get());
		E=next;
	}
	for(List<ProjectItem>::Element *E=favorite_projects.back();E;E=E->prev()) {
		projects.push_front(E->get());
	}

	Ref<Texture> favorite_icon = get_icon("Favorites","EditorIcons");

	for(List<ProjectItem>::Element *E=projects.front();E;E=E->next()) {

		ProjectItem &item = E->get();
		String project = item.project;
		String path = item.path;
		String conf = item.conf;
		bool is_favorite = item.favorite;

		Ref<ConfigFile> cf = memnew( ConfigFile );
		Error err = cf->load(conf);
		ERR_CONTINUE(err!=OK);

		String project_name="Unnamed Project";

		if (cf->has_section_key("application","name")) {
			project_name = cf->get_value("application","name");
		}

		if (filter_option==ProjectListFilter::FILTER_NAME && search_term!="" && project_name.findn(search_term)==-1)
			continue;

		Ref<Texture> icon;
		if (cf->has_section_key("application","icon")) {
			String appicon = cf->get_value("application","icon");
			if (appicon!="") {
				Image img;
				Error err = img.load(appicon.replace_first("res://",path+"/"));
				if (err==OK) {

					img.resize(64,64);
					Ref<ImageTexture> it = memnew( ImageTexture );
					it->create_from_image(img);
					icon=it;
				}
			}
		}

		if (icon.is_null()) {
			icon=get_icon("DefaultProjectIcon","EditorIcons");
		}

		String main_scene;
		if (cf->has_section_key("application","main_scene")) {
			main_scene = cf->get_value("application","main_scene");
		}

		HBoxContainer *hb = memnew( HBoxContainer );
		hb->set_meta("name",project);
		hb->set_meta("main_scene",main_scene);
		hb->set_meta("favorite",is_favorite);
		hb->connect("draw",this,"_panel_draw",varray(hb));
		hb->connect("input_event",this,"_panel_input",varray(hb));

		VBoxContainer *favorite_box = memnew( VBoxContainer );
		TextureButton *favorite = memnew( TextureButton );
		favorite->set_normal_texture(favorite_icon);
		if (!is_favorite)
			favorite->set_opacity(0.2);
		favorite->set_v_size_flags(SIZE_EXPAND);
		favorite->connect("pressed",this,"_favorite_pressed",varray(hb));
		favorite_box->add_child(favorite);
		hb->add_child(favorite_box);

		TextureFrame *tf = memnew( TextureFrame );
		tf->set_texture(icon);
		hb->add_child(tf);

		VBoxContainer *vb = memnew(VBoxContainer);
		hb->add_child(vb);
		Control *ec = memnew( Control );
		ec->set_custom_minimum_size(Size2(0,1));
		vb->add_child(ec);
		Label *title = memnew( Label(project_name) );
		title->add_font_override("font",get_font("large","Fonts"));
		title->add_color_override("font_color",font_color);
		vb->add_child(title);
		Label *fpath = memnew( Label(path) );
		vb->add_child(fpath);
		fpath->set_opacity(0.5);
		fpath->add_color_override("font_color",font_color);

		scroll_childs->add_child(hb);
	}

	scroll->set_v_scroll(0);

	erase_btn->set_disabled(selected_list.size()<1);
	open_btn->set_disabled(selected_list.size()<1);
	run_btn->set_disabled(selected_list.size()<1 || (selected_list.size()==1 && single_selected_main==""));

	EditorSettings::get_singleton()->save();
}

void ProjectManager::_open_project_confirm() {

	for (Map<String,String>::Element *E=selected_list.front(); E; E=E->next()) {
		const String &selected = E->key();
		String path = EditorSettings::get_singleton()->get("projects/"+selected);
		print_line("OPENING: "+path+" ("+selected+")");

		List<String> args;

		args.push_back("-path");
		args.push_back(path);

		args.push_back("-editor");

		String exec = OS::get_singleton()->get_executable_path();

		OS::ProcessID pid=0;
		Error err = OS::get_singleton()->execute(exec,args,false,&pid);
		ERR_FAIL_COND(err);
	}

	get_tree()->quit();
}

void ProjectManager::_open_project() {

	if (selected_list.size()<1) {
		return;
	}

	if (selected_list.size()>1) {
		multi_open_ask->set_text("Are you sure to open more than one projects?");
		multi_open_ask->popup_centered_minsize();
	} else {
		_open_project_confirm();
	}
}

void ProjectManager::_run_project_confirm() {

	for (Map<String,String>::Element *E=selected_list.front(); E; E=E->next()) {

		const String &selected_main = E->get();
		if (selected_main == "") continue;

		const String &selected = E->key();
		String path = EditorSettings::get_singleton()->get("projects/"+selected);
		print_line("OPENING: "+path+" ("+selected+")");

		List<String> args;

		args.push_back("-path");
		args.push_back(path);

		String exec = OS::get_singleton()->get_executable_path();

		OS::ProcessID pid=0;
		Error err = OS::get_singleton()->execute(exec,args,false,&pid);
		ERR_FAIL_COND(err);
	}
	//	get_scene()->quit(); do not quit
}

void ProjectManager::_run_project() {

	if (selected_list.size()<1) {
		return;
	}

	if (selected_list.size()>1) {
		multi_run_ask->set_text("Are you sure to run more than one projects?");
		multi_run_ask->popup_centered_minsize();
	} else {
		_run_project_confirm();
	}
}

void ProjectManager::_scan_dir(DirAccess *da,float pos, float total,List<String> *r_projects) {

	List<String> subdirs;
	da->list_dir_begin();
	String n = da->get_next();
	while(n!=String()) {
		if (da->current_is_dir() && !n.begins_with(".")) {
			subdirs.push_front(n);
		} else if (n=="engine.cfg") {
			r_projects->push_back(da->get_current_dir());
		}
		n=da->get_next();
	}
	da->list_dir_end();
	int m=0;
	for(List<String>::Element *E=subdirs.front();E;E=E->next()) {

		da->change_dir(E->get());

		float slice=total/subdirs.size();
		_scan_dir(da,pos+slice*m,slice,r_projects);
		da->change_dir("..");
		m++;
	}

}

void ProjectManager::_scan_begin(const String& p_base) {

	print_line("SCAN PROJECTS AT: "+p_base);
	List<String> projects;
	DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	da->change_dir(p_base);
	_scan_dir(da,0,1,&projects);
	memdelete(da);
	print_line("found: "+itos(projects.size())+" projects.");

	for(List<String>::Element *E=projects.front();E;E=E->next()) {
		String proj=E->get().replace("/","::");
		EditorSettings::get_singleton()->set("projects/"+proj,E->get());

	}
	EditorSettings::get_singleton()->save();
	_load_recent_projects();

}

void ProjectManager::_scan_projects() {

	scan_dir->popup_centered_ratio();

}

void ProjectManager::_new_project()  {

	npdialog->set_import_mode(false);
	npdialog->show_dialog();
}

void ProjectManager::_import_project()  {

	npdialog->set_import_mode(true);
	npdialog->show_dialog();
}

void ProjectManager::_erase_project_confirm()  {

	if (selected_list.size()==0) {
		return;
	}
	for (Map<String,String>::Element *E=selected_list.front(); E; E=E->next()) {
		EditorSettings::get_singleton()->erase("projects/"+E->key());
		EditorSettings::get_singleton()->erase("favorite_projects/"+E->key());
	}
	EditorSettings::get_singleton()->save();
	selected_list.clear();
	last_clicked = "";
	single_selected_main="";
	_load_recent_projects();

}

void ProjectManager::_erase_project()  {

	if (selected_list.size()==0)
		return;

	erase_ask->set_text("Erase project from list?? (Folder contents will not be modified)");
	erase_ask->popup_centered_minsize();

}

void ProjectManager::_exit_dialog()  {

	get_tree()->quit();
}

void ProjectManager::_bind_methods() {

	ObjectTypeDB::bind_method("_open_project",&ProjectManager::_open_project);
	ObjectTypeDB::bind_method("_open_project_confirm",&ProjectManager::_open_project_confirm);
	ObjectTypeDB::bind_method("_run_project",&ProjectManager::_run_project);
	ObjectTypeDB::bind_method("_run_project_confirm",&ProjectManager::_run_project_confirm);
	ObjectTypeDB::bind_method("_scan_projects",&ProjectManager::_scan_projects);
	ObjectTypeDB::bind_method("_scan_begin",&ProjectManager::_scan_begin);
	ObjectTypeDB::bind_method("_import_project",&ProjectManager::_import_project);
	ObjectTypeDB::bind_method("_new_project",&ProjectManager::_new_project);
	ObjectTypeDB::bind_method("_erase_project",&ProjectManager::_erase_project);
	ObjectTypeDB::bind_method("_erase_project_confirm",&ProjectManager::_erase_project_confirm);
	ObjectTypeDB::bind_method("_exit_dialog",&ProjectManager::_exit_dialog);
	ObjectTypeDB::bind_method("_load_recent_projects",&ProjectManager::_load_recent_projects);
	ObjectTypeDB::bind_method("_panel_draw",&ProjectManager::_panel_draw);
	ObjectTypeDB::bind_method("_panel_input",&ProjectManager::_panel_input);
	ObjectTypeDB::bind_method("_favorite_pressed",&ProjectManager::_favorite_pressed);

}

ProjectManager::ProjectManager() {

	int margin = get_constant("margin","Dialogs");
	int button_margin = get_constant("button_margin","Dialogs");

	// load settings
	if (!EditorSettings::get_singleton())
		EditorSettings::create();

	FileDialog::set_default_show_hidden_files(EditorSettings::get_singleton()->get("file_dialog/show_hidden_files"));

	set_area_as_parent_rect();

	Ref<Theme> theme = Ref<Theme>( memnew( Theme ) );
	set_theme(theme);
	editor_register_icons(theme);

	String global_font = EditorSettings::get_singleton()->get("global/font");
	if (global_font!="") {
		Ref<Font> fnt = ResourceLoader::load(global_font);
		if (fnt.is_valid()) {
			theme->set_default_theme_font(fnt);
		}
	}

	Panel *panel = memnew( Panel );
	add_child(panel);
	panel->set_area_as_parent_rect();

	VBoxContainer *vb = memnew( VBoxContainer );
	panel->add_child(vb);
	vb->set_area_as_parent_rect(20);

	OS::get_singleton()->set_window_title(_MKSTR(VERSION_NAME)" - Project Manager");

	Label *l = memnew( Label );
	l->set_text(_MKSTR(VERSION_NAME)" - Project Manager");
	l->add_font_override("font",get_font("large","Fonts"));
	l->set_align(Label::ALIGN_CENTER);
	vb->add_child(l);
	l = memnew( Label );
	l->set_text("v" VERSION_MKSTRING);
	//l->add_font_override("font",get_font("bold","Fonts"));
	l->set_align(Label::ALIGN_CENTER);
	vb->add_child(l);
	vb->add_child(memnew(HSeparator));
	vb->add_margin_child("\n",memnew(Control));

	HBoxContainer *tree_hb = memnew( HBoxContainer);
	vb->add_margin_child("Recent Projects:",tree_hb,true);

	VBoxContainer *search_tree_vb = memnew(VBoxContainer);
	search_tree_vb->set_h_size_flags(SIZE_EXPAND_FILL);
	tree_hb->add_child(search_tree_vb);

	HBoxContainer *search_box = memnew(HBoxContainer);
	search_box->add_spacer(true);
	project_filter = memnew(ProjectListFilter);
	search_box->add_child(project_filter);
	project_filter->connect("filter_changed", this, "_load_recent_projects");
	project_filter->set_custom_minimum_size(Size2(250,10));
	search_tree_vb->add_child(search_box);

	PanelContainer *pc = memnew( PanelContainer);
	pc->add_style_override("panel",get_stylebox("bg","Tree"));
	search_tree_vb->add_child(pc);
	pc->set_v_size_flags(SIZE_EXPAND_FILL);

	scroll = memnew( ScrollContainer );
	pc->add_child(scroll);
	scroll->set_enable_h_scroll(false);

	VBoxContainer *tree_vb = memnew( VBoxContainer);
	tree_hb->add_child(tree_vb);
	scroll_childs = memnew( VBoxContainer );
	scroll_childs->set_h_size_flags(SIZE_EXPAND_FILL);
	scroll->add_child(scroll_childs);

	//HBoxContainer *hb = memnew( HBoxContainer );
	//vb->add_child(hb);

	Button *open = memnew( Button );
	open->set_text("Edit");
	tree_vb->add_child(open);
	open->connect("pressed", this,"_open_project");
	open_btn=open;

	Button *run = memnew( Button );
	run->set_text("Run");
	tree_vb->add_child(run);
	run->connect("pressed", this,"_run_project");
	run_btn=run;

	tree_vb->add_child(memnew( HSeparator ));

	Button *scan = memnew( Button );
	scan->set_text("Scan");
	tree_vb->add_child(scan);
	scan->connect("pressed", this,"_scan_projects");

	tree_vb->add_child(memnew( HSeparator ));

	scan_dir = memnew( FileDialog );
	scan_dir->set_access(FileDialog::ACCESS_FILESYSTEM);
	scan_dir->set_mode(FileDialog::MODE_OPEN_DIR);
	scan_dir->set_current_dir( EditorSettings::get_singleton()->get("global/default_project_path") );
	add_child(scan_dir);
	scan_dir->connect("dir_selected",this,"_scan_begin");

	Button* create = memnew( Button );
	create->set_text("New Project");
	tree_vb->add_child(create);
	create->connect("pressed", this,"_new_project");

	Button* import = memnew( Button );
	import->set_text("Import");
	tree_vb->add_child(import);
	import->connect("pressed", this,"_import_project");

	Button* erase = memnew( Button );
	erase->set_text("Erase");
	tree_vb->add_child(erase);
	erase->connect("pressed", this,"_erase_project");
	erase_btn=erase;

	tree_vb->add_spacer();

	Button * cancel = memnew( Button );
	cancel->set_text("Exit");
	tree_vb->add_child(cancel);
	cancel->connect("pressed", this,"_exit_dialog");

	vb->add_margin_child("\n",memnew(Control));
	vb->add_child(memnew(HSeparator));

	l = memnew( Label );
	String cp;
	cp.push_back(0xA9);
	cp.push_back(0);
	l->set_text(cp+" 2008-2015 Juan Linietsky, Ariel Manzur.");
	l->set_align(Label::ALIGN_CENTER);
	vb->add_child(l);

	erase_ask = memnew( ConfirmationDialog );
	erase_ask->get_ok()->set_text("Erase");
	erase_ask->get_ok()->connect("pressed", this,"_erase_project_confirm");

	add_child(erase_ask);

	multi_open_ask = memnew( ConfirmationDialog );
	multi_open_ask->get_ok()->set_text("Edit");
	multi_open_ask->get_ok()->connect("pressed", this, "_open_project_confirm");

	add_child(multi_open_ask);

	multi_run_ask = memnew( ConfirmationDialog );
	multi_run_ask->get_ok()->set_text("Run");
	multi_run_ask->get_ok()->connect("pressed", this, "_run_project_confirm");

	add_child(multi_run_ask);

	OS::get_singleton()->set_low_processor_usage_mode(true);

	npdialog = memnew( NewProjectDialog );
	add_child(npdialog);

	npdialog->connect("project_created", this,"_load_recent_projects");
	_load_recent_projects();

	if ( EditorSettings::get_singleton()->get("global/autoscan_project_path") ) {
		_scan_begin( EditorSettings::get_singleton()->get("global/autoscan_project_path") );
	}

	//get_ok()->set_text("Open");
	//get_ok()->set_text("Exit");

	last_clicked = "";
}

ProjectManager::~ProjectManager() {

	if (EditorSettings::get_singleton())
		EditorSettings::destroy();
}

void ProjectListFilter::_setup_filters() {

	filter_option->clear();
	filter_option->add_item("Name");
	filter_option->add_item("Path");
}

void ProjectListFilter::_command(int p_command) {
	switch (p_command) {

		case CMD_CLEAR_FILTER: {
			if (search_box->get_text()!="") {
				search_box->clear();
				emit_signal("filter_changed");
			}
		}break;
	}
}

void ProjectListFilter::_search_text_changed(const String &p_newtext) {
	emit_signal("filter_changed");
}

String ProjectListFilter::get_search_term() {
	return search_box->get_text().strip_edges();
}

ProjectListFilter::FilterOption ProjectListFilter::get_filter_option() {
	return _current_filter;
}

void ProjectListFilter::_filter_option_selected(int p_idx) {
	FilterOption selected = (FilterOption)(filter_option->get_selected());
	if (_current_filter != selected ) {
		_current_filter = selected;
		emit_signal("filter_changed");
	}
}

void ProjectListFilter::_notification(int p_what) {
	switch(p_what) {
		case NOTIFICATION_ENTER_TREE: {
			clear_search_button->set_icon(get_icon("CloseHover","EditorIcons"));
		} break;
	}
}

void ProjectListFilter::_bind_methods() {

	ObjectTypeDB::bind_method(_MD("_command"),&ProjectListFilter::_command);
	ObjectTypeDB::bind_method(_MD("_search_text_changed"), &ProjectListFilter::_search_text_changed);
	ObjectTypeDB::bind_method(_MD("_filter_option_selected"), &ProjectListFilter::_filter_option_selected);

	ADD_SIGNAL( MethodInfo("filter_changed") );
}

ProjectListFilter::ProjectListFilter() {

	_current_filter = FILTER_NAME;

	filter_option = memnew(OptionButton);
	filter_option->set_custom_minimum_size(Size2(80,10));
	filter_option->set_clip_text(true);
	filter_option->connect("item_selected", this, "_filter_option_selected");
	add_child(filter_option);

	_setup_filters();

	search_box = memnew( LineEdit );
	search_box->connect("text_changed",this,"_search_text_changed");
	search_box->set_h_size_flags(SIZE_EXPAND_FILL);
	add_child(search_box);

	clear_search_button = memnew( ToolButton );
	clear_search_button->connect("pressed",this,"_command",make_binds(CMD_CLEAR_FILTER));
	add_child(clear_search_button);

}


text:
package models.lists;

import javax.persistence.Entity;
import javax.persistence.Id;

import com.avaje.ebean.Page;

import play.db.ebean.Model;

@SuppressWarnings("serial")
@Entity
public class Hpricerange extends Model {
	public Hpricerange() {

	}
	public Hpricerange (String description) {
		this.description = description;
	}
	@Id
	Long id;
	String description;

	public static Finder<Long, Hpricerange> find = new Finder<Long, Hpricerange>(Long.class, Hpricerange.class);

	public static Page<Hpricerange> find(int page) {
	    return
	            find.where()
	                .orderBy("id asc")
	                .findPagingList(10)
	                .setFetchAhead(false)
	                .getPage(page);
	}

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
}

redpajama_set_name: RedPajamaGithub


text:
require 'cloud_conductor/updaters/updater'

module CloudConductor
  module Updaters
    describe Updater do
      include_context 'default_resources'

      before do
        @updater = Updater.new(cloud, environment)
        allow(@updater).to receive(:get_nodes).and_return([])
      end

      describe '#new' do
        it 'keep @cloud' do
          expect(@updater.instance_variable_get(:@cloud)).to eq(cloud)
        end

        it 'keep @environment' do
          expect(@updater.instance_variable_get(:@environment)).to eq(environment)
        end
      end

      describe '#update' do
        before do
          allow(@updater).to receive(:update_infrastructure)
          allow(@updater).to receive(:send_events)
        end

        it 'keep @nodes that contains node list before update' do
          @updater.update
          expect(@updater.instance_variable_get(:@nodes)).to eq([])
        end

        it 'call subroutines that can override in child classes' do
          expect(@updater).to receive(:update_infrastructure)
          expect(@updater).to receive(:send_events)
          @updater.update
        end

        it 'update environment status to :CREATE_COMPLETE without error' do
          @updater.update
          expect(environment.status).to eq(:CREATE_COMPLETE)
        end

        it 'raise error and update environment status to :ERROR when some error has been occurred' do
          allow(@updater).to receive(:update_infrastructure).and_raise
          expect { @updater.update }.to raise_error(RuntimeError)
          expect(environment.status).to eq(:ERROR)
        end
      end

      describe '#update_infrastructure' do
        it 'raise exception when call don\'t overrided update_infrastructure' do
          allow(@updater).to receive(:update_infrastructure).and_call_original
          expect { @updater.send(:update_infrastructure) }.to raise_error(RuntimeError)
        end
      end

      describe '#send_events' do
        before do
          @event = double(:event, sync_fire: 1)
          allow(environment).to receive(:event).and_return(@event)

          @updater.instance_variable_set(:@nodes, [])
        end

        it 'will request configure event to consul' do
          expect(@event).to receive(:sync_fire).with(:configure)
          @updater.send(:send_events, environment)
        end

        it 'won\'t request restore event to consul when instance have not been added' do
          expect(@event).not_to receive(:sync_fire).with(:restore, anything, anything)
          @updater.send(:send_events, environment)
        end

        it 'will request restore event to added instances on consul' do
          @updater.instance_variable_set(:@nodes, %w(dummy1 dummy3))
          allow(@updater).to receive(:get_nodes).and_return(%w(dummy1 dummy2 dummy3))

          expect(@event).to receive(:sync_fire).with(:restore, {}, node: ['dummy2'])
          @updater.send(:send_events, environment)
        end

        it 'won\'t request deploy event to consul when instance have not been added' do
          expect(@event).not_to receive(:sync_fire).with(:deploy, anything, anything)
          @updater.send(:send_events, environment)
        end

        it 'won\'t request deploy event to consul when application have not been deployed' do
          @updater.instance_variable_set(:@nodes, %w(dummy1 dummy3))
          allow(@updater).to receive(:get_nodes).and_return(%w(dummy1 dummy2 dummy3))

          expect(@event).not_to receive(:sync_fire).with(:deploy, {}, node: ['dummy2'])
          @updater.send(:send_events, environment)
        end

        it 'will request deploy event to consul when create environment that already deploymented' do
          @updater.instance_variable_set(:@nodes, %w(dummy1 dummy3))
          allow(@updater).to receive(:get_nodes).and_return(%w(dummy1 dummy2 dummy3))

          environment.status = :CREATE_COMPLETE
          FactoryGirl.create(:deployment, environment: environment, application_history: application_history)

          expect(@event).to receive(:sync_fire).with(:deploy, {}, node: ['dummy2'])
          @updater.send(:send_events, environment)
        end

        it 'will request spec event to consul' do
          expect(@event).to receive(:sync_fire).with(:spec)
          @updater.send(:send_events, environment)
        end
      end
    end
  end
end


text:
minet
=====

Client Side of Computer Networking Project.


text:
#import <ABI42_0_0React/ABI42_0_0RCTSinglelineTextInputView.h>

#import <ABI42_0_0React/ABI42_0_0RCTBridge.h>

#import <ABI42_0_0React/ABI42_0_0RCTUITextField.h>

@implementation ABI42_0_0RCTSinglelineTextInputView
{
  ABI42_0_0RCTUITextField *_backedTextInputView;
}

- (instancetype)initWithBridge:(ABI42_0_0RCTBridge *)bridge
{
  if (self = [super initWithBridge:bridge]) {
    // `blurOnSubmit` defaults to `true` for <TextInput multiline={false}> by design.
    self.blurOnSubmit = YES;

    _backedTextInputView = [[ABI42_0_0RCTUITextField alloc] initWithFrame:self.bounds];
    _backedTextInputView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _backedTextInputView.textInputDelegate = self;

    [self addSubview:_backedTextInputView];
  }

  return self;
}

- (id<ABI42_0_0RCTBackedTextInputViewProtocol>)backedTextInputView
{
  return _backedTextInputView;
}

@end


text:
package com.authlete.jaxrs;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import com.authlete.common.api.AuthleteApi;
import com.authlete.jaxrs.spi.DeviceCompleteRequestHandlerSpi;

/**
 * A base class for device complete endpoints of OAuth 2.0 Device Authorization
 * Grant (Device Flow).
 *
 * @since 2.18
 *
 * @author Hideki Ikeda
 */
public class BaseDeviceCompleteEndpoint extends BaseEndpoint
{
    /**
     * Handle a device complete request.
     *
     *

     * This method internally creates a {@link DeviceCompleteRequestHandler} instance and
     * calls its {@link DeviceCompleteRequestHandler#handle(String, String[])} method.
     * Then, this method uses the value returned from the {@code handle()} method
     * as a response from this method.
     *

     *
     *

     * When {@code DeviceCompleteRequestHandler.handle()} method raises a {@link
     * WebApplicationException}, this method calls {@link #onError(WebApplicationException)
     * onError()} method with the exception. The default implementation of {@code onError()}
     * does nothing. You can override the method as necessary. After calling
     * {@code onError()} method, this method calls {@code getResponse()} method of
     * the exception and uses the returned value as a response from this method.
     *

     *
     * @param api
     *         An implementation of {@link AuthleteApi}.
     *
     * @param spi
     *         An implementation of {@link DeviceCompleteRequestHandlerSpi}.
     *
     * @param userCode
     *         The user code that the end-user input.
     *
     * @param claimNames
     *         Names of requested claims. Use the value of the {@code claimNames}
     *         parameter in a response from Authlete's {@code /api/device/verification} API.
     *
     * @return
     *         A response that should be returned to the end-user.
     */
    public Response handle(
            AuthleteApi api, DeviceCompleteRequestHandlerSpi spi, String userCode,
            String[] claimNames)
    {
        try
        {
            // Create a handler.
            DeviceCompleteRequestHandler handler = new DeviceCompleteRequestHandler(api, spi);

            // Delegate the task to the handler.
            return handler.handle(userCode, claimNames);
        }
        catch (WebApplicationException e)
        {
            // An error occurred in the handler.
            onError(e);

            // Convert the error to a Response.
            return e.getResponse();
        }
    }
}


text:
Laravel Cashier provides an expressive, fluent interface to [Mollie's](https://www.mollie.com) subscription billing services. It handles almost all of the boilerplate subscription billing code you are dreading writing. In addition to basic subscription management, Cashier can handle coupons, swapping subscription, cancellation grace periods, and even generate invoice PDFs.

## Documentation
Since this is an unofficial Laravel package, you can not find any documentation about this package on the [Laravel website](http://laravel.com/docs/billing).
TODO

## License
Laravel Cashier - Mollie Edition is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)


text:
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="A place for music">
    <meta name="author" content="Tyler">
    <title>Musicality</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
    <link href="static/styles.css" rel="stylesheet">

              <input type="text" class="form-control input" id="input" value="">

                <button class="btn btn-default" type="button" id="btn">Go! </button>


text:
var LIMIT_ACTION = { STOP : 0,
                     KILL : 1 };

function Sprite()
{
    this.Clear();
}

Sprite.prototype.Clear = function()
{
    this.index = -1;
    this.active = false;
    this.dormant = false;
    this.type = null;
    this.x = 0;
    this.y = 0;
    this.speedX = 0;
    this.speedY = 0;
    this.animation = null;
    this.persistSpeed = false;
    this.visible = true;
    this.minX = null;
    this.minY = null;
    this.maxX = null;
    this.maxY = null;
    this.limitAction = LIMIT_ACTION.STOP;
    this.hotArea = null;
}

Sprite.prototype.Update = function()
{
    if(this.active && !this.dormant)
    {
        // Update position
        this.x += this.speedX;
        this.y += this.speedY;

        // Clear speed, unless persisted
        if(!this.persistSpeed)
        {
            this.speedX = 0;
            this.speedY = 0;
        }

        // Stop at limit
        if(this.limitAction == LIMIT_ACTION.STOP)
        {
            if(this.minX != null && this.x < this.minX) this.x = this.minX;
            if(this.maxX != null && this.x > this.maxX) this.x = this.maxX;
            if(this.minY != null && this.y < this.minY) this.y = this.minY;
            if(this.maxY != null && this.y > this.maxY) this.y = this.maxY;
        }

        // Kill at limit
        if(this.limitAction == LIMIT_ACTION.KILL)
        {
            if(this.minX != null && this.x < this.minX) g_SpriteList[this.index].active = false;
            if(this.maxX != null && this.x > this.maxX) g_SpriteList[this.index].active = false;
            if(this.minY != null && this.y < this.minY) g_SpriteList[this.index].active = false;
            if(this.maxY != null && this.y > this.maxY) g_SpriteList[this.index].active = false;
        }

        // Update animation
        this.animation.Update();
    }
}

Sprite.prototype.Draw = function()
{
    if(this.active && this.visible && !this.dormant)
    {
        var bitmap = g_BitmapManager.BitmapList[this.animation.bitmapIndex];
        g_Context.drawImage(bitmap.image,
                            this.animation.currentFrame * bitmap.tileWidth, 0, bitmap.tileWidth, bitmap.tileHeight,
                            this.x, this.y, bitmap.tileWidth, bitmap.tileHeight);
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.spi.block;

import com.facebook.presto.spi.type.TypeManager;
import io.airlift.slice.SliceInput;
import io.airlift.slice.SliceOutput;

import static com.facebook.presto.spi.block.EncoderUtil.decodeNullBits;
import static com.facebook.presto.spi.block.EncoderUtil.encodeNullsAsBits;

public class IntArrayBlockEncoding
        implements BlockEncoding
{
    public static final BlockEncodingFactory<IntArrayBlockEncoding> FACTORY = new IntArrayBlockEncodingFactory();
    private static final String NAME = "INT_ARRAY";

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

    @Override
    public void writeBlock(SliceOutput sliceOutput, Block block)
    {
        int positionCount = block.getPositionCount();
        sliceOutput.appendInt(positionCount);

        encodeNullsAsBits(sliceOutput, block);

        for (int position = 0; position < positionCount; position++) {
            if (!block.isNull(position)) {
                sliceOutput.writeInt(block.getInt(position, 0));
            }
        }
    }

    @Override
    public Block readBlock(SliceInput sliceInput)
    {
        int positionCount = sliceInput.readInt();

        boolean[] valueIsNull = decodeNullBits(sliceInput, positionCount);

        int[] values = new int[positionCount];
        for (int position = 0; position < positionCount; position++) {
            if (!valueIsNull[position]) {
                values[position] = sliceInput.readInt();
            }
        }

        return new IntArrayBlock(positionCount, valueIsNull, values);
    }

    @Override
    public BlockEncodingFactory getFactory()
    {
        return FACTORY;
    }

    public static class IntArrayBlockEncodingFactory
            implements BlockEncodingFactory<IntArrayBlockEncoding>
    {
        @Override
        public String getName()
        {
            return NAME;
        }

        @Override
        public IntArrayBlockEncoding readEncoding(TypeManager manager, BlockEncodingSerde serde, SliceInput input)
        {
            return new IntArrayBlockEncoding();
        }

        @Override
        public void writeEncoding(BlockEncodingSerde serde, SliceOutput output, IntArrayBlockEncoding blockEncoding)
        {
        }
    }
}


text:
DEFINE_string(opt, "CTR,MinMaxLD", "The optimizers to plot");

static std::string GetFilename(const std::string& tm_file,
                               const std::string opt_string) {
  std::string tm_base = nc::StringReplace(tm_file, ".demands", "", true);
  return nc::StrCat(tm_base, "_", opt_string, ".rc");
}

int main(int argc, char** argv) {
  gflags::ParseCommandLineFlags(&argc, &argv, true);

  std::vector<ctr::TopologyAndFilename> topologies;
  std::vector<ctr::DemandMatrixAndFilename> matrices;
  std::tie(topologies, matrices) = ctr::GetDemandMatrixInputs(false);
  CHECK(topologies.size() == 1) << "Only one topology should match";
  CHECK(matrices.size() == 1) << "Only one TM should match";

  const nc::lp::DemandMatrix* demand_matrix = matrices[0].demand_matrix.get();
  const nc::net::GraphStorage* graph = demand_matrix->graph();
  const std::vector<std::string>& node_order = topologies[0].node_order;
  const std::string& demand_file = matrices[0].file;
  const std::string& topology_file = topologies[0].file;

  nc::viz::CDFPlot plot({nc::StrCat("Link utilizations for ",
                                    nc::File::ExtractFileName(demand_file)),
                         "link utilization"});
  std::vector<std::string> opts = nc::Split(FLAGS_opt, ",", true);
  for (const std::string& opt : opts) {
    ctr::PathProvider path_provider(graph);
    std::string rc_filename = GetFilename(demand_file, opt);
    if (!nc::File::Exists(rc_filename)) {
      LOG(INFO) << "Missing " << rc_filename;
      continue;
    }

    std::string rc_serialized = nc::File::ReadFileToStringOrDie(rc_filename);
    std::unique_ptr<ctr::TrafficMatrix> tm =
        ctr::TrafficMatrix::DistributeFromDemandMatrix(*demand_matrix);
    LOG(INFO) << "Will parse " << demand_file << " at " << topology_file
              << " opt " << opt;
    auto rc = ctr::RoutingConfiguration::LoadFromSerializedText(
        *tm, node_order, rc_serialized, &path_provider);

    nc::net::GraphLinkMap<double> utilizations = rc->LinkUtilizations();
    std::vector<double> to_plot;
    for (const auto& link_and_util : utilizations) {
      to_plot.emplace_back(*link_and_util.second);
    }

    double total = std::accumulate(to_plot.begin(), to_plot.end(), 0.0);
    double mean = total / to_plot.size();
    std::string label =
        nc::StrCat(opt, " (mean ", nc::ToStringMaxDecimals(mean, 2), ")");
    plot.AddData(label, to_plot);
  }

  plot.PlotToDir("utilization");
}


text:
#pragma once
#include <aws/workdocs/WorkDocs_EXPORTS.h>
#include <aws/workdocs/WorkDocsRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace WorkDocs
{
namespace Model
{

  /**
   */
  class AWS_WORKDOCS_API DeleteNotificationSubscriptionRequest : public WorkDocsRequest
  {
  public:
    DeleteNotificationSubscriptionRequest();

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

    Aws::String SerializePayload() const override;

    /**
     *
The ID of the subscription.

     */
    inline const Aws::String& GetSubscriptionId() const{ return m_subscriptionId; }

    /**
     *
The ID of the subscription.

     */
    inline bool SubscriptionIdHasBeenSet() const { return m_subscriptionIdHasBeenSet; }

    /**
     *
The ID of the subscription.

     */
    inline void SetSubscriptionId(const Aws::String& value) { m_subscriptionIdHasBeenSet = true; m_subscriptionId = value; }

    /**
     *
The ID of the subscription.

     */
    inline void SetSubscriptionId(Aws::String&& value) { m_subscriptionIdHasBeenSet = true; m_subscriptionId = std::move(value); }

    /**
     *
The ID of the subscription.

     */
    inline void SetSubscriptionId(const char* value) { m_subscriptionIdHasBeenSet = true; m_subscriptionId.assign(value); }

    /**
     *
The ID of the subscription.

     */
    inline DeleteNotificationSubscriptionRequest& WithSubscriptionId(const Aws::String& value) { SetSubscriptionId(value); return *this;}

    /**
     *
The ID of the subscription.

     */
    inline DeleteNotificationSubscriptionRequest& WithSubscriptionId(Aws::String&& value) { SetSubscriptionId(std::move(value)); return *this;}

    /**
     *
The ID of the subscription.

     */
    inline DeleteNotificationSubscriptionRequest& WithSubscriptionId(const char* value) { SetSubscriptionId(value); return *this;}

    /**
     *
The ID of the organization.

     */
    inline const Aws::String& GetOrganizationId() const{ return m_organizationId; }

    /**
     *
The ID of the organization.

     */
    inline bool OrganizationIdHasBeenSet() const { return m_organizationIdHasBeenSet; }

    /**
     *
The ID of the organization.

     */
    inline void SetOrganizationId(const Aws::String& value) { m_organizationIdHasBeenSet = true; m_organizationId = value; }

    /**
     *
The ID of the organization.

     */
    inline void SetOrganizationId(Aws::String&& value) { m_organizationIdHasBeenSet = true; m_organizationId = std::move(value); }

    /**
     *
The ID of the organization.

     */
    inline void SetOrganizationId(const char* value) { m_organizationIdHasBeenSet = true; m_organizationId.assign(value); }

    /**
     *
The ID of the organization.

     */
    inline DeleteNotificationSubscriptionRequest& WithOrganizationId(const Aws::String& value) { SetOrganizationId(value); return *this;}

    /**
     *
The ID of the organization.

     */
    inline DeleteNotificationSubscriptionRequest& WithOrganizationId(Aws::String&& value) { SetOrganizationId(std::move(value)); return *this;}

    /**
     *
The ID of the organization.

     */
    inline DeleteNotificationSubscriptionRequest& WithOrganizationId(const char* value) { SetOrganizationId(value); return *this;}

  private:

    Aws::String m_subscriptionId;
    bool m_subscriptionIdHasBeenSet = false;

    Aws::String m_organizationId;
    bool m_organizationIdHasBeenSet = false;
  };

} // namespace Model
} // namespace WorkDocs
} // namespace Aws


text:
package com.platypii.baseline.views.charts;

import com.platypii.baseline.Services;
import com.platypii.baseline.events.ChartFocusEvent;
import com.platypii.baseline.lasers.LaserMeasurement;
import com.platypii.baseline.lasers.LaserProfile;
import com.platypii.baseline.measurements.MLocation;
import com.platypii.baseline.tracks.TrackData;
import com.platypii.baseline.util.Bounds;
import com.platypii.baseline.views.charts.layers.ChartLayer;
import com.platypii.baseline.views.charts.layers.Colors;
import com.platypii.baseline.views.charts.layers.LaserProfileLayer;
import com.platypii.baseline.views.charts.layers.TrackProfileLayer;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import androidx.annotation.NonNull;
import java.util.ArrayList;
import java.util.List;
import org.greenrobot.eventbus.EventBus;

public class FlightProfileTouchable extends FlightProfile {

    private float scaleFactor = 1;

    final List<TrackData> tracks = new ArrayList<>();
    final List<LaserProfile> lasers = new ArrayList<>();

    public FlightProfileTouchable(Context context, AttributeSet attrs) {
        super(context, attrs);

        // Add starred tracks
        for (TrackData track : Services.tracks.getStarredTracks(context)) {
            addLayer(new TrackProfileLayer(track.id, track.id, track, Colors.starredTracks));
        }
    }

    private final ScaleGestureDetector scaler = new ScaleGestureDetector(getContext(), new ScaleGestureDetector.SimpleOnScaleGestureListener() {
        @Override
        public boolean onScale(@NonNull ScaleGestureDetector detector) {
            scaleFactor *= detector.getScaleFactor();
            scaleFactor = Math.max(1f, Math.min(scaleFactor, 10f));
            invalidate();
            return true;
        }
    });

    @Override
    public boolean onTouchEvent(@NonNull MotionEvent event) {
        super.onTouchEvent(event);
        scaler.onTouchEvent(event);

        // Focus
        if (!scaler.isInProgress()) {
            final int action = event.getAction();
            if (action == MotionEvent.ACTION_MOVE) {
                final double x = plot.getXinverse(0, event.getX());
                final double y = plot.getYinverse(0, event.getY());
                // Find nearest data point, and emit chart focus event
                EventBus.getDefault().post(findClosest(x, y));
            } else if (action == MotionEvent.ACTION_UP) {
                // Clear chart focus event
                EventBus.getDefault().post(new ChartFocusEvent.Unfocused());
            }
        }
        return true; // event was handled
    }

    @Override
    public void addLayer(@NonNull ChartLayer layer) {
        super.addLayer(layer);
        // Keep focus layer on top
        removeLayer(focusLayer);
        super.addLayer(focusLayer);
        // Add to track/laser lists for focusing later
        if (layer instanceof TrackProfileLayer) {
            tracks.add(((TrackProfileLayer) layer).trackData);
        } else if (layer instanceof LaserProfileLayer) {
            lasers.add(((LaserProfileLayer) layer).laserProfile);
        }
    }

    @Override
    public void removeLayer(@NonNull ChartLayer layer) {
        super.removeLayer(layer);
        // Remove from track/laser lists
        if (layer instanceof TrackProfileLayer) {
            tracks.remove(((TrackProfileLayer) layer).trackData);
        } else if (layer instanceof LaserProfileLayer) {
            lasers.remove(((LaserProfileLayer) layer).laserProfile);
        }
    }

    /**
     * Performs a search for the nearest data point
     */
    @NonNull
    private ChartFocusEvent findClosest(double x, double y) {
        ChartFocusEvent closest = new ChartFocusEvent.Unfocused();
        double closestDistance = Double.POSITIVE_INFINITY;
        for (TrackData trackData : tracks) {
            if (!trackData.data.isEmpty()) {
                final MLocation start = trackData.data.get(0);
                for (MLocation loc : trackData.data) {
                    final double dx = start.distanceTo(loc) - x;
                    final double dy = loc.altitude_gps - start.altitude_gps - y;
                    final double distance = dx * dx + dy * dy; // distance squared
                    if (distance < closestDistance) {
                        closest = new ChartFocusEvent.TrackFocused(loc, trackData.data);
                        closestDistance = distance;
                    }
                }
            }
        }
        for (LaserProfile laser : lasers) {
            for (LaserMeasurement point : laser.points) {
                final double dx = point.x - x;
                final double dy = point.y - y;
                final double distance = dx * dx + dy * dy; // distance squared
                if (distance < closestDistance) {
                    closest = new ChartFocusEvent.LaserFocused(point);
                    closestDistance = distance;
                }
            }
        }
        return closest;
    }

    @NonNull
    @Override
    public Bounds getBounds(@NonNull Bounds dataBounds, int axis) {
        dataBounds.x.max /= scaleFactor;
        dataBounds.y.min /= scaleFactor;
        return super.getBounds(dataBounds, axis);
    }

}


text:
#include "StandardOutputStream.h"

using namespace decaf;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;
using namespace decaf::internal;
using namespace decaf::internal::io;

////////////////////////////////////////////////////////////////////////////////
StandardOutputStream::StandardOutputStream() {
}

////////////////////////////////////////////////////////////////////////////////
StandardOutputStream::~StandardOutputStream() {
}

////////////////////////////////////////////////////////////////////////////////
void StandardOutputStream::doWriteByte( unsigned char c ) {

    std::cout << c;
}

////////////////////////////////////////////////////////////////////////////////
void StandardOutputStream::doWriteArrayBounded( const unsigned char* buffer, int size,
                                                int offset, int length ) {

    if( length == 0 ) {
        return;
    }

    if( buffer == NULL ) {
        throw lang::exceptions::NullPointerException(
            __FILE__, __LINE__,
            "StandardErrorOutputStream::write - Passed buffer is null." );
    }

    if( size < 0 ) {
        throw IndexOutOfBoundsException(
            __FILE__, __LINE__, "size parameter out of Bounds: %d.", size );
    }

    if( offset > size || offset < 0 ) {
        throw IndexOutOfBoundsException(
            __FILE__, __LINE__, "offset parameter out of Bounds: %d.", offset );
    }

    if( length < 0 || length > size - offset ) {
        throw IndexOutOfBoundsException(
            __FILE__, __LINE__, "length parameter out of Bounds: %d.", length );
    }

    for( int i = 0; i < length; ++i ) {
        std::cout << buffer[i+offset];
    }
}

////////////////////////////////////////////////////////////////////////////////
void StandardOutputStream::flush() {
    std::cout.flush();
}

////////////////////////////////////////////////////////////////////////////////
void StandardOutputStream::close() {
    std::cout.flush();
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Model;

import View.MainMenu;
import java.util.List;
import java.util.Random;

/**
 *
 * @author ryan
 */
public class EnemyFactory {

    private Ship enemyShip;
    private Ship[] enemyFormation;
    private Random rand;

    public Ship getEnemyShip(String shipSelection, float x, float y){

        switch(shipSelection) {
            case "defaultship":
                enemyShip = new EnemyShip(x,y);
                return enemyShip;
            default:
                throw new IllegalArgumentException("NO SUCH SHIP TYPE");
        }
    }

    public Ship[] getEnemyShipFormation(String shipSelection, float x, float y) {
        enemyFormation = new Ship[5];
        rand = new Random();
        enemyFormation[0] = new EnemyShip("alien1", x, y - rand.nextInt(1000));
        enemyFormation[1] = new EnemyShip("blueFighter", x + rand.nextInt(800), y - rand.nextInt(1000));
        enemyFormation[2] = new EnemyShip("purpleFighter", x + rand.nextInt(800), y - rand.nextInt(1000));
        enemyFormation[3] = new EnemyShip("redFighter", x + rand.nextInt(800), y - rand.nextInt(1000));
        enemyFormation[4] = new EnemyShip("defaultEnemyShip", x + rand.nextInt(800), y - rand.nextInt(1000));
        return enemyFormation;
    }

}


text:
<tool id="artic_minion" name="ARTIC minion" version="@PACKAGE_VERSION@+galaxy0" profile="20.09">
    <description>Build consensus sequence and call variants from amplicon-based nanopore sequence data</description>
    <macros>
        <import>macros.xml</import>
    </macros>
    <xrefs>
        <xref type="bio.tools">artic</xref>
    </xrefs>
    <requirements>
        <requirement type="package" version="@PACKAGE_VERSION@">artic</requirement>
    </requirements>
    <command detect_errors="exit_code"><![CDATA[
        mkdir -p 'scheme/name/V1' &&
        #if str( $primer_scheme_source.primer_scheme_source_selector ) == "tool_data_table":
          ln -s '${primer_scheme_source.primer_scheme_bedfile.fields.path}' 'scheme/name/V1/name.scheme.bed' &&
        #else:
          ln -s '${primer_scheme_source.primer_scheme_bedfile}' 'scheme/name/V1/name.scheme.bed' &&
        #end if
        #if str( $reference_source.reference_source_selector ) == "history":
          ln -s '${reference_source.reference}' 'scheme/name/V1/name.reference.fasta' &&
          samtools faidx 'scheme/name/V1/name.reference.fasta' &&
        #else:
          ln -s '${reference_source.reference.fields.path}' 'scheme/name/V1/name.reference.fasta' &&
          samtools faidx 'scheme/name/V1/name.reference.fasta' &&
        #end if
        artic minion
            --threads \${GALAXY_SLOTS:-1}
        #if $normalise > 0:
            --normalise ${normalise}
        #end if
            --read-file '${read_file}'
            --scheme-directory 'scheme'
            --medaka
            --medaka-model '$medaka_model'
            $bwa
            'name/V1'
            '${read_file.element_identifier}'
        && bgzip -f '${read_file.element_identifier}.fail.vcf'
    ]]></command>
    <inputs>
        <param argument="--read-file" type="data" format="fastq,fastqsanger,fastq.gz,fastqsanger.gz" label="Input Read File"/>
        <param argument="--normalise" type="integer" min="0" value="0"
        label="Coverage normalisation depth"
        help="Sample at most this number of reads per amplicon and strand. default=0 (use all reads)" />
        <param argument="--bwa" type="boolean" truevalue="--bwa" falsevalue="" label="Use bwa aligner"/>
        <conditional name="primer_scheme_source">
            <param name="primer_scheme_source_selector" type="select" label="Select a primer scheme from your history or use one from a tool data table?"
                   help="Screening files must be stored in the 'primer_scheme_bedfiles' tool data table">
                <option value="tool_data_table">From tool data table</option>
                <option value="history">From history</option>
            </param>
            <when value="tool_data_table">
                <param name="primer_scheme_bedfile" type="select" format="tabular" label="Primer Scheme">
	            <options from_data_table="primer_scheme_bedfiles">
	                <validator type="no_options" message="No primer scheme .bed files are available" />
                    </options>
	        </param>
            </when>
            <when value="history">
                <param name="primer_scheme_bedfile" type="data" format="tabular" label="Primer Scheme" />
            </when>
        </conditional>
        <conditional name="reference_source">
            <param name="reference_source_selector" type="select" label="Will you select a reference genome from your history or use a built-in reference?" >
                <option value="cached">Use a built-in reference</option>
                <option value="history">Use a reference from history</option>
            </param>
            <when value="cached">
                <param name="reference" type="select" label="Using reference genome" help="Select genome from the list">
                    <options from_data_table="all_fasta">
                        <filter type="sort_by" column="2" />
                        <validator type="no_options" message="No references are available" />
                    </options>
                </param>
            </when>
            <when value="history">
                <param name="reference" type="data" format="fasta" label="Use the following dataset as the reference sequence"
                       help="You can upload a FASTA sequence to the history and use it as reference" />
            </when>
        </conditional>
        <param type="text" name="medaka_model" label="Medaka model" help="Model string to pass to medaka (see https://github.com/nanoporetech/medaka#models)">
            <validator type="expression" message="Please specify a valid medaka model string (see https://github.com/nanoporetech/medaka#models)">(len(value.strip().split('_')) == 3 or len(value.strip().split('_')) == 4) and value.strip().startswith('r')</validator>
        </param>
    </inputs>
    <outputs>
        <data name="alignment_trimmed" format="bam" from_work_dir="*.primertrimmed.rg.sorted.bam" label="${tool.name} on ${on_string}: trimmed alignment" />
        <data name="alignment_report" format="tabular" from_work_dir="*.alignreport.txt" label="${tool.name} on ${on_string}: alignment report" />
        <data name="variants_merged_vcf" format="vcf_bgzip" from_work_dir="*.merged.vcf.gz" label="${tool.name} on ${on_string}: medaka variant calls" />
        <data name="variants_fail_vcf" format="vcf_bgzip" from_work_dir="*.fail.vcf.gz" label="${tool.name} on ${on_string}: variants fail" />
        <data name="variants_pass_vcf" format="vcf_bgzip" from_work_dir="*.pass.vcf.gz" label="${tool.name} on ${on_string}: variants pass" />
        <data name="consensus_fasta" format="fasta" from_work_dir="*.consensus.fasta" label="${tool.name} on ${on_string}: consensus sequence" />
        <data name="coverage_mask" format="tabular" from_work_dir="*.coverage_mask.txt" label="${tool.name} on ${on_string}: consensus coverage mask" />
        <data name="analysis_log" format="txt" from_work_dir="*.minion.log.txt" label="${tool.name} on ${on_string}: analysis log" />
    </outputs>
    <tests>
        <test>
            <param name="reference_source_selector" value="history" />
            <param name="read_file" value="SRR11410539_seqtk_sample_500_1.fastq" />
            <param name="reference" value="nCoV-2019.reference.fasta" />
            <param name="primer_scheme_source_selector" value="tool_data_table" />
            <param name="primer_scheme_bedfile" value="test_entry" />
            <param name="medaka_model" value="r941_min_high_g360" />
            <output name="consensus_fasta" file="SRR11410539_seqtk_sample_500_1.fastq.consensus.fasta" />
        </test>
        <test>
            <param name="reference_source_selector" value="history" />
            <param name="read_file" value="SRR11410539_seqtk_sample_500_1.fastq" />
            <param name="reference" value="nCoV-2019.reference.fasta" />
            <param name="primer_scheme_source_selector" value="history" />
            <param name="primer_scheme_bedfile" value="nCoV-2019.scheme.V1.bed" />
            <param name="medaka_model" value="r941_min_high_g360" />
            <output name="consensus_fasta" file="SRR11410539_seqtk_sample_500_1.fastq.consensus.fasta" />
        </test>
        <test>
            <param name="reference_source_selector" value="tool_data_table" />
            <param name="read_file" value="SRR11410539_seqtk_sample_500_1.fastq" />
            <param name="reference" value="test_entry" />
            <param name="primer_scheme_source_selector" value="tool_data_table" />
            <param name="primer_scheme_bedfile" value="test_entry" />
            <param name="medaka_model" value="r941_min_high_g360" />
            <output name="consensus_fasta" file="SRR11410539_seqtk_sample_500_1.fastq.consensus.fasta" />
        </test>
    </tests>
    <help><![CDATA[
ARTIC_ minion aligns Nanopore reads that were generated from a tiling amplicon library against a viral reference sequence.
It generates a consensus fasta file and a vcf variant file.

This tool is configured to use the experimental 'medaka' variant caller and must be supplied with the name of
a model file to use with 'medaka', see the `medaka web page`_ for details.

.. _ARTIC: https://artic.readthedocs.io/en/latest/
.. _medaka web page: https://github.com/nanoporetech/medaka#models

Note that you should choose an appropriate model for the medaka version used by ARTIC minion.

==================  ==================
  ARTIC version     medaka version
==================  ==================
 1.2.1                1.0.3
 1.3.0-dev            1.2.3
==================  ==================
    ]]></help>
    <expand macro="citations" />
</tool>


text:
#ifndef QTOOLBUTTON_H
#define QTOOLBUTTON_H

#include <QtWidgets/qabstractbutton.h>

QT_BEGIN_NAMESPACE

#ifndef QT_NO_TOOLBUTTON

class QToolButtonPrivate;
class QMenu;
class QStyleOptionToolButton;

class Q_WIDGETS_EXPORT QToolButton : public QAbstractButton
{
    Q_OBJECT
    Q_ENUMS(Qt::ToolButtonStyle Qt::ArrowType)
#ifndef QT_NO_MENU
    Q_PROPERTY(ToolButtonPopupMode popupMode READ popupMode WRITE setPopupMode)
#endif
    Q_PROPERTY(Qt::ToolButtonStyle toolButtonStyle READ toolButtonStyle WRITE setToolButtonStyle)
    Q_PROPERTY(bool autoRaise READ autoRaise WRITE setAutoRaise)
    Q_PROPERTY(Qt::ArrowType arrowType READ arrowType WRITE setArrowType)

public:
    enum ToolButtonPopupMode {
        DelayedPopup,
        MenuButtonPopup,
        InstantPopup
    };
    Q_ENUM(ToolButtonPopupMode)

    explicit QToolButton(QWidget *parent = Q_NULLPTR);
    ~QToolButton();

    QSize sizeHint() const Q_DECL_OVERRIDE;
    QSize minimumSizeHint() const Q_DECL_OVERRIDE;

    Qt::ToolButtonStyle toolButtonStyle() const;

    Qt::ArrowType arrowType() const;
    void setArrowType(Qt::ArrowType type);

#ifndef QT_NO_MENU
    void setMenu(QMenu* menu);
    QMenu* menu() const;

    void setPopupMode(ToolButtonPopupMode mode);
    ToolButtonPopupMode popupMode() const;
#endif

    QAction *defaultAction() const;

    void setAutoRaise(bool enable);
    bool autoRaise() const;

public Q_SLOTS:
#ifndef QT_NO_MENU
    void showMenu();
#endif
    void setToolButtonStyle(Qt::ToolButtonStyle style);
    void setDefaultAction(QAction *);

Q_SIGNALS:
    void triggered(QAction *);

protected:
    bool event(QEvent *e) Q_DECL_OVERRIDE;
    void mousePressEvent(QMouseEvent *) Q_DECL_OVERRIDE;
    void mouseReleaseEvent(QMouseEvent *) Q_DECL_OVERRIDE;
    void paintEvent(QPaintEvent *) Q_DECL_OVERRIDE;
    void actionEvent(QActionEvent *) Q_DECL_OVERRIDE;

    void enterEvent(QEvent *) Q_DECL_OVERRIDE;
    void leaveEvent(QEvent *) Q_DECL_OVERRIDE;
    void timerEvent(QTimerEvent *) Q_DECL_OVERRIDE;
    void changeEvent(QEvent *) Q_DECL_OVERRIDE;

    bool hitButton(const QPoint &pos) const Q_DECL_OVERRIDE;
    void nextCheckState() Q_DECL_OVERRIDE;
    void initStyleOption(QStyleOptionToolButton *option) const;

private:
    Q_DISABLE_COPY(QToolButton)
    Q_DECLARE_PRIVATE(QToolButton)
#ifndef QT_NO_MENU
    Q_PRIVATE_SLOT(d_func(), void _q_buttonPressed())
    Q_PRIVATE_SLOT(d_func(), void _q_buttonReleased())
    Q_PRIVATE_SLOT(d_func(), void _q_updateButtonDown())
    Q_PRIVATE_SLOT(d_func(), void _q_menuTriggered(QAction*))
#endif
    Q_PRIVATE_SLOT(d_func(), void _q_actionTriggered())

};

#endif // QT_NO_TOOLBUTTON

QT_END_NAMESPACE

#endif // QTOOLBUTTON_H


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="SectionLabel">
        <item name="android:gravity">start|center_vertical</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textColor">@color/colorPrimary</item>
        <item name="android:textSize">@dimen/section_label_font_size</item>
        <item name="android:padding">@dimen/app_ver_padding</item>
    </style>

    <style name="AppVerName">
        <item name="android:gravity">start|center_vertical</item>
        <item name="android:textColor">@color/colorPrimary</item>
        <item name="android:textSize">@dimen/app_ver_font_size</item>
        <item name="android:paddingStart">@dimen/app_ver_padding</item>
    </style>

    <style name="ChatText" parent="DefaultLabel">
        <item name="android:gravity">start|center_vertical</item>
        <item name="android:autoLink">web|email</item>
        <item name="android:textStyle">normal</item>
        <item name="android:singleLine">false</item>
    </style>

    <style name="ChatTextSend" parent="ChatText">
    </style>

    <style name="ChatTextRecv" parent="ChatText">
    </style>

    <style name="BaseListView" parent="DefaultListView">
        <!--
                <item name="android:listSelector">@drawable/base_list_selector</item>
        -->
    </style>

    <style name="BaseDialogTitle" parent="DefaultLabel" >
        <item name="android:singleLine">true</item>
        <item name="android:textColor">@color/white</item>
        <item name="android:background">@color/colorPrimary</item>
    </style>

    <style name="SendButton">
        <item name="android:textColor">@color/white</item>
        <item name="android:backgroundTint">@color/def_btn_bg_int</item>
    </style>

</resources>


text:
package com.hs.mail.imap.processor;

import com.hs.mail.imap.ImapSession;
import com.hs.mail.imap.mailbox.Mailbox;
import com.hs.mail.imap.mailbox.MailboxManager;
import com.hs.mail.imap.mailbox.MailboxPath;
import com.hs.mail.imap.message.request.ImapRequest;
import com.hs.mail.imap.message.request.RenameRequest;
import com.hs.mail.imap.message.responder.Responder;
import com.hs.mail.imap.message.response.HumanReadableText;

/**
 *
 * @author Won Chul Doh
 * @since Feb 1, 2010
 *
 */
public class RenameProcessor extends AbstractImapProcessor {

	@Override
	protected void doProcess(ImapSession session, ImapRequest message,
			Responder responder) throws Exception {
		RenameRequest request = (RenameRequest) message;
		String sourceName = request.getOldName();
		String targetName = request.getNewName();
		MailboxManager manager = getMailboxManager();
		Mailbox source = manager.getMailbox(session.getUserID(), sourceName);
		MailboxPath targetPath = buildMailboxPath(session, targetName);
		// Attempt to rename from a mailbox name that does not exist
		if (source == null) {
			responder.taggedNo(request, HumanReadableText.MAILBOX_NOT_FOUND);
		} else {
			if (manager.mailboxExists(targetPath.getUserID(), targetName)) {
				// Attempt to rename to a mailbox name that already exists
				responder.taggedNo(request, HumanReadableText.MAILBOX_EXISTS);
			} else {
				// RENAME - Moving a mailbox from one parent to another requires
				// the "x" right on the mailbox itself and the "k" right for the
				// new parent.
				MailboxPath sourcePath = buildMailboxPath(session, sourceName);
				if (!sourcePath.isPersonalNamespace()) {
					if (!manager.hasRights(session.getUserID(), source, "x")) { // x_DeleteMailbox_RIGHT
						responder.taggedNo(request,
								HumanReadableText.INSUFFICIENT_RIGHTS);
						return;
					}
				}
				if (!targetPath.isPersonalNamespace()) {
					Mailbox target = manager.getMailbox(targetPath.getUserID(),
							Mailbox.getParent(targetName));
					if (target == null
							|| !manager.hasRights(session.getUserID(), target,
									"k")) { // k_CreateMailbox_RIGHT
						responder.taggedNo(request,
								HumanReadableText.INSUFFICIENT_RIGHTS);
						return;
					}
				}
				if (targetName.startsWith(sourceName + Mailbox.folderSeparator)) {
					// Check if new name invade structure as in "rename foo foo.bar"
					// would create foo.bar but delete foo.
					responder.taggedNo(request, HumanReadableText.INVADE_STRUCTURE);
				} else {
					manager.renameMailbox(source, targetName);
					responder.okCompleted(request);
				}
			}
		}
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>python.sparknlp.annotator.matcher.big_text_matcher — Spark NLP 4.2.3 documentation</title>

  <link href="../../../../../static/styles/theme.css?digest=1e1de1a1873e13ef5536" rel="stylesheet">
<link href="../../../../../static/styles/pydata-sphinx-theme.css?digest=1e1de1a1873e13ef5536" rel="stylesheet">

  <link rel="stylesheet"
    href="../../../../../static/vendor/fontawesome/6.1.2/css/all.min.css">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-solid-900.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-brands-400.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-regular-400.woff2">

    <link rel="stylesheet" type="text/css" href="../../../../../static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../../../../../static/graphviz.css" />
    <link rel="stylesheet" type="text/css" href="../../../../../static/css/custom.css" />

  <link rel="preload" as="script" href="../../../../../static/scripts/pydata-sphinx-theme.js?digest=1e1de1a1873e13ef5536">

    <link rel="shortcut icon" href="../../../../../static/fav.ico"/>
    <link rel="index" title="Index" href="../../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../../search.html" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="docsearch:language" content="en">

  <input type="checkbox" class="sidebar-toggle" name="__primary" id="__primary">

  <input type="checkbox" class="sidebar-toggle" name="__secondary" id="__secondary">

<form class="bd-search d-flex align-items-center" action="../../../../../search.html" method="get">

  <input type="search" class="form-control" name="q" id="search-input" placeholder="Search the docs ..." aria-label="Search the docs ..." autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
  Ctrl+K
</form>

        Site Navigation

                        Getting Started

                        User Guide

                        Third Party Projects

                        API Reference

<button class="btn btn-sm navbar-btn search-button search-button__button" title="Search" data-toggle="tooltip">

</button>

<button class="btn btn-sm navbar-btn search-button search-button__button" title="Search" data-toggle="tooltip">

</button>

        Site Navigation

                        Getting Started

                        User Guide

                        Third Party Projects

                        API Reference

Source code for python.sparknlp.annotator.matcher.big_text_matcher

#  Copyright 2017-2022 John Snow Labs
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
"""Contains classes for the BigTextMatcher."""

from sparknlp.common import *
from sparknlp.annotator.matcher.text_matcher import TextMatcherModel
from sparknlp.common.annotator_type import AnnotatorType

[docs]class BigTextMatcher(AnnotatorApproach, HasStorage):
    """Annotator to match exact phrases (by token) provided in a file against a
    Document.

    A text file of predefined phrases must be provided with ``setStoragePath``.

    In contrast to the normal ``TextMatcher``, the ``BigTextMatcher`` is
    designed for large corpora.

    ====================== ======================
    Input Annotation types Output Annotation type
    ====================== ======================
    ``DOCUMENT, TOKEN``    ``CHUNK``
    ====================== ======================

    Parameters
    ----------
    entities
        ExternalResource for entities
    caseSensitive
        whether to ignore case in index lookups, by default True
    mergeOverlapping
        whether to merge overlapping matched chunks, by default False
    tokenizer
        TokenizerModel to use to tokenize input file for building a Trie

    Examples
    --------
    In this example, the entities file is of the form::

        ...
        dolore magna aliqua
        lorem ipsum dolor. sit
        laborum
        ...

    where each line represents an entity phrase to be extracted.

    >>> import sparknlp
    >>> from sparknlp.base import *
    >>> from sparknlp.annotator import *
    >>> from pyspark.ml import Pipeline
    >>> documentAssembler = DocumentAssembler() \\
    ...     .setInputCol("text") \\
    ...     .setOutputCol("document")
    >>> tokenizer = Tokenizer() \\
    ...     .setInputCols("document") \\
    ...     .setOutputCol("token")
    >>> data = spark.createDataFrame([["Hello dolore magna aliqua. Lorem ipsum dolor. sit in laborum"]]).toDF("text")
    >>> entityExtractor = BigTextMatcher() \\
    ...     .setInputCols("document", "token") \\
    ...     .setStoragePath("src/test/resources/entity-extractor/test-phrases.txt", ReadAs.TEXT) \\
    ...     .setOutputCol("entity") \\
    ...     .setCaseSensitive(False)
    >>> pipeline = Pipeline().setStages([documentAssembler, tokenizer, entityExtractor])
    >>> results = pipeline.fit(data).transform(data)
    >>> results.selectExpr("explode(entity)").show(truncate=False)
    +--------------------------------------------------------------------+
    |col                                                                 |
    +--------------------------------------------------------------------+
    |[chunk, 6, 24, dolore magna aliqua, [sentence -> 0, chunk -> 0], []]|
    |[chunk, 53, 59, laborum, [sentence -> 0, chunk -> 1], []]           |
    +--------------------------------------------------------------------+
    """

    inputAnnotatorTypes = [AnnotatorType.DOCUMENT, AnnotatorType.TOKEN]

    entities = Param(Params._dummy(),
                     "entities",
                     "ExternalResource for entities",
                     typeConverter=TypeConverters.identity)

    caseSensitive = Param(Params._dummy(),
                          "caseSensitive",
                          "whether to ignore case in index lookups",
                          typeConverter=TypeConverters.toBoolean)

    mergeOverlapping = Param(Params._dummy(),
                             "mergeOverlapping",
                             "whether to merge overlapping matched chunks. Defaults false",
                             typeConverter=TypeConverters.toBoolean)

    tokenizer = Param(Params._dummy(),
                      "tokenizer",
                      "TokenizerModel to use to tokenize input file for building a Trie",
                      typeConverter=TypeConverters.identity)

    @keyword_only
    def __init__(self):
        super(BigTextMatcher, self).__init__(classname="com.johnsnowlabs.nlp.annotators.btm.BigTextMatcher")
        self._setDefault(caseSensitive=True)
        self._setDefault(mergeOverlapping=False)

    def _create_model(self, java_model):
        return TextMatcherModel(java_model=java_model)

[docs]    def setEntities(self, path, read_as=ReadAs.TEXT, options={"format": "text"}):
        """Sets ExternalResource for entities.

        Parameters
        ----------
        path : str
            Path to the resource
        read_as : str, optional
            How to read the resource, by default ReadAs.TEXT
        options : dict, optional
            Options for reading the resource, by default {"format": "text"}
        """
        return self._set(entities=ExternalResource(path, read_as, options.copy()))

[docs]    def setCaseSensitive(self, b):
        """Sets whether to ignore case in index lookups, by default True.

        Parameters
        ----------
        b : bool
            Whether to ignore case in index lookups
        """
        return self._set(caseSensitive=b)

[docs]    def setMergeOverlapping(self, b):
        """Sets whether to merge overlapping matched chunks, by default False.

        Parameters
        ----------
        b : bool
            Whether to merge overlapping matched chunks

        """
        return self._set(mergeOverlapping=b)

[docs]    def setTokenizer(self, tokenizer_model):
        """Sets TokenizerModel to use to tokenize input file for building a
        Trie.

        Parameters
        ----------
        tokenizer_model : :class:`TokenizerModel <sparknlp.annotator.TokenizerModel>`
            TokenizerModel to use to tokenize input file

        """
        tokenizer_model._transfer_params_to_java()
        return self._set(tokenizer_model._java_obj)

[docs]class BigTextMatcherModel(AnnotatorModel, HasStorageModel):
    """Instantiated model of the BigTextMatcher.

    This is the instantiated model of the :class:`.BigTextMatcher`.
    For training your own model, please see the documentation of that class.

    ====================== ======================
    Input Annotation types Output Annotation type
    ====================== ======================
    ``DOCUMENT, TOKEN``    ``CHUNK``
    ====================== ======================

    Parameters
    ----------
    caseSensitive
        Whether to ignore case in index lookups
    mergeOverlapping
        Whether to merge overlapping matched chunks, by default False
    searchTrie
        SearchTrie
    """
    name = "BigTextMatcherModel"
    databases = ['TMVOCAB', 'TMEDGES', 'TMNODES']
    inputAnnotatorTypes = [AnnotatorType.TOKEN]

    caseSensitive = Param(Params._dummy(),
                          "caseSensitive",
                          "whether to ignore case in index lookups",
                          typeConverter=TypeConverters.toBoolean)

    mergeOverlapping = Param(Params._dummy(),
                             "mergeOverlapping",
                             "whether to merge overlapping matched chunks. Defaults false",
                             typeConverter=TypeConverters.toBoolean)

    searchTrie = Param(Params._dummy(),
                       "searchTrie",
                       "searchTrie",
                       typeConverter=TypeConverters.identity)

    def __init__(self, classname="com.johnsnowlabs.nlp.annotators.btm.TextMatcherModel", java_model=None):
        super(BigTextMatcherModel, self).__init__(
            classname=classname,
            java_model=java_model
        )

[docs]    def setMergeOverlapping(self, b):
        """Sets whether to merge overlapping matched chunks, by default False.

        Parameters
        ----------
        v : bool
            Whether to merge overlapping matched chunks, by default False
        """
        return self._set(mergeOverlapping=b)

[docs]    def setCaseSensitive(self, v):
        """Sets whether to ignore case in index lookups.

        Parameters
        ----------
        b : bool
            Whether to ignore case in index lookups
        """
        return self._set(caseSensitive=v)

    @staticmethod

[docs]    def pretrained(name, lang="en", remote_loc=None):
        """Downloads and loads a pretrained model.

        Parameters
        ----------
        name : str, optional
            Name of the pretrained model
        lang : str, optional
            Language of the pretrained model, by default "en"
        remote_loc : str, optional
            Optional remote address of the resource, by default None. Will use
            Spark NLPs repositories otherwise.

        Returns
        -------
        TextMatcherModel
            The restored model
        """
        from sparknlp.pretrained import ResourceDownloader
        return ResourceDownloader.downloadModel(TextMatcherModel, name, lang, remote_loc)

    @staticmethod

[docs]    def loadStorage(path, spark, storage_ref):
        """Loads the model from storage.

        Parameters
        ----------
        path : str
            Path to the model
        spark : :class:`pyspark.sql.SparkSession`
            The current SparkSession
        storage_ref : str
            Identifiers for the model parameters
        """
        HasStorageModel.loadStorages(path, spark, storage_ref, BigTextMatcherModel.databases)

    © Copyright 2022, John Snow Labs.

Created using Sphinx 5.3.0.


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.DataBox.Models
{
    /// <summary> List of unencrypted credentials for accessing device. </summary>
    internal partial class UnencryptedCredentialsList
    {
        /// <summary> Initializes a new instance of UnencryptedCredentialsList. </summary>
        internal UnencryptedCredentialsList()
        {
            Value = new ChangeTrackingList<UnencryptedCredentials>();
        }

        /// <summary> Initializes a new instance of UnencryptedCredentialsList. </summary>
        /// <param name="value"> List of unencrypted credentials. </param>
        /// <param name="nextLink"> Link for the next set of unencrypted credentials. </param>
        internal UnencryptedCredentialsList(IReadOnlyList<UnencryptedCredentials> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> List of unencrypted credentials. </summary>
        public IReadOnlyList<UnencryptedCredentials> Value { get; }
        /// <summary> Link for the next set of unencrypted credentials. </summary>
        public string NextLink { get; }
    }
}


text:
// +build ignore

package main

import (
	"log"

	minio "github.com/minio/minio-go"
)

func main() {
	// Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY, my-testfile, my-bucketname and
	// my-objectname are dummy values, please replace them with original values.

	// Requests are always secure (HTTPS) by default. Set secure=false to enable insecure (HTTP) access.
	// This boolean value is the last argument for New().

	// New returns an Amazon S3 compatible client object. API compatibility (v2 or v4) is automatically
	// determined based on the Endpoint value.
	s3Client, err := minio.New("s3.amazonaws.com", "YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", true)
	if err != nil {
		log.Fatalln(err)
	}

	// Enable trace.
	// s3Client.TraceOn(os.Stderr)

	// Prepare source decryption key (here we assume same key to
	// decrypt all source objects.)
	decKey := minio.NewSSEInfo([]byte{1, 2, 3}, "")

	// Source objects to concatenate. We also specify decryption
	// key for each
	src1 := minio.NewSourceInfo("bucket1", "object1", &decKey)
	src1.SetMatchETagCond("31624deb84149d2f8ef9c385918b653a")

	src2 := minio.NewSourceInfo("bucket2", "object2", &decKey)
	src2.SetMatchETagCond("f8ef9c385918b653a31624deb84149d2")

	src3 := minio.NewSourceInfo("bucket3", "object3", &decKey)
	src3.SetMatchETagCond("5918b653a31624deb84149d2f8ef9c38")

	// Create slice of sources.
	srcs := []minio.SourceInfo{src1, src2, src3}

	// Prepare destination encryption key
	encKey := minio.NewSSEInfo([]byte{8, 9, 0}, "")

	// Create destination info
	dst, err := minio.NewDestinationInfo("bucket", "object", &encKey, nil)
	if err != nil {
		log.Fatalln(err)
	}

	err = s3Client.ComposeObject(dst, srcs)
	if err != nil {
		log.Fatalln(err)
	}

	log.Println("Composed object successfully.")
}