text:
namespace lux {
namespace sys {
namespace gameplay {

	using namespace glm;
	using namespace unit_literals;
	using namespace renderer;

	namespace {
		float dot(vec2 a, vec2 b) {
			return a.x*b.x + a.y*b.y;
		}

		auto round_player_pos(physics::Transform_comp& transform, float alpha) {
			auto pos = remove_units(transform.position());
			auto npos = pos;
			npos.x = std::round(pos.x*10.0f) / 10.f;
			npos.y = std::ceil(pos.y*10.0f) / 10.f;
			transform.position(glm::mix(pos, npos, alpha) * 1_m);
		}
	}

	Gameplay_system::Gameplay_system(Engine& engine, ecs::Entity_manager& ecs,
	                                 physics::Physics_system& physics_world,
	                                 cam::Camera_system& camera_sys,
	                                 controller::Controller_system& controller_sys)
	    : _engine(engine),
	      _ecs(ecs),
	      _mailbox(engine.bus()),
	      _enlightened(ecs.list<Enlightened_comp>()),
	      _players(ecs.list<Player_tag_comp>()),
	      _lamps(ecs.list<Lamp_comp>()),
	      _paints(ecs.list<Paint_comp>()),
	      _finish_marker(ecs.list<Finish_marker_comp>()),
	      _reset_comps(ecs.list<Reset_comp>()),
	      _physics_world(physics_world),
	      _camera_sys(camera_sys),
	      _controller_sys(controller_sys),
	      _rng(util::create_random_generator()) {

		ecs.register_component_type<Collectable_comp>();
		ecs.register_component_type<Reflective_comp>();
		ecs.register_component_type<Paintable_comp>();
		ecs.register_component_type<Paint_comp>();
		ecs.register_component_type<Transparent_comp>();
		ecs.register_component_type<Lamp_comp>();
		ecs.register_component_type<Light_leech_comp>();
		ecs.register_component_type<Prism_comp>();
		ecs.register_component_type<Deadly_comp>();
		ecs.register_component_type<Finish_marker_comp>();
		ecs.register_component_type<Reset_comp>();

		_mailbox.subscribe_to([&](sys::physics::Collision& c) {
			if(!_level_finished) {
				this->_on_collision(c);
			}
		});
		_mailbox.subscribe_to([&](sys::physics::Contact& c) {
			if(!_level_finished) {
				this->_on_contact(c);
			}
		});
		_mailbox.subscribe_to([&](Animation_event& e){
			_on_animation_event(e);
		});

		auto dummy = ecs.emplace("blueprint:player_white"_aid);
		ecs::apply_blueprint(engine.assets(), *dummy, "blueprint:player_red"_aid);
		ecs::apply_blueprint(engine.assets(), *dummy, "blueprint:player_blue"_aid);
		ecs::apply_blueprint(engine.assets(), *dummy, "blueprint:player_green"_aid);
		ecs::apply_blueprint(engine.assets(), *dummy, "blueprint:player_cyan"_aid);
		ecs::apply_blueprint(engine.assets(), *dummy, "blueprint:player_magenta"_aid);
		ecs::apply_blueprint(engine.assets(), *dummy, "blueprint:player_yellow"_aid);
		ecs.erase(dummy);
	}

	void Gameplay_system::_on_contact(sys::physics::Contact& c) {
		if(c.a && c.b && (c.a->has<Player_tag_comp>() || c.b->has<Player_tag_comp>())) {
			auto player = c.a->has<Player_tag_comp>() ? c.a : c.b;
			auto other = c.a!=player ? c.a : c.b;

			if(other->has<Finish_marker_comp>()) {
				auto& marker = other->get<Finish_marker_comp>().get_or_throw();

				auto player_color = Light_color::white;
				player->get<Enlightened_comp>().process([&](auto& e) {
					player_color = e._color;
				});

				auto marker_color = marker._required_color!=Light_color::black || marker._activated ? marker.colors_left() :	Light_color::white;
				auto interactive_part = interactive_color(marker_color, player_color);
				if(interactive_part!=Light_color::black) {
					auto non_interactive_part = not_interactive_color(marker_color, player_color);
					if (non_interactive_part != Light_color::black) {
						_split_player(player->get<Enlightened_comp>().get_or_throw(), {}, non_interactive_part);
						_color_player(player->get<Enlightened_comp>().get_or_throw(), interactive_part);
					}

					player->get<Enlightened_comp>().process([&](auto& e) {
						this->_disable_light(e, false, false);
					});
					player->erase_other<graphic::Anim_sprite_comp, physics::Transform_comp, Reset_comp>();
					player->get<graphic::Anim_sprite_comp>().process([&](auto &s) {
						s.play("exit"_strid);
					});

					marker.add_color(player_color);
					other->get<light::Light_comp>().process([&](auto &l) {
						l.color(to_rgb(marker._contained_colors)*6.f);
					});

					auto markers_left = std::any_of(_finish_marker.begin(), _finish_marker.end(), [](auto &m) {
						return m.colors_left() != Light_color::black;
					});

					if (!markers_left) {
						_level_finished = true;
						_mailbox.send<Level_finished>();
					}
				}
			}
		}
	}

	void Gameplay_system::update_pre_physic(Time dt) {
		_update_light(dt);

		for(auto& lamp : _lamps) {
			if(lamp._cooldown_left>0_s) {
				lamp._cooldown_left -= dt;
			}
		}
	}
	void Gameplay_system::update_post_physic(Time dt) {
		if(_first_update_after_reset) {
			_mailbox.enable();

			for(auto& d : _reset_data) {
				_ecs.restore(d);
			}
			_reset_data.clear();

			if(_players.size()==0) {
				WARN("No players left in level after reload (level file might be compromised)");
				_mailbox.send<Level_finished>();
				return;
			}

			_reset_data.reserve(_reset_comps.size());
			for(Reset_comp& c : _reset_comps) {
				_reset_data.push_back(c.owner().manager().backup(c.owner_ptr()));
			}

			_first_update_after_reset = false;
		}

		_mailbox.update_subscriptions();

		if(_level_finished) {
			return; //< we are done here
		}

		if(_game_timer<=0_s) {
			if(_controller_sys.input_active())
				_game_timer+=dt;
		} else {
			_game_timer += dt;
		}

		if(_players.size()==0) {
			DEBUG("Everyone is dead!");

			reset();
		}

		_camera_sys.active_only(*_controller_sys.get_controlled());
	}
	void Gameplay_system::reset() {
		// set camera to slowly lerp back to player and block input
		_camera_sys.start_slow_lerp(1.0_s);
		_controller_sys.block_input(0.5_s);

		_mailbox.disable();
		for(Reset_comp& c : _reset_comps) {
			c.owner().manager().erase(c.owner_ptr());
		}
		_game_timer = 0_s;
		_first_update_after_reset = true;
		_level_finished = false;
	}

	namespace {
		auto build_lopr(Light_color filter, Light_color pred) {
			return Light_op_res {
				interactive_color(filter, pred),
				not_interactive_color(filter, pred)
			};
		}
	}

	auto Gameplay_system::_is_reflective(glm::vec2 pos, Enlightened_comp& light,
	                                     ecs::Entity* hit) -> Light_op_res {
		if(hit==nullptr)
			return Light_op_res{Light_color::black, Light_color::white};;

		auto ref_res = hit->get<Reflective_comp>().process(Light_op_res{Light_color::black, Light_color::black},
		                                                   [&](auto& r) {
			return build_lopr(r.color(), light._color);
		});

		auto paint_res = hit->get<Paintable_comp>().process(Light_op_res{Light_color::black, Light_color::black},
		                                                   [&](auto&) {
			auto reflected = Light_color::black;

			for(auto& p : _paints) {
				auto interaction = interactive_color(p._color, light._color);

				if(interaction!=Light_color::black) {
					auto& transform = p.owner().get<physics::Transform_comp>().get_or_throw();
					auto paint_pos = remove_units(transform.position()).xy();
					if(glm::length2(paint_pos-pos) < p._radius*p._radius*transform.scale()) {
						reflected = reflected | interaction;
					}
				}
			}

			return Light_op_res{reflected, not_interactive_color(reflected, light._color)};
		});

		return std::max(ref_res, paint_res);
	}
	auto Gameplay_system::_is_solid(Enlightened_comp& light, ecs::Entity* hit) -> Light_op_res {
		if(hit!=nullptr) {
			auto transparent = hit->get<Transparent_comp>();
			if(transparent.is_some()) {
				return !build_lopr(transparent.get_or_throw().color(), light._color);
			}
		}

		return Light_op_res{light._color, Light_color::black};
	}

	void Gameplay_system::_update_light(Time dt) {

		for(Enlightened_comp& c : _enlightened) {
			auto body_mb = c.owner().get<physics::Dynamic_body_comp>();
			if(body_mb.is_nothing() || c._smashed)
				continue;

			auto& transform = c.owner().get<physics::Transform_comp>().get_or_throw();
			auto& body = body_mb.get_or_throw();

			if(c._smash || c._forced_smash) {
				if(c._forced_smash) {
					transform.position(c._last_impact_point);
				}

				_on_smashed(c.owner());
				continue;
			}
			c._forced_smash = false;
			c._last_impact += dt;

			c._direction = glm::normalize(c._direction);

			if(c._state!=Enlightened_State::enabled) {
				c._air_time = 0_s;
			}

			switch(c._state) {
				case Enlightened_State::canceling:
					if(c._was_light) {
						_enable_light(c); //< re-enable
					} else {
						_disable_light(c, false, false); //< re-disable
					}
					break;

				case Enlightened_State::activating:
					if(_physics_world.query_intersection(body, [](ecs::Entity& e){return e.has<Light_leech_comp>();}).is_some()) {
						_disable_light(c, false, false);
					} else {
						if(c._was_light) { // to physical
							_disable_light(c);

						} else { // to light
							_enable_light(c);
						}
					}
					break;

				case Enlightened_State::pending:
					if(_physics_world.query_intersection(body, [](ecs::Entity& e){return e.has<Light_leech_comp>();}).is_some()) {
						_disable_light(c, false, false);
					} else {
						_handle_light_pending(dt, c);
					}
					break;

				case Enlightened_State::disabled:
					_handle_light_disabled(dt, c);
					break;

				case Enlightened_State::enabled:
					_handle_light_enabled(dt, c);
					break;
			}

			auto res_color = c._color;
			for(auto& lamp : _lamps) {
				if(lamp._cooldown_left<=0_s && lamp.in_range(transform.position())) {
					auto new_res_color = lamp.resulting_color(res_color);
					if(new_res_color!=res_color) {
						res_color = new_res_color;
						lamp._cooldown_left = 1_s;
					}
				}
			}
			if(res_color!=c._color) {
				_mailbox.send<Animation_event>("color_sound"_strid, &c.owner());
				_color_player(c, res_color);
			}
		}

		static constexpr auto cam_effect_fade_time = 0.5_s;
		if(_controller_sys.get_controlled()) {
			process(_controller_sys.get_controlled()->get<Enlightened_comp>(),
			        _controller_sys.get_controlled()->get<physics::Dynamic_body_comp>())
			        >> [&](auto& light, auto& body) {
				if(light.enabled()) {
					static constexpr auto cam_fade_time = 1_s;
					_light_timer = cam_fade_time;
					_light_effects_timer = cam_effect_fade_time;
				} else if(_light_effects_timer>0_s) {
					_light_effects_timer -= dt;
				}
				if(_light_timer>0_s && body.grounded()) {
					_light_timer -= dt;
				}
			};
		}

		_camera_sys.motion_blur(_light_effects_timer/cam_effect_fade_time);
		_camera_sys.type(_light_timer>0_s ? cam::Camera_move_type::centered
		                                  : cam::Camera_move_type::lazy);

	}

	void Gameplay_system::_on_collision(sys::physics::Collision& c) {
		if(c.a && c.a->has<Collectable_comp>() && !c.a->get<Collectable_comp>().get_or_throw()._collected) {
			c.a->get<Collectable_comp>().get_or_throw()._collected = true;
			c.a->manager().erase(c.a->shared_from_this());
			return;
		}
		if(c.b && c.b->has<Collectable_comp>() && !c.b->get<Collectable_comp>().get_or_throw()._collected) {
			c.b->get<Collectable_comp>().get_or_throw()._collected = true;
			c.b->manager().erase(c.b->shared_from_this());
			return;
		}

		if(c.a && c.b) {
			process(c.a->get<Enlightened_comp>(), c.b->get<Enlightened_comp>())
			        >> [&](Enlightened_comp& ae, Enlightened_comp& be) {
				if(!ae._smashed && !be._smashed && !ae._smash && !be._smash && !ae.enabled() && !be.enabled()) {
					_color_player(ae, ae._color|be._color);
					c.b->manager().erase(c.b->shared_from_this());
					be._smashed = true;
					c.b = nullptr;
					_controller_sys.set_controlled(ae.owner_ptr());
				}
			};
		}

		auto try_smash = [&](ecs::Entity* e) {
			return e && e->get<Enlightened_comp>().process(false, [&](auto& elc) {
				ecs::Entity* other = (c.a.get()==&elc.owner()) ? c.b.get() : c.a.get();
				auto deadly = other && other->has<Deadly_comp>();
				if((elc._final_booster_left>0_s && c.impact>=elc._smash_force*0.1f) || c.impact>=elc._smash_force || deadly) {
					return elc.smash();
				} else {
					auto fp = c.impact/elc._smash_force;
					if(fp>=0.75f)
						_camera_sys.screen_shake(0.2_s, 0.5f*fp);
					return false;
				}
			});
		};

		try_smash(c.a.get());
		try_smash(c.b.get());
	}
	void Gameplay_system::_on_smashed(ecs::Entity& e) {
		e.get<Enlightened_comp>().process([&](auto& e) {
			e._smashed = true;
		});

		e.get<graphic::Anim_sprite_comp>().process([&](auto& s) {
			s.play("die"_strid);
			e.erase_other<physics::Transform_comp, Enlightened_comp, graphic::Anim_sprite_comp, Player_tag_comp>();

		}).on_nothing([&] {
			WARN("smashed a not animated entity");
			e.manager().erase(e.shared_from_this());
		});

		_camera_sys.screen_shake(0.2_s, 0.5f);
	}
	void Gameplay_system::_on_animation_event(const Animation_event& event) {
		if(!event.owner)
			return;

		auto& e = *static_cast<ecs::Entity*>(event.owner);

		switch(event.name) {
			case "left"_strid:
				e.manager().erase(e.shared_from_this());
				break;

			case "dead"_strid: {
				auto light = e.get<Enlightened_comp>();
				if(light.is_some()) {
					auto& transform = e.get<physics::Transform_comp>().get_or_throw();
					auto color = light.get_or_throw()._color;

					ecs::Entity_ptr blood;

					switch (color) {
						case Light_color::blue:
							blood = _ecs.emplace("blueprint:blood_blue"_aid);
							break;
						case Light_color::cyan:
							blood = _ecs.emplace("blueprint:blood_cyan"_aid);
							break;
						case Light_color::green:
							blood = _ecs.emplace("blueprint:blood_green"_aid);
							break;
						case Light_color::magenta:
							blood = _ecs.emplace("blueprint:blood_magenta"_aid);
							break;
						case Light_color::red:
							blood = _ecs.emplace("blueprint:blood_red"_aid);
							break;
						case Light_color::white:
							blood = _ecs.emplace("blueprint:blood_white"_aid);
							break;
						case Light_color::yellow:
							blood = _ecs.emplace("blueprint:blood_yellow"_aid);
							break;
						case Light_color::black:
							break;
					}

					if(blood) {
						auto& t = blood->get<physics::Transform_comp>().get_or_throw();
						t.position(transform.position());
						t.scale(util::random_real(_rng, 0.8f, 1.0f));
						t.rotation(Angle::from_degrees(util::random_real(_rng, 0.f, 360.f)));
					}
				}

				e.manager().erase(e.shared_from_this());
				break;
			}
		}
	}

	void Gameplay_system::_handle_light_pending(Time, Enlightened_comp& c) {
		if(!c._was_light) {
			c._initial_timer = 0_s;

			auto& body = c.owner().get<physics::Dynamic_body_comp>().get_or_throw();
			body.velocity({0,0});
			body.active(true);
			body.kinematic(true);
			auto& transform = c.owner().get<physics::Transform_comp>().get_or_throw();

			auto angle = Angle{glm::atan(-c._direction.x, c._direction.y)};
			transform.rotation(angle);

			c.owner().get<light::Light_comp>().process([&](auto& l){
				l.brightness_factor(2.f);
			});
			c.owner().get<graphic::Particle_comp>().process([&](auto& particle) {
				if( c._color==Light_color::white)
					particle.add("wlight_effect"_strid);
				else
					particle.add("light_effect"_strid);
			});
		}
	}
	void Gameplay_system::_handle_light_disabled(Time dt, Enlightened_comp& c) {
		auto& body = c.owner().get<physics::Dynamic_body_comp>().get_or_throw();

		body.active(true);
		body.kinematic(false);

		if(body.grounded()) {
			c._air_transforms_left = c._air_transformations;
		}
		if(c._final_booster_left>0_s) {
			body.velocity(c._direction * c._velocity);
			c._final_booster_left -= dt;
		} else {
			c._direction = {0,1};
			// TODO: shouldn't be necessary
			c.owner().get<graphic::Particle_comp>().process([&](auto &particle) {
				particle.remove("light_effect"_strid);
				particle.remove("wlight_effect"_strid);
			});
		}
	}
	void Gameplay_system::_handle_light_enabled(Time dt, Enlightened_comp& c) {
		c._final_booster_left = 0_s;

		auto& transform = c.owner().get<physics::Transform_comp>().get_or_throw();
		auto& body = c.owner().get<physics::Dynamic_body_comp>().get_or_throw();

		body.active(false);
		body.kinematic(false);

		auto pos = remove_units(transform.position());

		auto move_distance = std::abs(c._velocity * dt.value());
		auto direction = c._direction;

		c._initial_timer += dt;
		if(c._initial_timer.value()<=c._initial_booster_time+c._initial_acceleration_time) {
			auto t = c._initial_timer.value();

			auto a_accel = glm::clamp(t/c._initial_acceleration_time, 0.f, 1.f);
			t-=c._initial_acceleration_time;
			move_distance *= a_accel;

			auto a_booster = glm::clamp(t/c._initial_booster_time, 0.f, 1.f);
			move_distance *= 1.0f + (1.f-a_booster)*c._initial_booster_factor;
		}

		float max_ray_dist = c._radius*2.f+move_distance;
		if(max_ray_dist>0.01f) {
			auto ray = _physics_world.raycast(pos.xy(), direction, max_ray_dist, c.owner());

			if(ray.is_some() && ray.get_or_throw().distance-move_distance<=c._radius) {
				if(auto prism = ray.get_or_throw().entity->get<Prism_comp>()) {
					auto prism_pos = ray.get_or_throw().entity->get<physics::Transform_comp>().get_or_throw().position();
					prism_pos.z = pos.z*1_m;

					// TODO: cleanup
					switch(c._color) {
						case Light_color::white:
							transform.position(prism_pos);
							_split_player(c, prism.get_or_throw()._offset_red, Light_color::red)._direction = glm::normalize(remove_units(prism.get_or_throw()._offset_red.xy()));
							_split_player(c, prism.get_or_throw()._offset_green, Light_color::green)._direction = glm::normalize(remove_units(prism.get_or_throw()._offset_green.xy()));
							_color_player(c, Light_color::blue);
							transform.position(prism_pos + prism.get_or_throw()._offset_blue);
							c._direction = glm::normalize(remove_units(prism.get_or_throw()._offset_blue.xy()));
							break;

						case Light_color::cyan:
							transform.position(prism_pos);
							_split_player(c, prism.get_or_throw()._offset_green, Light_color::green)._direction = glm::normalize(remove_units(prism.get_or_throw()._offset_green.xy()));
							_color_player(c, Light_color::blue);
							transform.position(prism_pos + prism.get_or_throw()._offset_blue);
							c._direction = glm::normalize(remove_units(prism.get_or_throw()._offset_blue.xy()));
							break;

						case Light_color::magenta:
							transform.position(prism_pos);
							_split_player(c, prism.get_or_throw()._offset_red, Light_color::red)._direction = glm::normalize(remove_units(prism.get_or_throw()._offset_red.xy()));
							_color_player(c, Light_color::blue);
							transform.position(prism_pos + prism.get_or_throw()._offset_blue);
							c._direction = glm::normalize(remove_units(prism.get_or_throw()._offset_blue.xy()));
							break;

						case Light_color::yellow:
							transform.position(prism_pos);
							_split_player(c, prism.get_or_throw()._offset_red, Light_color::red)._direction = glm::normalize(remove_units(prism.get_or_throw()._offset_red.xy()));
							_color_player(c, Light_color::green);
							transform.position(prism_pos + prism.get_or_throw()._offset_green);
							c._direction = glm::normalize(remove_units(prism.get_or_throw()._offset_green.xy()));
							break;

						default:
							break; // nothing to do
					}

				} else {
					auto solid = _is_solid(c, ray.get_or_throw().entity);
					if(solid.interactive!=Light_color::black) {
						auto interactive = &c;

						if(solid.passive!=Light_color::black) {
							auto offset = Position{direction.x * move_distance, direction.y * move_distance, 0_m};
							interactive = &_split_player(c, {}, solid.interactive);
							_color_player(c, solid.passive);
							transform.move(offset);
						}

						move_distance = ray.get_or_throw().distance - interactive->_radius*2.f;

						auto collision_point = pos.xy()+direction*move_distance;
						auto reflective = _is_reflective(collision_point, *interactive, ray.get_or_throw().entity);

						if(reflective.interactive!=Light_color::black) {
							if(reflective.passive!=Light_color::black) {
								auto offset = Position{direction.x * move_distance, direction.y * move_distance, 0_m};
								auto& new_light = _split_player(*interactive, offset, reflective.passive);
								_disable_light(new_light, true, false);

								_color_player(*interactive, reflective.interactive);
							}

							auto normal = ray.get_or_throw().normal;
							interactive->_direction = interactive->_direction - 2.f*normal*dot(normal, interactive->_direction);
							interactive->_air_time = 0_s;
							c._initial_timer = 0_s;

							_mailbox.send<Animation_event>("reflected"_strid, &c.owner());

						} else {
							_disable_light(*interactive, true, false);
						}

						c._last_impact = c.enabled() ? c._latency_compensation-1_s/60.f : 0_s;
						c._last_impact_point = glm::vec3{
							pos.x+direction.x * move_distance,
							pos.y+direction.y * move_distance,
							pos.z
						} * 1_m;
					}
				}
			}
		}

		pos.x += direction.x * move_distance;
		pos.y += direction.y * move_distance;
		transform.position(pos * 1_m);

		if(c.enabled()) {
			auto angle = Angle{glm::atan(-c._direction.x, c._direction.y)};
			transform.rotation(angle);
		}

		if(c._max_air_time>0.f) {
			c._air_time+=dt;
			if(c._air_time >= c._max_air_time*1_s) {
				_disable_light(c, true, false);
			}
		}
	}

	void Gameplay_system::_enable_light(Enlightened_comp& c) {
		auto& transform = c.owner().get<physics::Transform_comp>().get_or_throw();
		auto& body = c.owner().get<physics::Dynamic_body_comp>().get_or_throw();

		// TODO: change animation/effect
		c._state = Enlightened_State::enabled;
		c._was_light = true;
		round_player_pos(transform, 1.f);
		if(!body.grounded()) {
			c._air_transforms_left--;
		}
	}
	void Gameplay_system::_disable_light(Enlightened_comp& c, bool final_impulse, bool boost) {
		c.owner().get<graphic::Anim_sprite_comp>().process([&](auto& s) {
			s.play("untransform"_strid);
		});

		if(c._state == Enlightened_State::disabled)
			return;

		if(!c.owner().has<physics::Dynamic_body_comp>()
		        || !c.owner().has<physics::Transform_comp>()) {
			return;
		}

		auto& body = c.owner().get<physics::Dynamic_body_comp>().get_or_throw();

		c._state = Enlightened_State::disabled;
		c._was_light = false;

		if(final_impulse) {
			body.velocity(c._direction * c._velocity);
			if(boost) {
				c._final_booster_left = c._final_booster_time * 1_s;
			}
		}

		if(c._final_booster_left <= 0_s) {
			c.owner().get<graphic::Particle_comp>().process([&](auto &particle) {
				particle.remove("light_effect"_strid);
				particle.remove("wlight_effect"_strid);
			});
		}

		auto& transform = c.owner().get<physics::Transform_comp>().get_or_throw();
		transform.rotation(0_deg);

		c.owner().get<light::Light_comp>().process([&](auto& l){
			l.brightness_factor(1.f);
		});
	}

	void Gameplay_system::_color_player(Enlightened_comp& c, Light_color new_color) {
		constexpr auto ns = "blueprint"_strid;
		asset::AID blueprint;

		if(c._color==Light_color::white && new_color!=Light_color::white) {
			c.owner().get<graphic::Particle_comp>().process([&](auto& particle) {
				particle.remove("wlight_effect"_strid);
				particle.add("light_effect"_strid);
			});
		} else if(c._color!=Light_color::white && new_color==Light_color::white) {
			c.owner().get<graphic::Particle_comp>().process([&](auto& particle) {
				particle.add("wlight_effect"_strid);
				particle.remove("light_effect"_strid);
			});
		}

		switch(new_color) {
			case Light_color::black:
				c.owner().manager().erase(c.owner_ptr());
				return;

			case Light_color::red:
				blueprint = asset::AID{ns, "player_red"};
				break;
			case Light_color::green:
				blueprint = asset::AID{ns, "player_green"};
				break;
			case Light_color::blue:
				blueprint = asset::AID{ns, "player_blue"};
				break;

			case Light_color::cyan:
				blueprint = asset::AID{ns, "player_cyan"};
				break;
			case Light_color::magenta:
				blueprint = asset::AID{ns, "player_magenta"};
				break;
			case Light_color::yellow:
				blueprint = asset::AID{ns, "player_yellow"};
				break;

			case Light_color::white:
				blueprint = asset::AID{ns, "player_white"};
				break;
		}

		DEBUG("Colored player in "<<blueprint.name());
		ecs::apply_blueprint(_engine.assets(), c.owner(), blueprint);
	}

	auto Gameplay_system::_split_player(Enlightened_comp& c, Position offset,
										Light_color new_color) -> Enlightened_comp& {
		// TODO[low]: poor-mans clone
		auto n = c.owner().manager().restore(c.owner().manager().backup(c.owner_ptr()));

		auto& nc = n->get<Enlightened_comp>().get_or_throw();
		_color_player(nc, new_color);

		auto& transform = n->get<physics::Transform_comp>().get_or_throw();
		transform.move(offset);

		return nc;
	}

}
}
}


text:
[sciCure](http://fredhasselman.github.io/scicuRe/)
========
### A Toolbox for Curating Scientific Knowledge Extracted from Scientific Publications
#### Tool development for the Curate Science website

*Very BETA version - [Fred Hasselman](http://fredhasselman.com)*

All the functions that are required are available in `scicuRe_source.R`, a package will follow soon.
Use the code below to source it directly from GitHub (the source function was found [here](http://tonybreyal.wordpress.com/2011/11/24/source_https-sourcing-an-r-script-from-github/)). It requires you to install and load the `RCurl` package

```
source_https <- function(url, ...) {
  # load the package
  require(RCurl)

  # parse and evaluate each .R script
  sapply(c(url, ...), function(u) {
    eval(parse(text = getURL(u, followlocation = TRUE, cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl"))), envir = .GlobalEnv)
  })
}

# Source the scicuRe_source.R toolbox!
source_https("https://raw.github.com/FredHasselman/SC-stats/master/scicuRe_source.R")
```

**SEARCH STRATEGY**

 - Need stats labelled for each experiment in a multi-experiment study
 - Need measures of effect size
 - Need aggregate stats, i.e. based on post-hoc power and more
 - Need information to decide if proper analysis was used on stats ([`statcheck`](https://github.com/MicheleNuijten/statcheck) provides some interesting tests!)

*Therefore:*
 - Search is implemented to be driven by the hierarchical structure of an empirical report
 - Structure is: Header (e.g., Experiment 1) -> Section (e.g., Results) -> [Table 1. ->] *STAT OF INTEREST* <- Page number [<- Appendix]
 - Extract as much information as possible!

The `statcheck` package bij M. Nuijten is available [here](https://github.com/MicheleNuijten/statcheck)
Download, unzip and install, e.g. by running:
```
install.packages("~/Downloads/statcheck-master/", repos = NULL, type="source")
```

The authors of `statcheck` note:
> The `pdftotext` program (http://www.foolabs.com/xpdf/download.html) is used to convert PDF files to plain text files. This must be installed and PATH variables must be properly set so that this program can be used from command line.

For the code in this package to execute correctly `pdftotxt` and `pdfinfo` need to be available on your system as well.
Check it now:
```
if(all(file.exists(Sys.which("pdftotext")))) print("YES!") else print("NO!")
```

redpajama_set_name: RedPajamaGithub


text:
// Artificial Slider|ArtificialControllables|120030
namespace VRTK.Controllables.ArtificialBased
{
    using UnityEngine;
    using System.Collections;
    using VRTK.GrabAttachMechanics;
    using VRTK.SecondaryControllerGrabActions;

    /// <summary>
    /// A artificially simulated slider.
    /// </summary>
    /// <remarks>
    /// **Required Components:**
    ///  * `Collider` - A Unity Collider to determine when an interaction has occured. Can be a compound collider set in child GameObjects. Will be automatically added at runtime.
    ///
    /// **Script Usage:**
    ///  * Create a slider container GameObject and set the GameObject that is to become the slider as a child of the container.
    ///  * Place the `VRTK_ArtificialSlider` script onto the GameObject that is to become the slider.
    ///
    ///   > The slider GameObject must not be at the root level and needs to have it's Transform position set to `0,0,0`. This is the reason for the container GameObject requirement. Any positioning of the slider must be set on the parent GameObject.
    /// </remarks>
    [AddComponentMenu("VRTK/Scripts/Interactables/Controllables/Artificial/VRTK_ArtificialSlider")]
    public class VRTK_ArtificialSlider : VRTK_BaseControllable
    {
        [Header("Slider Settings")]

        [Tooltip("The maximum length that the slider can be moved from the origin position across the `Operate Axis`. A negative value will allow it to move the opposite way.")]
        public float maximumLength = 0.1f;
        [Tooltip("The normalized position the slider can be within the minimum or maximum slider positions before the minimum or maximum positions are considered reached.")]
        public float minMaxThreshold = 0.01f;
        [Tooltip("The target position to move the slider towards given in a normalized value of `0f` (start point) to `1f` (end point).")]
        [Range(0f, 1f)]
        [SerializeField]
        protected float positionTarget = 0f;
        [Tooltip("The position the slider when it is at the default resting point given in a normalized value of `0f` (start point) to `1f` (end point).")]
        [Range(0f, 1f)]
        public float restingPosition = 0f;
        [Tooltip("The normalized threshold value the slider has to be within the `Resting Position` before the slider is forced back to the `Resting Position` if it is not grabbed.")]
        [Range(0f, 1f)]
        public float forceRestingPositionThreshold = 0f;

        [Header("Value Step Settings")]

        [Tooltip("The minimum and the maximum step values for the slider to register along the `Operate Axis`.")]
        public Limits2D stepValueRange = new Limits2D(0f, 1f);
        [Tooltip("The increments the slider value will change in between the `Step Value Range`.")]
        public float stepSize = 0.1f;
        [Tooltip("If this is checked then the value for the slider will be the step value and not the absolute position of the slider Transform.")]
        public bool useStepAsValue = true;

        [Header("Snap Settings")]

        [Tooltip("If this is checked then the slider will snap to the position of the nearest step along the value range.")]
        public bool snapToStep = false;
        [Tooltip("The speed in which the slider will snap to the relevant point along the `Operate Axis`")]
        public float snapForce = 10f;

        [Header("Interaction Settings")]

        [Tooltip("The speed in which to track the grabbed slider to the interacting object.")]
        public float trackingSpeed = 25f;
        [Tooltip("If this is checked then when the Interact Grab grabs the Interactable Object, it will grab it with precision and pick it up at the particular point on the Interactable Object that the Interact Touch is touching.")]
        public bool precisionGrab = true;
        [Tooltip("The maximum distance the grabbing object is away from the slider before it is automatically released.")]
        public float detachDistance = 1f;
        [Tooltip("The amount of friction to the slider Rigidbody when it is released.")]
        public float releaseFriction = 10f;
        [Tooltip("A collection of GameObjects that will be used as the valid collisions to determine if the door can be interacted with.")]
        public GameObject[] onlyInteractWith = new GameObject[0];

        protected VRTK_InteractableObject controlInteractableObject;
        protected VRTK_MoveTransformGrabAttach controlGrabAttach;
        protected VRTK_SwapControllerGrabAction controlSecondaryGrabAction;
        protected bool createInteractableObject;
        protected Limits2D axisLimits;
        protected Vector3 previousLocalPosition;
        protected Coroutine setPositionTargetAtEndOfFrameRoutine;
        protected bool stillResting;

        /// <summary>
        /// The GetValue method returns the current position value of the slider.
        /// </summary>
        /// <returns>The actual position of the button.</returns>
        public override float GetValue()
        {
            return transform.localPosition[(int)operateAxis];
        }

        /// <summary>
        /// The GetNormalizedValue method returns the current position value of the slider normalized between `0f` and `1f`.
        /// </summary>
        /// <returns>The normalized position of the button.</returns>
        public override float GetNormalizedValue()
        {
            return VRTK_SharedMethods.NormalizeValue(GetValue(), originalLocalPosition[(int)operateAxis], MaximumLength()[(int)operateAxis]);
        }

        /// <summary>
        /// The GetStepValue method returns the current position of the slider based on the step value range.
        /// </summary>
        /// <param name="currentValue">The current position value of the slider to get the Step Value for.</param>
        /// <returns>The current Step Value based on the slider position.</returns>
        public virtual float GetStepValue(float currentValue)
        {
            return Mathf.Round((stepValueRange.minimum + Mathf.Clamp01(currentValue / maximumLength) * (stepValueRange.maximum - stepValueRange.minimum)) / stepSize) * stepSize;
        }

        /// <summary>
        /// The SetPositionTarget method allows the setting of the `Position Target` parameter at runtime.
        /// </summary>
        /// <param name="newPositionTarget">The new position target value.</param>
        /// <param name="speed">The speed to move to the new position target.</param>
        public virtual void SetPositionTarget(float newPositionTarget, float speed)
        {
            positionTarget = newPositionTarget;
            SetPositionWithNormalizedValue(positionTarget, speed);
        }

        /// <summary>
        /// The SetPositionTargetWithStepValue sets the `Position Target` parameter but uses a value within the `Step Value Range`.
        /// </summary>
        /// <param name="givenStepValue">The step value within the `Step Value Range` to set the `Position Target` parameter to.</param>
        /// <param name="speed">The speed to move to the new position target.</param>
        public virtual void SetPositionTargetWithStepValue(float givenStepValue, float speed)
        {
            SetPositionTarget(VRTK_SharedMethods.NormalizeValue(givenStepValue, stepValueRange.minimum, stepValueRange.maximum), speed);
        }

        /// <summary>
        /// The SetRestingPositionWithStepValue sets the `Resting Position` parameter but uses a value within the `Step Value Range`.
        /// </summary>
        /// <param name="givenStepValue">The step value within the `Step Value Range` to set the `Resting Position` parameter to.</param>
        public virtual void SetRestingPositionWithStepValue(float givenStepValue)
        {
            restingPosition = VRTK_SharedMethods.NormalizeValue(givenStepValue, stepValueRange.minimum, stepValueRange.maximum);
        }

        /// <summary>
        /// The GetPositionFromStepValue returns the position the slider would be at based on the given step value.
        /// </summary>
        /// <param name="givenStepValue">The step value to check the position for.</param>
        /// <returns>The position the slider would be at based on the given step value.</returns>
        public virtual float GetPositionFromStepValue(float givenStepValue)
        {
            float normalizedStepValue = VRTK_SharedMethods.NormalizeValue(givenStepValue, stepValueRange.minimum, stepValueRange.maximum);
            return Mathf.Lerp(axisLimits.minimum, axisLimits.maximum, Mathf.Clamp01(normalizedStepValue));
        }

        /// <summary>
        /// The IsResting method returns whether the slider is at the resting position or within the resting position threshold.
        /// </summary>
        /// <returns>Returns `true` if the slider is at the resting position or within the resting position threshold.</returns>
        public override bool IsResting()
        {
            float currentValue = GetNormalizedValue();
            return (!IsGrabbed() && currentValue <= (restingPosition + forceRestingPositionThreshold) && currentValue >= (restingPosition - forceRestingPositionThreshold));
        }

        /// <summary>
        /// The GetControlInteractableObject method returns the Interactable Object associated with the control.
        /// </summary>
        /// <returns>The Interactable Object associated with the control.</returns>
        public virtual VRTK_InteractableObject GetControlInteractableObject()
        {
            return controlInteractableObject;
        }

        protected override void OnDrawGizmosSelected()
        {
            Vector3 initialPoint = transform.position;
            base.OnDrawGizmosSelected();
            Vector3 destinationPoint = initialPoint + (AxisDirection(true) * maximumLength);
            Gizmos.DrawLine(initialPoint, destinationPoint);
            Gizmos.DrawSphere(initialPoint, 0.01f);
            Gizmos.DrawSphere(destinationPoint, 0.01f);
        }

        protected override void OnEnable()
        {
            base.OnEnable();
            previousLocalPosition = Vector3.one * float.MaxValue;
            stillResting = false;
            SetupInteractableObject();
            setPositionTargetAtEndOfFrameRoutine = StartCoroutine(SetPositionTargetAtEndOfFrameRoutine());
        }

        protected override void OnDisable()
        {
            base.OnDisable();
            ManageInteractableListeners(false);
            if (createInteractableObject)
            {
                Destroy(controlInteractableObject);
            }
            if (setPositionTargetAtEndOfFrameRoutine != null)
            {
                StopCoroutine(setPositionTargetAtEndOfFrameRoutine);
            }
            transform.localPosition = Vector3.zero;
        }

        protected override void EmitEvents()
        {
            bool valueChanged = !VRTK_SharedMethods.Vector3ShallowCompare(transform.localPosition, previousLocalPosition, equalityFidelity);

            if (valueChanged)
            {
                float currentPosition = GetNormalizedValue();
                float minThreshold = minMaxThreshold;
                float maxThreshold = 1f - minMaxThreshold;
                stillResting = false;

                ControllableEventArgs payload = EventPayload();
                OnValueChanged(payload);

                if (currentPosition >= maxThreshold && !AtMaxLimit())
                {
                    atMaxLimit = true;
                    OnMaxLimitReached(payload);
                }
                else if (currentPosition <= minThreshold && !AtMinLimit())
                {
                    atMinLimit = true;
                    OnMinLimitReached(payload);
                }
                else if (currentPosition > minThreshold && currentPosition < maxThreshold)
                {
                    if (AtMinLimit())
                    {
                        OnMinLimitExited(payload);
                    }
                    if (AtMaxLimit())
                    {
                        OnMaxLimitExited(payload);
                    }

                    atMinLimit = false;
                    atMaxLimit = false;
                }
            }

            if (!stillResting && IsResting() && !valueChanged)
            {
                OnRestingPointReached(EventPayload());
                stillResting = true;
            }

            previousLocalPosition = transform.localPosition;
        }

        protected override ControllableEventArgs EventPayload()
        {
            ControllableEventArgs e = base.EventPayload();
            e.value = (useStepAsValue ? GetStepValue(GetValue()) : GetValue());
            return e;
        }

        protected virtual IEnumerator SetPositionTargetAtEndOfFrameRoutine()
        {
            yield return new WaitForEndOfFrame();
            SetPositionTarget(positionTarget, 0f);
            if (snapToStep)
            {
                SetPositionTargetWithStepValue(GetStepValue(GetValue()), snapForce);
            }
            EmitEvents();
        }

        protected virtual void SetupInteractableObject()
        {
            controlInteractableObject = GetComponent<VRTK_InteractableObject>();
            if (controlInteractableObject == null)
            {
                controlInteractableObject = gameObject.AddComponent<VRTK_InteractableObject>();
                controlInteractableObject.isGrabbable = true;
                controlInteractableObject.ignoredColliders = (onlyInteractWith.Length > 0 ? VRTK_SharedMethods.ColliderExclude(GetComponentsInChildren<Collider>(true), VRTK_SharedMethods.GetCollidersInGameObjects(onlyInteractWith, true, true)) : new Collider[0]);
                SetupGrabMechanic();
                SetupSecondaryAction();
            }
            ManageInteractableListeners(true);
        }

        protected virtual void SetupGrabMechanic()
        {
            if (controlInteractableObject != null)
            {
                controlGrabAttach = controlInteractableObject.gameObject.AddComponent<VRTK_MoveTransformGrabAttach>();
                SetGrabMechanicParameters();
                controlInteractableObject.grabAttachMechanicScript = controlGrabAttach;
                ManageGrabbableListeners(true);
                controlGrabAttach.ResetState();
            }
        }

        protected virtual void SetGrabMechanicParameters()
        {
            if (controlGrabAttach != null)
            {
                controlGrabAttach.precisionGrab = precisionGrab;
                controlGrabAttach.releaseDecelerationDamper = releaseFriction;
                axisLimits = new Limits2D(originalLocalPosition[(int)operateAxis], MaximumLength()[(int)operateAxis]);
                switch (operateAxis)
                {
                    case OperatingAxis.xAxis:
                        controlGrabAttach.xAxisLimits = axisLimits;
                        break;
                    case OperatingAxis.yAxis:
                        controlGrabAttach.yAxisLimits = axisLimits;
                        break;
                    case OperatingAxis.zAxis:
                        controlGrabAttach.zAxisLimits = axisLimits;
                        break;
                }
                controlGrabAttach.trackingSpeed = trackingSpeed;
                controlGrabAttach.detachDistance = detachDistance;
            }
        }

        protected virtual void SetupSecondaryAction()
        {
            if (controlInteractableObject != null)
            {
                controlSecondaryGrabAction = controlInteractableObject.gameObject.AddComponent<VRTK_SwapControllerGrabAction>();
                controlInteractableObject.secondaryGrabActionScript = controlSecondaryGrabAction;
            }
        }

        protected virtual Vector3 MaximumLength()
        {
            return originalLocalPosition + (AxisDirection() * maximumLength);
        }

        protected virtual void SetPositionWithNormalizedValue(float givenTargetPosition, float speed)
        {
            float positionOnAxis = Mathf.Lerp(axisLimits.minimum, axisLimits.maximum, Mathf.Clamp01(givenTargetPosition));
            SnapToPosition(positionOnAxis, speed);
        }

        protected virtual void SnapToPosition(float positionOnAxis, float speed)
        {
            if (controlGrabAttach != null)
            {
                controlGrabAttach.SetCurrentPosition((AxisDirection() * Mathf.Sign(maximumLength)) * positionOnAxis, speed);
            }
        }

        protected virtual void ManageInteractableListeners(bool state)
        {
            if (controlInteractableObject != null)
            {
                if (state)
                {
                    controlInteractableObject.InteractableObjectGrabbed += InteractableObjectGrabbed;
                    controlInteractableObject.InteractableObjectUngrabbed += InteractableObjectUngrabbed;
                }
                else
                {
                    controlInteractableObject.InteractableObjectGrabbed -= InteractableObjectGrabbed;
                    controlInteractableObject.InteractableObjectUngrabbed -= InteractableObjectUngrabbed;
                }
            }
        }

        protected virtual void InteractableObjectGrabbed(object sender, InteractableObjectEventArgs e)
        {
            SetGrabMechanicParameters();
        }

        protected virtual void InteractableObjectUngrabbed(object sender, InteractableObjectEventArgs e)
        {
            SetGrabMechanicParameters();
            if (snapToStep)
            {
                SetPositionTargetWithStepValue(GetStepValue(GetValue()), snapForce);
            }

            if (ForceRestingPosition())
            {
                SetPositionWithNormalizedValue(restingPosition, snapForce);
            }
        }

        protected virtual bool ForceRestingPosition()
        {
            return (forceRestingPositionThreshold > 0f && !IsGrabbed() && (Mathf.Abs(restingPosition - GetNormalizedValue()) <= forceRestingPositionThreshold));
        }

        protected virtual bool IsGrabbed()
        {
            return (controlInteractableObject != null && controlInteractableObject.IsGrabbed());
        }

        protected virtual void ManageGrabbableListeners(bool state)
        {
            if (controlGrabAttach != null)
            {
                if (state)
                {
                    controlGrabAttach.TransformPositionChanged += GrabMechanicTransformPositionChanged;
                }
                else
                {
                    controlGrabAttach.TransformPositionChanged -= GrabMechanicTransformPositionChanged;
                }
            }
        }

        protected virtual void GrabMechanicTransformPositionChanged(object sender, MoveTransformGrabAttachEventArgs e)
        {
            EmitEvents();
        }
    }
}


text:
{% set urls = [
  (addon.get_dev_url(), _('Edit Listing'))
] %}

{% if addon.is_packaged %}
  {% do urls.append((addon.get_dev_url('versions'), _('Status & Versions'))) %}
{% else %}
  {% do urls.append((addon.get_dev_url('versions'), _('Status'))) %}
{% endif %}

{% do urls.append(
  (addon.get_dev_url('ratings'), _('Content Ratings'))
) %}

  {% do urls.append((addon.get_dev_url('payments'),
                     _('Compatibility'))) %}
{% do urls.append((addon.get_dev_url('owner'), _('Team Members'))) %}
{% do urls.append((addon.get_url_path(), _('View Listing'))) %}

{% set other_urls = [
  (addon.get_comm_thread_url(), _('Messages')),
  (addon.get_stats_url(), _('Statistics'))
] %}

{% if waffle.switch('view-transactions') %}
  {% do other_urls.append(
    (url('mkt.developers.transactions')|urlparams(app=addon.id), _('Transactions')),
  ) %}
{% endif %}

      {% for url, title in urls %}

          {{ title }}

      {% endfor %}

  {% if other_urls %}

        {% for url, title in other_urls %}

            {{ title }}

        {% endfor %}

  {% endif %}


text:
!-------------------------------------------------------------------------------
!> module PRECISION
!!
!! @par Description
!!          precision module
!!
!! @author NICAM developers
!!
!<
module mod_precision
  !-----------------------------------------------------------------------------
  !
  !++ used modules
  !
  !-----------------------------------------------------------------------------
  implicit none
  private
  !-----------------------------------------------------------------------------
  !
  !++ Public procedure
  !
  !-----------------------------------------------------------------------------
  !
  !++ Public parameters & variables
  !
  !-----------------------------------------------------------------------------
  integer, public, parameter :: SP = kind(0.E0) ! Single Precision: kind(0.E0)
  integer, public, parameter :: DP = kind(0.D0) ! Double Precision: kind(0.D0)

  integer, public, parameter :: SP_PREC = precision(0.E0)
  integer, public, parameter :: DP_PREC = precision(0.D0)

#ifdef SINGLE
  integer, public, parameter :: RP      = SP
  integer, public, parameter :: RP_PREC = SP_PREC
#else
  integer, public, parameter :: RP      = DP
  integer, public, parameter :: RP_PREC = DP_PREC
#endif

  !-----------------------------------------------------------------------------
  !++ Private procedure
  !
  !-----------------------------------------------------------------------------
  !
  !++ Private parameters & variables
  !
  !-----------------------------------------------------------------------------
end module mod_precision
!-------------------------------------------------------------------------------


text:
- Bumped Swift language version to 4.2 with Xcode 10 (10A255)
- Reorganizing project directories and files

## Version 2.1.0
- Added completion handlers after expanding or collapsing cell.

## Version 2.0.1
- Migrated to Swift 4 and Xcode 9.1

## Version 2.0.0

- Updated code for Swift 3
- Updated project for Xcode 8.3.3
- Improvements and refactoring
- Migrated to dynamic framework with example project

## Version 1.0.3

- Minor changes

## Version 1.0.2

- Minor changes

## Version 1.0.1

- Minor changes

## Version 1.0.0

- Initial version


text:
package com.pineone.icbms.so.util.property;

import java.util.*;

/**
 * Property Utility class.

 *
 * Created by uni4love on 2016. 11. 16..
 */
public class PropertyUtils {

    /**
     * return Properties from Map.

     *
     * @param propertiesMap Map
     * @return Properties
     */
    public static Properties getProperties(Map propertiesMap) {
        Properties properties = new Properties();
        properties.putAll(propertiesMap);
        return properties;
    }

    /**
     * return Map<String, String> from Properties.

     *
     * @param properties Properties
     * @return Map<String, String>
     */
    public static Map<String, String> getMapFromProperties(Properties properties) {
        HashMap<String, String> hm = new HashMap<String, String>();
        for (String key : properties.stringPropertyNames())
        {
            hm.put(key, properties.getProperty(key));
        }
        return hm;
    }

}


text:
package vhr.RuinAndRecreateAlgorithm.Ruin;

import vhr.core.VRPInstance;
import vhr.core.VRPSolution;
import vhr.core.VehicleRoute;

import java.util.Collections;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

import static java.util.Collections.*;
import static java.util.Collections.max;

/**
 * Created by quachv on 3/29/2017.
 */
public class RandomRuinStrategy extends AbstractRuinStrategy {

    public RandomRuinStrategy() {
        super();
    }
    @Override
    protected void ruinSolution(VRPInstance vrpInstance, VRPSolution ruinSolution, double ruinRate) {
        int numberOfNodeWillBeRemoved = (int) Math.floor(ruinRate * vrpInstance.getNumberOfCustomers());
        int minCustomerId = min(vrpInstance.getCustomerIds());
        int maxCustomerId = max(vrpInstance.getCustomerIds());

        for (int i = 0; i < numberOfNodeWillBeRemoved; i++) {
            int customerId;
            do {
                customerId = ThreadLocalRandom.current().nextInt(minCustomerId, maxCustomerId + 1);
            } while (vrpInstance.getCustomer(customerId) == null || removedCustomerIds.contains(customerId));
            removedCustomerIds.add(customerId);
        }
    }

    public static class Builder {

        public Builder() {

        }

        public AbstractRuinStrategy build() {
            return new RandomRuinStrategy();
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>TW Career Orientation - May 2016</title>
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <link rel="stylesheet" href="css/app.css" />
    <link rel="stylesheet" href="css/icons/fontello.css" />

Career Orientation Session

Flashback

2nd edition

May 12 2016

Do you have a real Passion for learning? Are you Curious and often challenge your own benchmarks? Do you love to play around with the latest cool technologies? Are you good at solving problems? Do you want to be a part of the technology that is making the world a better place?

You can chat with some of the cool folks in our office who will share with you the tips and tricks of tackling a ThoughtWorks interview ;-)
                    This orientation session will walk you through our recruitment process.
                    Join us for an interactive evening. Snacks and tea is on us!

Agenda

4:00 - 4:10 pm

Keynote: About ThoughtWorks

4:10 - 4:30 pm

Mind the code

4:30 - 5:15 pm

Interactive Panel Discussion: Q&A

5:15 - 5:30 pm

Clean Code: 4 rules of simple design

5:30 - 5:45 pm

Thought leadership at TW

Career Orientation Session » May 12

ThoughtWorks

About

Agenda

                Career Orientation Session sponsored by
                ThoughtWorks

                Built with
                HTML5 Boilerplate,
                Zurb Foundation,
                Skrollr,
                Animate,
                Nanoc &
                Fontello


text:
package net.alexben.Slayer.Listeners;

import net.alexben.Slayer.Core.Events.*;
import net.alexben.Slayer.Core.Objects.Assignment;
import net.alexben.Slayer.Core.Objects.SerialItemStack;
import net.alexben.Slayer.Core.Slayer;
import net.alexben.Slayer.Utilities.ConfigUtil;
import net.alexben.Slayer.Utilities.MiscUtil;
import net.alexben.Slayer.Utilities.PlayerUtil;

import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.FireworkMeta;

public class AssignmentListener implements Listener
{
	@EventHandler(priority = EventPriority.MONITOR)
	private void onTaskAssign(TaskAssignEvent event)
	{
		Player player = event.getPlayer();

		if(player.isOnline())
		{
			MiscUtil.sendMsg(player.getPlayer(), ChatColor.GREEN + MiscUtil.getString("new_assignment"));
			MiscUtil.sendMsg(player.getPlayer(), ChatColor.GRAY + MiscUtil.getString("new_assignment_details").replace("{command}", ChatColor.GOLD + "/sl my tasks" + ChatColor.GRAY));
		}
	}

	@EventHandler(priority = EventPriority.MONITOR)
	private void onAssignmentComplete(AssignmentCompleteEvent event)
	{
		// Define variables
		final Player player = event.getPlayer();
		final Assignment assignment = event.getAssignment();

		// Add the rewards to their reward queue
		for(ItemStack item : assignment.getTask().getItemReward())
		{
			PlayerUtil.addReward(player, new SerialItemStack(item));
		}

		// From this point on, return if the player is offline
		if(!player.isOnline()) return;

		MiscUtil.sendMsg(player, ChatColor.GRAY + MiscUtil.getString("assignment_complete").replace("{task}", ChatColor.AQUA + assignment.getTask().getName() + ChatColor.GRAY));
		MiscUtil.sendMsg(player, ChatColor.GRAY + MiscUtil.getString("rewards_awaiting").replace("{rewards}", ChatColor.YELLOW + "" + PlayerUtil.getRewardAmount(player) + ChatColor.GRAY).replace("{command}", ChatColor.GOLD + "/rewards" + ChatColor.GRAY));

		// Shoot a firework, woohoo!
		if(ConfigUtil.getSettingBoolean("tasks.completion_firework"))
		{
			Firework firework = (Firework) player.getPlayer().getLocation().getWorld().spawnEntity(player.getPlayer().getLocation(), EntityType.FIREWORK);
			FireworkMeta fireworkmeta = firework.getFireworkMeta();
			FireworkEffect.Type type = FireworkEffect.Type.BALL_LARGE;
			FireworkEffect effect = FireworkEffect.builder().flicker(false).withColor(Color.AQUA).withFade(Color.FUCHSIA).with(type).trail(true).build();
			fireworkmeta.addEffect(effect);
			fireworkmeta.setPower(1);
			firework.setFireworkMeta(fireworkmeta);
		}

		// Tracking
		PlayerUtil.addCompletion(player);

		// Handle points and leveling
		PlayerUtil.addPoints(player, assignment.getTask().getValue());

		if(PlayerUtil.getPoints(player) >= PlayerUtil.getPointsGoal(player))
		{
			// Loop and make sure they didn't get a crap-ton of points and if so update accordingly
			while(PlayerUtil.getPoints(player) >= PlayerUtil.getPointsGoal(player))
			{
				SlayerLevelUpEvent levelUpEvent = new SlayerLevelUpEvent(player, PlayerUtil.getLevel(player), PlayerUtil.getLevel(player) + 1);
				Slayer.plugin.getServer().getPluginManager().callEvent(levelUpEvent);

				if(!levelUpEvent.isCancelled())
				{
					// Get rid of the points
					PlayerUtil.subtractPoints(player, PlayerUtil.getPointsGoal(player));

					// Add the level
					PlayerUtil.addLevel(player);

					// Message the player
					MiscUtil.sendMsg(player, ChatColor.GRAY + MiscUtil.getString("level_up_msg1").replace("{level}", ChatColor.LIGHT_PURPLE + "" + PlayerUtil.getLevel(player) + ChatColor.GRAY));
					MiscUtil.sendMsg(player, ChatColor.GRAY + MiscUtil.getString("level_up_msg2").replace("{points}", "" + ChatColor.YELLOW + ((int) PlayerUtil.getPointsGoal(player) - PlayerUtil.getPoints(player)) + ChatColor.GRAY));

					if(ConfigUtil.getSettingBoolean("misc.level_up_firework"))
					{
						// Shoot a random firework!
						MiscUtil.shootRandomFirework(player.getLocation());
					}
				}
			}
		}

		// Update the scoreboard
		PlayerUtil.updateScoreboard(player);
	}

	@EventHandler(priority = EventPriority.MONITOR)
	private void onAssignmentExpire(AssignmentExpireEvent event)
	{
		// Do nothing if they're offline
		if(!event.getOfflinePlayer().isOnline()) return;

		Player player = event.getOfflinePlayer().getPlayer();
		Assignment assignment = event.getAssignment();

		MiscUtil.sendMsg(player, ChatColor.GRAY + MiscUtil.getString("assignment_expired").replace("{task}", ChatColor.AQUA + assignment.getTask().getName() + ChatColor.GRAY));

		// Handle expiration punishment if enabled
		if(ConfigUtil.getSettingBoolean("expiration.punish"))
		{
			// TODO: Update punishments.
		}

		// Tracking
		PlayerUtil.addExpiration(player);

		// Update the scoreboard
		PlayerUtil.updateScoreboard(player);
	}

	@EventHandler(priority = EventPriority.MONITOR)
	private void onAssignmentForfeit(AssignmentForfeitEvent event)
	{
		// Define the variables
		OfflinePlayer player = event.getOfflinePlayer();
		Assignment assignment = event.getAssignment();

		MiscUtil.sendMsg(player, ChatColor.GRAY + MiscUtil.getString("assignment_forfeit").replace("{task}", ChatColor.AQUA + assignment.getTask().getName() + ChatColor.GRAY));

		// Handle punishments if enabled
		if(ConfigUtil.getSettingBoolean("forfeit.punish"))
		{
			// TODO: Update punishments.
		}

		// Tracking
		PlayerUtil.addForfeit(player);

		if(player.isOnline())
		{
			// Update scoreboard
			PlayerUtil.updateScoreboard(player.getPlayer());
		}
	}
}


text:
package org.observe.collect;

import java.util.List;

import org.qommons.IntList;

/**
 * A change event to an ordered collection
 *
 * @param <E> The type of elements in the collection
 */
public class OrderedCollectionChangeEvent<E> extends CollectionChangeEvent<E> {
	/** The indexes of elements that were added, removed, or changed in the collection, in the same order as {@link #values} */
	public IntList indexes;

	/**
	 * @param aType The common type of the changes
	 * @param val The values that were added, removed, or changed in the collection
	 * @param oldVal The old values from the set events
	 * @param idxs The indexes of the elements added, removed, or changed, in the same order as val
	 * @param cause The cause of the event
	 */
	public OrderedCollectionChangeEvent(CollectionChangeType aType, List<E> val, List<E> oldVal, IntList idxs, Object cause) {
		super(aType, val, oldVal, cause);
		indexes = idxs.clone();
		indexes.seal();
	}

	@Override
	public String toString() {
		StringBuilder ret = new StringBuilder();
		switch (type) {
		case add:
			ret.append("added ");
			break;
		case remove:
			ret.append("removed ");
			break;
		case set:
			ret.append("set ");
			break;
		}
		ret.append(" (\n");
		for(int i = 0; i < values.size(); i++) {
			ret.append("\t[").append(indexes.get(i)).append("]: ");
			switch (type) {
			case add:
				ret.append(values.get(i));
				break;
			case remove:
				ret.append(values.get(i));
				break;
			case set:
				ret.append(oldValues.get(i)).append("->").append(values.get(i));
				break;
			}
			ret.append('\n');
		}
		ret.append(')');
		return ret.toString();
	}
}


text:
var STRATEGIES = [
	'class name',
	'css selector',
	'id',
	'name',
	'link text',
	'partial link text',
	'tag name',
	'xpath'
];

var SUFFIXES = STRATEGIES.map(function (strategy) {
	return strategy.replace(/(?:^| )([a-z])/g, function (_, letter) {
		return letter.toUpperCase();
	});
});

STRATEGIES.suffixes = SUFFIXES;
STRATEGIES.applyTo = function (prototype) {
	STRATEGIES.forEach(function (strategy, index) {
		var suffix = SUFFIXES[index];

		prototype['findBy' + suffix] = function (value) {
			return this.find(strategy, value);
		};

		prototype['findDisplayedBy' + suffix] = function (value) {
			return this.findDisplayed(strategy, value);
		};

		prototype['waitForDeletedBy' + suffix] = function (value) {
			return this.waitForDeleted(strategy, value);
		};

		if (strategy !== 'id') {
			prototype['findAllBy' + suffix] = function (value) {
				return this.findAll(strategy, value);
			};
		}
	});
};

STRATEGIES.toW3cLocator = function (using, value) {
	switch (using) {
	case 'id':
		using = 'css selector';
		value = '#' + value;
		break;
	case 'class name':
		using = 'css selector';
		value = '.' + value;
		break;
	case 'name':
		using = 'css selector';
		value = '[name="' + value + '"]';
		break;
	case 'tag name':
		using = 'css selector';
		break;
	}

	return { using: using, value: value };
};

module.exports = STRATEGIES;


text:
package org.radargun.stages.cache.background;

/**
 * Checker used for {@link org.radargun.stages.cache.background.PrivateLogValue non-shared log values}
 *
 * @author Radim Vansa <rvansa@redhat.com>
 */
public class PrivateLogChecker extends LogChecker {

   public PrivateLogChecker(int id, StressorRecordPool pool, BackgroundOpsManager manager) {
      super(manager.getName() + "-Checker-" + id, manager, pool);
   }

   @Override
   protected StressorRecord newRecord(StressorRecord record, long operationId, long seed) {
      return new StressorRecord( record, operationId, seed);
   }

   @Override
   protected Object findValue(StressorRecord record) throws Exception {
      // We cannot atomically get the two vars - the stressor could move backup to main or back between the two
      // gets. But the chance for doing this 100 times is small enough.
      Object value = null;
      long keyId = record.getKeyId();
      for (int i = 0; i < 100; ++i) {
         value = basicCache.get(keyGenerator.generateKey(keyId));
         if (value == null) {
            if (keyId < 0 && record.getCurrentConfirmationTimestamp() < 0) {
               // do not poll it 100x when we're not sure that the operation is written, try just twice
               break;
            }
            keyId = ~keyId;
            if (keyId > 0) {
               // we yield because of the first entry to empty cache
               Thread.yield();
            }
         } else {
            break;
         }
      }
      return value;
   }

   @Override
   protected boolean containsOperation(Object value, StressorRecord record) {
      if (value == null) {
         return false;
      }
      if (!(value instanceof PrivateLogValue)) {
         log.error("Key " + record.getKeyId() + " has unexpected value " + value);
         return false;
      }
      PrivateLogValue logValue = (PrivateLogValue) value;
      if (logValue.getThreadId() == record.getThreadId()) {
         if (logValue.contains(record.getOperationId())) {
            return true;
         }
      } else {
         log.error("Expected value from threadId " + record.getThreadId() + " but found from " + logValue.getThreadId());
      }
      return false;
   }

}


text:
# Copyright 2022 Google LLC
#
# 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.

import json
from pathlib import Path
import shutil

import synthtool as s
import synthtool.gcp as gcp
from synthtool.languages import python

# ----------------------------------------------------------------------------
# Copy the generated client from the owl-bot staging directory
# ----------------------------------------------------------------------------

clean_up_generated_samples = True

# Load the default version defined in .repo-metadata.json.
default_version = json.load(open(".repo-metadata.json", "rt")).get(
    "default_version"
)

for library in s.get_staging_dirs(default_version):
    if clean_up_generated_samples:
        shutil.rmtree("samples/generated_samples", ignore_errors=True)
        clean_up_generated_samples = False
    s.move([library], excludes=["**/gapic_version.py"])
s.remove_staging_dirs()

# Work around gapic generator bug. https://github.com/googleapis/gapic-generator-python/issues/1083
s.replace(
    "google/cloud/**/types/assuredworkloads.py",
    """Signed Access Approvals \(SAA\) enrollment response.\n
        Attributes""",
    """Signed Access Approvals (SAA) enrollment response.\n
        .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields\n
        Attributes"""
)

# ----------------------------------------------------------------------------
# Add templated files
# ----------------------------------------------------------------------------

templated_files = gcp.CommonTemplates().py_library(
    cov_level=100,
    microgenerator=True,
    versions=gcp.common.detect_versions(path="./google", default_first=True),
)
s.move(templated_files, excludes=[".coveragerc", ".github/release-please.yml"])

python.py_samples(skip_readmes=True)

# run format session for all directories which have a noxfile
for noxfile in Path(".").glob("**/noxfile.py"):
    s.shell.run(["nox", "-s", "format"], cwd=noxfile.parent, hide_output=False)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <meta http-equiv="Content-Type"
      content="text/html; charset=windows-1252" />
      <title>
         DNS Service Provider
      </title>
      <link rel="stylesheet" type="text/css" href="../../site.css" />

         DNS Service Provider

Revision History

About this Document

Purpose

Intended Audience

Documentation Conventions

Introduction to DNS Provider

DNS Provider in DRL

About

DNS URL Syntax

Attribute Identifiers

API Mapping

Environment Properties

DNS Resolver

Federation

Appendix: Usage Examples

References

         Revision History

                  Version

                  Version Information

                  Date

                  Initial version

                  Alexei Zakharov, Nadya Morozova: document created.

                  March 23, 2006

                  Formatting update

                  Nadya Morozova

                  September 21, 2006

         About This
         Document

         Purpose

         This document introduces the DRL implementation of the DNS service
         provider for JNDI, the Java* Naming Directory
         Interface. The document gives details on the DNS provider design,
         includes an overall description of the package, and includes helpful
         usage examples. The description documents the first version of the DRL
         DNS service provider deployed in March 2006.

         Intended
         Audience

         The target audience for the document includes a wide community of
         engineers interested in using the DNS service provider for JNDI and in
         further work with the product to contribute to its development. The
         document assumes that readers are familiar with the Java* programming language, the Java*
         Naming Directory Interface, and common concepts of the DNS protocol.

         Documentation Conventions

         This document uses the unified
         conventions for the DRL documentation kit.

         Back to Top

         Introduction to DNS Provider

         The DNS service provider enables Java* applications
         to access information stored in the Domain Name System database by
         means of the Java* Naming and Directory Interface [1]. The provider presents the DNS namespace as a tree
         of JNDI directory contexts, and DNS resource records as JNDI
         attributes.

         Back to Top

         DNS
         Provider in DRL

         This part of the document describes the DRL implementation of the DNS
         provider as a whole and defines the API mapping, environment
         properties usage, and other specific aspects.

         About

         This
         is an independent implementation of the DNS service provider for JNDI.
         More detailed information on JNDI and JNDI service providers can be
         found at [1].

         In DRL, the DNS service provider is a directory context associated
         with a domain name. This way, DNS resource records correspond to JNDI
         attributes. The DNS support functionality is mainly represented by the
         following classes of the
         org.apache.harmony.jndi.provider.dns package:

            The DNSContext class represents the DNS context and
            implements the DirContext interface

            The DNSName class represents DNS names and implements
            the Name interface

            The DNSNameParser class enables parsing DNS names and
            implements the NameParser interface

            The Resolver class and the related set of classes
            contain DNS specific algorithms and protocol messages functionality

         DNS URL Syntax

         The DNS URL, or DNS Pseudo URL, passes the initial information
         to the DNS context as a value for the
         java.naming.provider.url property or as an argument to a
         method of the initial context via the DNS URL provider. The DNS URL is
         defined in the following format:

dns:[//host[:port]][/domain]

         A given combination of host and port
         indicates the DNS server to be used for serving requests about a given
         domain. Given partial data, the following values are used instead of
         missing parameters:

            If host is missing, localhost is used.

            If port is missing, 53 is taken by
            default.

            If host and port are missing, the DNS
            server is set to the default of localhost:53.

            If domain is missing, the root domain .
            is used.

         Back to Top

         Attribute Identifiers

         Because this provider presents DNS resource records in the form of
         JNDI attributes, the exact format of attribute identifiers must be
         defined. These identifiers are accepted by different methods of the
         DNS provider. An identifier consists of the following combination of
         DNS class and type information:

[CLASS_IDENTIFIER] TYPE_IDENTIFIER

         Currently supported class identifiers:

            IN - Internet class

            HS - Hesiod class (not tested)

         Currently supported type identifiers:

            A - address record

            NS - name server record

            CNAME - canonical name for record

            SOA - start of authority record

            PTR - name pointer record

            MX - mail exchange

            TXT - text record

            HINFO - host information

            SRV - location of services record

         If the class identifier is missing, the provider assumes the
         IN class identifier. For an unsupported attribute type,
         calling getAttributes() returns a numerical value rather
         than its type ID. The symbol "" indicates
         ANY type or class, so that an empty string stands for any
         type in any class.

         For more details about DNS resource record classes and types, see RFC
         1035 [2].

         Back to Top

         API Mapping

         The DNSContext class, the main class of the DRL DNS
         provider, implements the DirContext interface. Because
         DNS allows a read-only service, DNSContext provides only
         a part of the overall DirContext functionality.

         Below is the list of supported DirContext methods grouped
         by functionality. All other methods throw
         javax.naming.OperationNotSupportedException.

         Environment operations

         addToEnvironment()

         getEnvironent()

         removeFromEnvironment()

         Operations with DNS names

         composeName()

         getNameInNamespace()

         getNameParser()

         Querying attribute values

         getAttributes()

         This method queries the attribute values from the remote DNS server or
         the local provider's cache.

         Lookup operations

         lookup()

         lookupLink()

         The lookup algorithm works as follows:

            Determines the attribute identifier (ID) contained in the
            org.apache.harmony.jndi.provider.dns.lookup.attr
            property. If the property value contains no attribute identifier,
            the TXT attribute is used.

            Calls getAttributes() to retrieve the values of
            attributes with the identifier determined at step 1 for the
            requested domain name.

            Calls DriverManager.getObjectInstance() to obtain the
            object instance for the requested domain name and the retrieved
            attribute value(s).

            Returns the object instance to the user application.

         Note

         The user object factory must be able to create object instances for an
         object of the
         org.apache.harmony.jndi.provider.dns.DNSContext class [1]. If no object factories have been specified, the
         lookup methods return an instance of DNSContext.

         List operations

         list()

         listBindings()

         These methods list the entire content of the DNS zone via DNS zone
         transfer mechanism.

         Releasing all resources

         close()

         Note

         Currently, this method does nothing because it has nothing to
         release.

         Back to Top

         Environment Properties

         The DNS service provider accepts a number of environment properties as
         shown in the table below.

                  Property Name

                  Function

                  java.naming.authoritative

                  Sets the authoritative bit [2] for all
                  outgoing messages when TRUE.

                  org.apache.harmony.jndi.provider.dns.lookup.attr

                  Specifies the attribute identifier to be used in the lookup algorithm.

                  org.apache.harmony.jndi.provider.dns.recursion

                  Sets the recursion bit for outgoing messages when
                  TRUE.

                  org.apache.harmony.jndi.provider.dns.timeout.initial

                  Indicates the initial timeout.

                     When accessing remote data, the DNS client tries to query
                     all possible remote servers with this value taken as a
                     timeout. If this fails, the client increases the initial
                     timeout value by two times. If this also fails, a value 4
                     times greater than the initial timeout is taken and so on
                     (x8, x16, ... ) until the maximum number of timeout
                     retries is reached, see the description of property
                     org.apache.harmony.jndi.provider.dns.timeout.retries.

                  org.apache.harmony.jndi.provider.dns.timeout.retries

                  Sets the number of timeout retries, that is, the maximum
                  number of retries that can be performed when accessing a
                  remote DNS server.

                     If all attempts fail and the maximum number of retries is
                     reached, the user gets an error message, see the
                     description of property
                     org.apache.harmony.jndi.provider.dns.timeout.initial.

                  org.apache.harmony.jndi.providers.dns.threads.max

                  Determines the maximum number of threads that can be started
                  by a single instance of the DNS context. The default value is
                  7.

                  java.naming.provider.url

                  Enumerates the initial DNS URLs.

                     Multiple URLs must go in a space-separated list, see DNS URL Syntax. During
                     instantiation, the DNS provider fills its internal tables
                     with the given DNS server and controlled domain pairs. The
                     domain part of all URLs must be identical. The newly
                     created DNS context is associated with this domain name.

         Back to Top

         DNS Resolver

         The DRL DNS provider includes an independent fully-functional DNS
         resolver with its own SLIST table and local cache. The SLIST table and
         the cache are singleton classes shared among all instances of the
         resolver. The resolver conforms with RFC 1034 on general principles
         and algorithms used by the resolver, and with RFC 1035 on respective
         records and message formats. The standards RFC 1123, 2181, and 2782
         are also relevant [2].

         Back to Top

         Federation

         The DLR DNS provider has built-in federation support. Implicit next
         naming system is determined dynamically. If the DNS context encounters
         the border of the DNS namespace, it calls the
         DirectoryManager.getContinuationContext(
         ) method and forwards the call to the obtained next naming
         system context.

         Unsupported methods, such as bind() and
         rename(), also perform the initial check. The user gets
         javax.naming.OperationNotSupportedException for these
         methods only if the requested name is entirely inside the DNS
         namespace.

         Back to Top

         Appendix: Usage Examples

         Below is an example of using the provider as the initial context. In
         the example, the DNSContextFactory class is specified as
         the default factory for producing initial contexts.

Hashtable env = new Hashtable();

DirectoryContext ctx;

Attributes attrs;

env.put(Context.INITIAL_CONTEXT_FACTORY,

        "org.apache.harmony.jndi.provider.dns.DNSContextFactory");

env.put(Context.PROVIDER_URL,

        "dns://dns01.example.com/subdomain.example.com");

ctx = new InitialDirContext(env);

// Obtain A and CNAME records for server1.subdomain.example.com

attrs = ctx.getAttributes("server1", new String[] {"A", "CNAME"});

         The provider can also be accessed by passing a DNS URL to any initial
         context method that accepts string arguments. For that, set the
         following property before calling a method of the initial context:

env.put(Context.URL_PKG_PREFIXES, "org.apache.harmony.jndi.provider.dns");

ctx = new InitialDirContext(env);

// Add server with IP address 192.168.1.111 to SLIST as a server

// responsible for serving requests about host11.subdomain.example.com

// Retrieve A and HINFO records for host11.subdomin.example.com

attrs = ctx.getAttributes("dns://192.168.1.111/host11.subdomain.example.com",

                          new String[] {"A", "HINFO"});

         The class dnsURLContext actually serves requests of this
         type.

         Back to Top

         References

         [1] Java* Naming And
         Directory Interface, http://java.sun.com/j2se/1.5.0/docs/guide/jndi/index.html

         [2] Internet Engineering Task Force,
         Requests for Comments, http://www.ietf.org/

         Back to Top

         * Other brands and names are the property of
         their respective owners.


text:
@implementation Callout

@end


text:
package interfaces

import (
	"context"
	"fmt"
	"math/rand"
	"strings"
	"time"

	"github.com/Tinker-Ware/gh-service/domain"
	"github.com/google/go-github/github"
	"golang.org/x/oauth2"

	ghoauth "golang.org/x/oauth2/github"
)

// GithubRepository receives a github client and performs the necessary operations
// within an user account
type GithubRepository struct {
	client      *github.Client
	oauthConfig *oauth2.Config
	context     context.Context
}

// NewGithubRepository initializes the GithubRepository
func NewGithubRepository(clientID, clientSecret string, scopes []string) (*GithubRepository, error) {

	oauth2client := &oauth2.Config{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		Scopes:       scopes,
		Endpoint:     ghoauth.Endpoint,
	}

	rp := &GithubRepository{
		oauthConfig: oauth2client,
		context:     context.Background(),
	}

	return rp, nil
}

// README defines a readme to be written in a repository
var README = domain.File{
	Path:    "README.md",
	Content: []byte("# This is a README"),
}

var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

// GetOauthURL returns the OATH URL based on the configuration
func (repo GithubRepository) GetOauthURL() (string, string) {
	oauthStateString := randSeq(10)
	url := repo.oauthConfig.AuthCodeURL(oauthStateString, oauth2.AccessTypeOnline)
	return url, oauthStateString
}

// GetToken returns a token from Github with the code received from the GET request
func (repo GithubRepository) GetToken(code, givenState, incomingStates string) (*domain.User, error) {

	token, err := repo.oauthConfig.Exchange(oauth2.NoContext, code)
	if err != nil {
		return nil, fmt.Errorf("oauthConf.Exchange() failed with '%s'", err.Error())
	}

	oauthClient := repo.oauthConfig.Client(oauth2.NoContext, token)
	client := github.NewClient(oauthClient)
	user, _, err := client.Users.Get(repo.context, "")
	if err != nil {
		return nil, fmt.Errorf("Cannot retrieve User data: %s", err.Error())
	}

	usr := domain.User{
		Username:       *user.Login,
		AccessToken:    token.AccessToken,
		ExpirationDate: token.Expiry.Unix(),
	}

	return &usr, nil
}

// GetUser retrieves the github user information
func (repo *GithubRepository) GetUser(username string) (*domain.User, error) {
	user, _, err := repo.client.Users.Get(repo.context, username)

	if err != nil {
		return nil, err
	}

	usr := domain.User{
		ID:       *user.ID,
		Username: *user.Login,
	}

	return &usr, nil

}

// SetToken sets the token for the client
func (repo *GithubRepository) SetToken(token string) {

	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: token},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)

	client := github.NewClient(tc)
	repo.client = client

}

// GetAllRepos returns all the repos from an user account
func (repo GithubRepository) GetAllRepos(username string) ([]domain.Repository, error) {

	opt := &github.RepositoryListOptions{
		ListOptions: github.ListOptions{PerPage: 30},
	}

	var allRepos []domain.Repository
	for {
		repos, resp, err := repo.client.Repositories.List(repo.context, "", opt)
		if err != nil {
			return nil, err
		}
		for _, repo := range repos {

			r := domain.Repository{
				Name:        repo.Name,
				FullName:    repo.FullName,
				Description: repo.Description,
				Private:     repo.Private,
				HTMLURL:     repo.HTMLURL,
				CloneURL:    repo.CloneURL,
				SSHURL:      repo.SSHURL,
			}
			allRepos = append(allRepos, r)
		}
		if resp.NextPage == 0 {
			break
		}
		opt.ListOptions.Page = resp.NextPage
	}

	return allRepos, nil
}

// GetRepo gets the information from a single repo
func (repo GithubRepository) GetRepo(username, reponame string) (*domain.Repository, error) {

	rp, _, err := repo.client.Repositories.Get(repo.context, username, reponame)
	if err != nil {
		return nil, err
	}

	r := &domain.Repository{
		Name:        rp.Name,
		FullName:    rp.FullName,
		Description: rp.Description,
		Private:     rp.Private,
		HTMLURL:     rp.HTMLURL,
		CloneURL:    rp.CloneURL,
		SSHURL:      rp.SSHURL,
	}

	return r, nil
}

// CreateRepo creates a repository in the github user account
func (repo GithubRepository) CreateRepo(username, reponame, org string, private bool) (*domain.Repository, error) {
	rp := &github.Repository{
		Name:    github.String(reponame),
		Private: github.Bool(private),
	}
	rp, _, err := repo.client.Repositories.Create(repo.context, org, rp)

	if err != nil {
		return nil, err
	}

	r := &domain.Repository{
		Name:        rp.Name,
		FullName:    rp.FullName,
		Description: rp.Description,
		Private:     rp.Private,
		HTMLURL:     rp.HTMLURL,
		CloneURL:    rp.CloneURL,
		SSHURL:      rp.SSHURL,
	}

	return r, nil
}

// GetKey returns a Key from the user github account
func (repo GithubRepository) GetKey(username string, id int) (*domain.Key, error) {
	ghkey, _, err := repo.client.Users.GetKey(repo.context, id)
	if err != nil {
		return nil, err
	}

	key := &domain.Key{
		ID:    ghkey.ID,
		Title: ghkey.Title,
		Key:   ghkey.Key,
		URL:   ghkey.URL,
	}

	return key, nil
}

// ShowKeys returns all the keys in a user github account
func (repo GithubRepository) ShowKeys(username string) ([]domain.Key, error) {
	ghKeys, _, err := repo.client.Users.ListKeys(repo.context, username, nil)
	if err != nil {
		fmt.Println(err.Error())
		return nil, err
	}

	keys := []domain.Key{}

	for _, k := range ghKeys {
		key := domain.Key{
			ID:    k.ID,
			Key:   k.Key,
			Title: k.Title,
			URL:   k.URL,
		}
		keys = append(keys, key)
	}

	return keys, nil

}

// CreateKey creates a key in the github repository
func (repo GithubRepository) CreateKey(username string, key *domain.Key) error {

	k := github.Key{
		Title: key.Title,
		Key:   key.Key,
	}

	ghK, _, err := repo.client.Users.CreateKey(repo.context, &k)
	if err != nil {
		return err
	}

	key.ID = ghK.ID
	key.URL = ghK.URL

	return nil

}

// CreateFile creates file inside an user repository
func (repo GithubRepository) CreateFile(file domain.File, author domain.Author, username, repoName string) error {

	opt := &github.RepositoryContentFileOptions{
		Message: github.String(author.Message),
		Content: file.Content,
		Branch:  github.String(author.Branch),
		Committer: &github.CommitAuthor{
			Name:  github.String(author.Author),
			Email: github.String(author.Email),
		},
	}

	_, _, err := repo.client.Repositories.CreateFile(repo.context, username, repoName, file.Path, opt)
	if err != nil {
		return err
	}
	return nil
}

// AddFiles inserts multiple files inside a github repository
func (repo GithubRepository) AddFiles(files []domain.File, author domain.Author, username, reponame string) error {
	tree := []github.TreeEntry{}
	emptyRepo := "409 Git Repository is empty"

	// Get the reference sha
	// TODO remove hardcoded branch name
	ghTree, _, err := repo.client.Git.GetRef(repo.context, username, reponame, "heads/master")
	if err != nil {

		// if the repo is empty create a README, else unexpected error
		if strings.Contains(err.Error(), emptyRepo) {

			// Create a copy of author for the initial commit
			author2 := author
			author2.Message = "Initial Commit"

			err = repo.CreateFile(README, author2, username, reponame)
			if err != nil {
				return err
			}

			// Repository should not be empty, otherwise, unexpected error
			ghTree, _, err = repo.client.Git.GetRef(repo.context, username, reponame, "heads/master")
			if err != nil {
				return err
			}

		} else {
			return err

		}

	}
	lastCommit := *ghTree.Ref

	// Create a new tree
	// TODO Check for existing files and paths

	for _, file := range files {
		t := github.TreeEntry{
			Path:    github.String(file.Path),
			Mode:    github.String("100644"),
			Type:    github.String("blob"),
			Content: github.String(string(file.Content)),
		}

		tree = append(tree, t)
	}

	// Get the current tree
	currentTree, _, err := repo.client.Git.GetTree(repo.context, username, reponame, lastCommit, false)
	if err != nil {
		return err
	}

	// Add the existing files to the tree
	for _, file := range currentTree.Entries {
		t := github.TreeEntry{
			Path: file.Path,
			Mode: file.Mode,
			Type: file.Type,
			SHA:  file.SHA,
		}

		tree = append(tree, t)
	}

	newTree, _, err := repo.client.Git.CreateTree(repo.context, username, reponame, *currentTree.SHA, tree)
	if err != nil {
		return err
	}

	commit := github.Commit{
		Message: github.String(author.Message),
		Parents: []github.Commit{{SHA: currentTree.SHA}},
		Tree:    &github.Tree{SHA: newTree.SHA},
	}

	newCommit, _, err := repo.client.Git.CreateCommit(repo.context, username, reponame, &commit)
	if err != nil {
		return err
	}

	reference := github.Reference{
		Ref: github.String("refs/heads/master"),
		Object: &github.GitObject{
			SHA: newCommit.SHA,
		},
	}

	_, _, err = repo.client.Git.UpdateRef(repo.context, username, reponame, &reference, false)
	if err != nil {
		return err
	}

	return nil
}

func (repo GithubRepository) AddDeployKey(username, reponame string, key *domain.Key) error {
	private := true
	k := github.Key{
		Title:    key.Title,
		Key:      key.Key,
		ReadOnly: &private,
	}

	_, _, err := repo.client.Repositories.CreateKey(repo.context, username, reponame, &k)
	return err
}

func randSeq(n int) string {
	rand.Seed(time.Now().UTC().UnixNano())
	b := make([]rune, n)
	for i := range b {
		b[i] = letters[rand.Intn(len(letters))]
	}
	return string(b)
}


text:
cask 'plex-media-player' do
  version '2.58.0.1076-38e019da'
  sha256 '1f0bd7da73891215d44fd17b16ef20d0e9a40d7128828f1561f406221183eb53'

  url "https://downloads.plex.tv/plexmediaplayer/#{version}/PlexMediaPlayer-#{version}-macosx-x86_64.zip"
  appcast 'https://plex.tv/api/downloads/3.json'
  name 'Plex Media Player'
  homepage 'https://www.plex.tv/'

  auto_updates true
  depends_on macos: '>= :yosemite'

  app 'Plex Media Player.app'

  zap trash: [
               '~/Library/Application Support/Plex Media Player',
               '~/Library/Caches/Plex Media Player',
               '~/Library/Logs/Plex Media Player',
               '~/Library/Saved Application State/tv.plex.Plex Media Player.savedState',
               '~/Library/Preferences/tv.plex.Plex Media Player.plist',
             ]
end


text:
import React from 'react';
import classnames from 'classnames';

class Document extends React.Component {
  static propTypes = {
    content: React.PropTypes.object.isRequired,
    className: React.PropTypes.string
  };

  constructor(props) {
    super(props);
  }

  render() {
    const { content, className } = this.props;
    const documentClassName = classnames(className, 'row');

    let availableActions;
    if (content.isUploading === true) {
      availableActions = Loading...;
    } else {
      availableActions = Download;
    }

    return (

            attach_file

            {content.fileName}

              {content.fileSize}
              {content.fileExtension}

              {availableActions}

    );
  }
}

export default Document;


text:
package com.smartg.res;

import com.smartg.java.util.HashBag;

/**
 * ResourceReaderFactory.
 * ResourceReader should register itself by ResourceReaderFactory.
 *
 * @author Andrei Kouznetsov
 * <br>
 *         Date: 15.07.2004
 *         Time: 14:25:50
 */
public class ResourceReaderFactory {
    private HashBag<String, ResourceReader<?>> decoders = new HashBag<String, ResourceReader<?>>();

    public static final ResourceReaderFactory factory = new ResourceReaderFactory();

    private ResourceReaderFactory() {

    }

    /**
     * Register ResourceReader
     * @param p ResourceReader
     * @param type String (resource type)
     */
    public void addProvider(ResourceReader<?> p, String type) {
        decoders.put(type, p);
    }

    /**
     * get array of ResourceReader(s) for given resource type
     * @param type String (resource type)
     * @return ResourceReader array
     */
    public static ResourceReader<?>[] list(String type) {
        int count = factory.decoders.getCount(type);
        ResourceReader<?>[] pps = new ResourceReader[count];
        for(int i = 0; i < pps.length; i++) {
            pps[i] = factory.decoders.get(type, i);
        }
        return pps;
    }

    /**
     * Determine how much ResourceReaders was registered for given resource type
     * @param type String (resource type)
     * @return int
     */
    public static int getProviderCount(String type) {
        return factory.decoders.getCount(type);
    }

    /**
     * get ResourceReader for given resource type at given index
     * @param type String (resource type)
     * @param index index of ResourceReader
     * @return ResourceReader
     */
    public static ResourceReader<?> get(String type, int index) {
        return factory.decoders.get(type, index);
    }

    /**
     * Deregister ResourceReader from factory
     * @param type String (resource type)
     * @param index index of ResourceReader
     * @return ResourceReader
     */
    public static ResourceReader<?> removeProvider(String type, int index) {
        return factory.decoders.remove(type, index);
    }

    static {
        ImageResourceReader p = new ImageResourceReader();
        for(int i = 0; i < ImageResourceReader.types.length; i++) {
            factory.addProvider(p, ImageResourceReader.types[i]);
        }
        ICC_ProfileResourceReader icc = new ICC_ProfileResourceReader();
        for(int i = 0; i < ICC_ProfileResourceReader.types.length; i++) {
            factory.addProvider(icc, ICC_ProfileResourceReader.types[i]);
        }
        PrimitiveResourceReader pri = new PrimitiveResourceReader();
        for(int i = 0; i < PrimitiveResourceReader.types.length; i++) {
            factory.addProvider(pri, PrimitiveResourceReader.types[i]);
        }
    }
}


text:
<form class="form-signin" role="form">

Register

    <input type="text" class="form-control" placeholder="First Name" required autofocus>
    <input type="text" class="form-control" placeholder="Last Name" required>
    <input type="text" class="form-control" placeholder="Email" required>
    <input type="password" class="form-control" placeholder="Password" required>
    <input type="password" class="form-control" placeholder="Confirm Password" required>
    <button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>
</form>


text:
var _ = require('underscore');
var assert = require('assert');

var AuthzAPI = require('oae-authz');
var AuthzTestUtil = require('oae-authz/lib/test/util');
var AuthzUtil = require('oae-authz/lib/util');

describe('Authz Delete', function() {

    /**
     * Test that verifies marking resource ids as deleted works as expected
     */
    it('verify it successfully marks a resource id as deleted', function(callback) {
        var group1 = 'g:oae-ad:d1';
        var group2 = 'g:oae-ad:d2';

        // Verify simple delete works as expected
        AuthzTestUtil.assertSetDeletedSucceeds(group1, function() {

            // Verify isDeleted that contains 1 non-deleted id works as expected
            AuthzTestUtil.assertIsDeletedSucceeds([group1, group2], [group1], function() {

                // Verify we successfully delete the second id
                AuthzTestUtil.assertSetDeletedSucceeds(group2, function() {

                    // Verify isDeleted that contains both deleted ids works as expected
                    return AuthzTestUtil.assertIsDeletedSucceeds([group1, group2], [group1, group2], callback);
                });
            });
        });
    });

    /**
     * Test that verifies restoring resource ids works as expected
     */
    it('verify it successfully restores a resource id', function(callback) {
        var group1 = 'g:oae-ad:r1';
        var group2 = 'g:oae-ad:r2';

        // Delete both groups
        AuthzTestUtil.assertSetDeletedSucceeds(group1, function() {
            AuthzTestUtil.assertSetDeletedSucceeds(group2, function() {

                // Verify simple restore of one id succeeds
                AuthzTestUtil.assertUnsetDeletedSucceeds(group1, function() {

                    // Verify isDeleted that contains 1 restored id works as expected
                    AuthzTestUtil.assertIsDeletedSucceeds([group1, group2], [group2], function() {

                        // Verify we successfully restore the second id
                        AuthzTestUtil.assertUnsetDeletedSucceeds(group2, function() {

                            // Verify isDeleted that contains both restored ids works as expected
                            return AuthzTestUtil.assertIsDeletedSucceeds([group1, group2], [], callback);
                        });
                    });
                });
            });
        });
    });
});