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

#ifndef VISUAL_SERVER_RASTER_H
#define VISUAL_SERVER_RASTER_H

#include "core/math/octree.h"
#include "servers/visual/rasterizer.h"
#include "servers/visual_server.h"
#include "visual_server_canvas.h"
#include "visual_server_globals.h"
#include "visual_server_scene.h"
#include "visual_server_viewport.h"

class VisualServerRaster : public VisualServer {
	enum {

		MAX_INSTANCE_CULL = 8192,
		MAX_INSTANCE_LIGHTS = 4,
		LIGHT_CACHE_DIRTY = -1,
		MAX_LIGHTS_CULLED = 256,
		MAX_ROOM_CULL = 32,
		MAX_EXTERIOR_PORTALS = 128,
		MAX_LIGHT_SAMPLERS = 256,
		INSTANCE_ROOMLESS_MASK = (1 << 20)

	};

	// low and high priority
	static int changes[2];
	RID test_cube;

	int black_margin[4];
	RID black_image[4];

	struct FrameDrawnCallbacks {
		ObjectID object;
		StringName method;
		Variant param;
	};

	List<FrameDrawnCallbacks> frame_drawn_callbacks;

	void _draw_margins();

	// This function is NOT dead code.
	// It is specifically for debugging redraws to help identify problems with
	// undesired constant editor updating.
	// The function will be called in DEV builds (and thus does not require a recompile),
	// allowing you to place a breakpoint either at the first line or the semicolon.
	// You can then look at the callstack to find the cause of the redraw.
	static void _changes_changed(int p_priority) {
		if (p_priority) {
			;
		}
	}

public:
	// if editor is redrawing when it shouldn't, use a DEV build and put a breakpoint in _changes_changed()
	_FORCE_INLINE_ static void redraw_request(bool p_high_priority = true) {
		int priority = p_high_priority ? 1 : 0;
		changes[priority] += 1;
#ifdef DEV_ENABLED
		_changes_changed(priority);
#endif
	}

#ifdef DEV_ENABLED
#define DISPLAY_CHANGED \
	changes[1] += 1;    \
	_changes_changed(1);
#else
#define DISPLAY_CHANGED \
	changes[1] += 1;
#endif

#define BIND0R(m_r, m_name) \
	m_r m_name() { return BINDBASE->m_name(); }
#define BIND1R(m_r, m_name, m_type1) \
	m_r m_name(m_type1 arg1) { return BINDBASE->m_name(arg1); }
#define BIND1RC(m_r, m_name, m_type1) \
	m_r m_name(m_type1 arg1) const { return BINDBASE->m_name(arg1); }
#define BIND2R(m_r, m_name, m_type1, m_type2) \
	m_r m_name(m_type1 arg1, m_type2 arg2) { return BINDBASE->m_name(arg1, arg2); }
#define BIND2RC(m_r, m_name, m_type1, m_type2) \
	m_r m_name(m_type1 arg1, m_type2 arg2) const { return BINDBASE->m_name(arg1, arg2); }
#define BIND3RC(m_r, m_name, m_type1, m_type2, m_type3) \
	m_r m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3) const { return BINDBASE->m_name(arg1, arg2, arg3); }
#define BIND4RC(m_r, m_name, m_type1, m_type2, m_type3, m_type4) \
	m_r m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4) const { return BINDBASE->m_name(arg1, arg2, arg3, arg4); }

#define BIND0N(m_name) \
	void m_name() { BINDBASE->m_name(); }
#define BIND1(m_name, m_type1) \
	void m_name(m_type1 arg1) { DISPLAY_CHANGED BINDBASE->m_name(arg1); }
#define BIND1N(m_name, m_type1) \
	void m_name(m_type1 arg1) { BINDBASE->m_name(arg1); }
#define BIND2(m_name, m_type1, m_type2) \
	void m_name(m_type1 arg1, m_type2 arg2) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2); }
#define BIND2C(m_name, m_type1, m_type2) \
	void m_name(m_type1 arg1, m_type2 arg2) const { BINDBASE->m_name(arg1, arg2); }
#define BIND3(m_name, m_type1, m_type2, m_type3) \
	void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3); }
#define BIND4(m_name, m_type1, m_type2, m_type3, m_type4) \
	void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4); }
#define BIND5(m_name, m_type1, m_type2, m_type3, m_type4, m_type5) \
	void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5); }
#define BIND6(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6) \
	void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6); }
#define BIND7(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6, m_type7) \
	void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6, m_type7 arg7) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6, arg7); }
#define BIND8(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6, m_type7, m_type8) \
	void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6, m_type7 arg7, m_type8 arg8) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); }
#define BIND9(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6, m_type7, m_type8, m_type9) \
	void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6, m_type7 arg7, m_type8 arg8, m_type9 arg9) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); }
#define BIND10(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6, m_type7, m_type8, m_type9, m_type10) \
	void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6, m_type7 arg7, m_type8 arg8, m_type9 arg9, m_type10 arg10) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); }
#define BIND11(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6, m_type7, m_type8, m_type9, m_type10, m_type11) \
	void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6, m_type7 arg7, m_type8 arg8, m_type9 arg9, m_type10 arg10, m_type11 arg11) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); }
#define BIND12(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6, m_type7, m_type8, m_type9, m_type10, m_type11, m_type12) \
	void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6, m_type7 arg7, m_type8 arg8, m_type9 arg9, m_type10 arg10, m_type11 arg11, m_type12 arg12) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12); }
#define BIND13(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6, m_type7, m_type8, m_type9, m_type10, m_type11, m_type12, m_type13) \
	void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6, m_type7 arg7, m_type8 arg8, m_type9 arg9, m_type10 arg10, m_type11 arg11, m_type12 arg12, m_type13 arg13) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13); }

//from now on, calls forwarded to this singleton
#define BINDBASE VSG::storage

	/* TEXTURE API */

	BIND0R(RID, texture_create)
	BIND7(texture_allocate, RID, int, int, int, Image::Format, TextureType, uint32_t)
	BIND3(texture_set_data, RID, const Ref<Image> &, int)
	BIND10(texture_set_data_partial, RID, const Ref<Image> &, int, int, int, int, int, int, int, int)
	BIND2RC(Ref<Image>, texture_get_data, RID, int)
	BIND2(texture_set_flags, RID, uint32_t)
	BIND1RC(uint32_t, texture_get_flags, RID)
	BIND1RC(Image::Format, texture_get_format, RID)
	BIND1RC(TextureType, texture_get_type, RID)
	BIND1RC(uint32_t, texture_get_texid, RID)
	BIND1RC(uint32_t, texture_get_width, RID)
	BIND1RC(uint32_t, texture_get_height, RID)
	BIND1RC(uint32_t, texture_get_depth, RID)
	BIND4(texture_set_size_override, RID, int, int, int)
	BIND2(texture_bind, RID, uint32_t)

	BIND3(texture_set_detect_3d_callback, RID, TextureDetectCallback, void *)
	BIND3(texture_set_detect_srgb_callback, RID, TextureDetectCallback, void *)
	BIND3(texture_set_detect_normal_callback, RID, TextureDetectCallback, void *)

	BIND2(texture_set_path, RID, const String &)
	BIND1RC(String, texture_get_path, RID)
	BIND1(texture_set_shrink_all_x2_on_set_data, bool)
	BIND1(texture_debug_usage, List<TextureInfo> *)

	BIND1(textures_keep_original, bool)

	BIND2(texture_set_proxy, RID, RID)

	BIND2(texture_set_force_redraw_if_visible, RID, bool)

	/* SKY API */

	BIND0R(RID, sky_create)
	BIND3(sky_set_texture, RID, RID, int)

	/* SHADER API */

	BIND0R(RID, shader_create)

	BIND2(shader_set_code, RID, const String &)
	BIND1RC(String, shader_get_code, RID)

	BIND2C(shader_get_param_list, RID, List<PropertyInfo> *)

	BIND3(shader_set_default_texture_param, RID, const StringName &, RID)
	BIND2RC(RID, shader_get_default_texture_param, RID, const StringName &)

	BIND2(shader_add_custom_define, RID, const String &)
	BIND2C(shader_get_custom_defines, RID, Vector<String> *)
	BIND2(shader_remove_custom_define, RID, const String &)

	BIND1(set_shader_async_hidden_forbidden, bool)

	/* COMMON MATERIAL API */

	BIND0R(RID, material_create)

	BIND2(material_set_shader, RID, RID)
	BIND1RC(RID, material_get_shader, RID)

	BIND3(material_set_param, RID, const StringName &, const Variant &)
	BIND2RC(Variant, material_get_param, RID, const StringName &)
	BIND2RC(Variant, material_get_param_default, RID, const StringName &)

	BIND2(material_set_render_priority, RID, int)
	BIND2(material_set_line_width, RID, float)
	BIND2(material_set_next_pass, RID, RID)

	/* MESH API */

	BIND0R(RID, mesh_create)

	BIND10(mesh_add_surface, RID, uint32_t, PrimitiveType, const PoolVector<uint8_t> &, int, const PoolVector<uint8_t> &, int, const AABB &, const Vector<PoolVector<uint8_t>> &, const Vector<AABB> &)

	BIND2(mesh_set_blend_shape_count, RID, int)
	BIND1RC(int, mesh_get_blend_shape_count, RID)

	BIND2(mesh_set_blend_shape_mode, RID, BlendShapeMode)
	BIND1RC(BlendShapeMode, mesh_get_blend_shape_mode, RID)

	BIND4(mesh_surface_update_region, RID, int, int, const PoolVector<uint8_t> &)

	BIND3(mesh_surface_set_material, RID, int, RID)
	BIND2RC(RID, mesh_surface_get_material, RID, int)

	BIND2RC(int, mesh_surface_get_array_len, RID, int)
	BIND2RC(int, mesh_surface_get_array_index_len, RID, int)

	BIND2RC(PoolVector<uint8_t>, mesh_surface_get_array, RID, int)
	BIND2RC(PoolVector<uint8_t>, mesh_surface_get_index_array, RID, int)

	BIND2RC(uint32_t, mesh_surface_get_format, RID, int)
	BIND2RC(PrimitiveType, mesh_surface_get_primitive_type, RID, int)

	BIND2RC(AABB, mesh_surface_get_aabb, RID, int)
	BIND2RC(Vector<PoolVector<uint8_t>>, mesh_surface_get_blend_shapes, RID, int)
	BIND2RC(Vector<AABB>, mesh_surface_get_skeleton_aabb, RID, int)

	BIND2(mesh_remove_surface, RID, int)
	BIND1RC(int, mesh_get_surface_count, RID)

	BIND2(mesh_set_custom_aabb, RID, const AABB &)
	BIND1RC(AABB, mesh_get_custom_aabb, RID)

	BIND1(mesh_clear, RID)

	/* MULTIMESH API */

	BIND0R(RID, multimesh_create)

	BIND5(multimesh_allocate, RID, int, MultimeshTransformFormat, MultimeshColorFormat, MultimeshCustomDataFormat)
	BIND1RC(int, multimesh_get_instance_count, RID)

	BIND2(multimesh_set_mesh, RID, RID)
	BIND3(multimesh_instance_set_transform, RID, int, const Transform &)
	BIND3(multimesh_instance_set_transform_2d, RID, int, const Transform2D &)
	BIND3(multimesh_instance_set_color, RID, int, const Color &)
	BIND3(multimesh_instance_set_custom_data, RID, int, const Color &)

	BIND1RC(RID, multimesh_get_mesh, RID)
	BIND1RC(AABB, multimesh_get_aabb, RID)

	BIND2RC(Transform, multimesh_instance_get_transform, RID, int)
	BIND2RC(Transform2D, multimesh_instance_get_transform_2d, RID, int)
	BIND2RC(Color, multimesh_instance_get_color, RID, int)
	BIND2RC(Color, multimesh_instance_get_custom_data, RID, int)

	BIND2(multimesh_set_as_bulk_array, RID, const PoolVector<float> &)

	BIND3(multimesh_set_as_bulk_array_interpolated, RID, const PoolVector<float> &, const PoolVector<float> &)
	BIND2(multimesh_set_physics_interpolated, RID, bool)
	BIND2(multimesh_set_physics_interpolation_quality, RID, int)
	BIND2(multimesh_instance_reset_physics_interpolation, RID, int)

	BIND2(multimesh_set_visible_instances, RID, int)
	BIND1RC(int, multimesh_get_visible_instances, RID)

	/* IMMEDIATE API */

	BIND0R(RID, immediate_create)
	BIND3(immediate_begin, RID, PrimitiveType, RID)
	BIND2(immediate_vertex, RID, const Vector3 &)
	BIND2(immediate_normal, RID, const Vector3 &)
	BIND2(immediate_tangent, RID, const Plane &)
	BIND2(immediate_color, RID, const Color &)
	BIND2(immediate_uv, RID, const Vector2 &)
	BIND2(immediate_uv2, RID, const Vector2 &)
	BIND1(immediate_end, RID)
	BIND1(immediate_clear, RID)
	BIND2(immediate_set_material, RID, RID)
	BIND1RC(RID, immediate_get_material, RID)

	/* SKELETON API */

	BIND0R(RID, skeleton_create)
	BIND3(skeleton_allocate, RID, int, bool)
	BIND1RC(int, skeleton_get_bone_count, RID)
	BIND3(skeleton_bone_set_transform, RID, int, const Transform &)
	BIND2RC(Transform, skeleton_bone_get_transform, RID, int)
	BIND3(skeleton_bone_set_transform_2d, RID, int, const Transform2D &)
	BIND2RC(Transform2D, skeleton_bone_get_transform_2d, RID, int)
	BIND2(skeleton_set_base_transform_2d, RID, const Transform2D &)

	/* Light API */

	BIND0R(RID, directional_light_create)
	BIND0R(RID, omni_light_create)
	BIND0R(RID, spot_light_create)

	BIND2(light_set_color, RID, const Color &)
	BIND3(light_set_param, RID, LightParam, float)
	BIND2(light_set_shadow, RID, bool)
	BIND2(light_set_shadow_color, RID, const Color &)
	BIND2(light_set_projector, RID, RID)
	BIND2(light_set_negative, RID, bool)
	BIND2(light_set_cull_mask, RID, uint32_t)
	BIND2(light_set_reverse_cull_face_mode, RID, bool)
	BIND2(light_set_use_gi, RID, bool)
	BIND2(light_set_bake_mode, RID, LightBakeMode)

	BIND2(light_omni_set_shadow_mode, RID, LightOmniShadowMode)
	BIND2(light_omni_set_shadow_detail, RID, LightOmniShadowDetail)

	BIND2(light_directional_set_shadow_mode, RID, LightDirectionalShadowMode)
	BIND2(light_directional_set_blend_splits, RID, bool)
	BIND2(light_directional_set_shadow_depth_range_mode, RID, LightDirectionalShadowDepthRangeMode)

	/* PROBE API */

	BIND0R(RID, reflection_probe_create)

	BIND2(reflection_probe_set_update_mode, RID, ReflectionProbeUpdateMode)
	BIND2(reflection_probe_set_intensity, RID, float)
	BIND2(reflection_probe_set_interior_ambient, RID, const Color &)
	BIND2(reflection_probe_set_interior_ambient_energy, RID, float)
	BIND2(reflection_probe_set_interior_ambient_probe_contribution, RID, float)
	BIND2(reflection_probe_set_max_distance, RID, float)
	BIND2(reflection_probe_set_extents, RID, const Vector3 &)
	BIND2(reflection_probe_set_origin_offset, RID, const Vector3 &)
	BIND2(reflection_probe_set_as_interior, RID, bool)
	BIND2(reflection_probe_set_enable_box_projection, RID, bool)
	BIND2(reflection_probe_set_enable_shadows, RID, bool)
	BIND2(reflection_probe_set_cull_mask, RID, uint32_t)
	BIND2(reflection_probe_set_resolution, RID, int)

	/* BAKED LIGHT API */

	BIND0R(RID, gi_probe_create)

	BIND2(gi_probe_set_bounds, RID, const AABB &)
	BIND1RC(AABB, gi_probe_get_bounds, RID)

	BIND2(gi_probe_set_cell_size, RID, float)
	BIND1RC(float, gi_probe_get_cell_size, RID)

	BIND2(gi_probe_set_to_cell_xform, RID, const Transform &)
	BIND1RC(Transform, gi_probe_get_to_cell_xform, RID)

	BIND2(gi_probe_set_dynamic_range, RID, int)
	BIND1RC(int, gi_probe_get_dynamic_range, RID)

	BIND2(gi_probe_set_energy, RID, float)
	BIND1RC(float, gi_probe_get_energy, RID)

	BIND2(gi_probe_set_bias, RID, float)
	BIND1RC(float, gi_probe_get_bias, RID)

	BIND2(gi_probe_set_normal_bias, RID, float)
	BIND1RC(float, gi_probe_get_normal_bias, RID)

	BIND2(gi_probe_set_propagation, RID, float)
	BIND1RC(float, gi_probe_get_propagation, RID)

	BIND2(gi_probe_set_interior, RID, bool)
	BIND1RC(bool, gi_probe_is_interior, RID)

	BIND2(gi_probe_set_compress, RID, bool)
	BIND1RC(bool, gi_probe_is_compressed, RID)

	BIND2(gi_probe_set_dynamic_data, RID, const PoolVector<int> &)
	BIND1RC(PoolVector<int>, gi_probe_get_dynamic_data, RID)

	/* LIGHTMAP CAPTURE */

	BIND0R(RID, lightmap_capture_create)

	BIND2(lightmap_capture_set_bounds, RID, const AABB &)
	BIND1RC(AABB, lightmap_capture_get_bounds, RID)

	BIND2(lightmap_capture_set_octree, RID, const PoolVector<uint8_t> &)
	BIND1RC(PoolVector<uint8_t>, lightmap_capture_get_octree, RID)

	BIND2(lightmap_capture_set_octree_cell_transform, RID, const Transform &)
	BIND1RC(Transform, lightmap_capture_get_octree_cell_transform, RID)
	BIND2(lightmap_capture_set_octree_cell_subdiv, RID, int)
	BIND1RC(int, lightmap_capture_get_octree_cell_subdiv, RID)

	BIND2(lightmap_capture_set_energy, RID, float)
	BIND1RC(float, lightmap_capture_get_energy, RID)

	BIND2(lightmap_capture_set_interior, RID, bool)
	BIND1RC(bool, lightmap_capture_is_interior, RID)

	/* PARTICLES */

	BIND0R(RID, particles_create)

	BIND2(particles_set_emitting, RID, bool)
	BIND1R(bool, particles_get_emitting, RID)
	BIND2(particles_set_amount, RID, int)
	BIND2(particles_set_lifetime, RID, float)
	BIND2(particles_set_one_shot, RID, bool)
	BIND2(particles_set_pre_process_time, RID, float)
	BIND2(particles_set_explosiveness_ratio, RID, float)
	BIND2(particles_set_randomness_ratio, RID, float)
	BIND2(particles_set_custom_aabb, RID, const AABB &)
	BIND2(particles_set_speed_scale, RID, float)
	BIND2(particles_set_use_local_coordinates, RID, bool)
	BIND2(particles_set_process_material, RID, RID)
	BIND2(particles_set_fixed_fps, RID, int)
	BIND2(particles_set_fractional_delta, RID, bool)
	BIND1R(bool, particles_is_inactive, RID)
	BIND1(particles_request_process, RID)
	BIND1(particles_restart, RID)

	BIND2(particles_set_draw_order, RID, VS::ParticlesDrawOrder)

	BIND2(particles_set_draw_passes, RID, int)
	BIND3(particles_set_draw_pass_mesh, RID, int, RID)

	BIND1R(AABB, particles_get_current_aabb, RID)
	BIND2(particles_set_emission_transform, RID, const Transform &)

#undef BINDBASE
//from now on, calls forwarded to this singleton
#define BINDBASE VSG::scene

	/* EVENT QUEUING */

	BIND0N(tick)
	BIND1N(pre_draw, bool)

	/* CAMERA API */

	BIND0R(RID, camera_create)
	BIND4(camera_set_perspective, RID, float, float, float)
	BIND4(camera_set_orthogonal, RID, float, float, float)
	BIND5(camera_set_frustum, RID, float, Vector2, float, float)
	BIND2(camera_set_transform, RID, const Transform &)
	BIND2(camera_set_interpolated, RID, bool)
	BIND1(camera_reset_physics_interpolation, RID)
	BIND2(camera_set_cull_mask, RID, uint32_t)
	BIND2(camera_set_environment, RID, RID)
	BIND2(camera_set_use_vertical_aspect, RID, bool)

#undef BINDBASE
//from now on, calls forwarded to this singleton
#define BINDBASE VSG::viewport

	/* VIEWPORT TARGET API */

	BIND0R(RID, viewport_create)

	BIND2(viewport_set_use_arvr, RID, bool)
	BIND3(viewport_set_size, RID, int, int)

	BIND2(viewport_set_active, RID, bool)
	BIND2(viewport_set_parent_viewport, RID, RID)

	BIND2(viewport_set_clear_mode, RID, ViewportClearMode)

	BIND3(viewport_attach_to_screen, RID, const Rect2 &, int)
	BIND2(viewport_set_render_direct_to_screen, RID, bool)
	BIND1(viewport_detach, RID)

	BIND2(viewport_set_update_mode, RID, ViewportUpdateMode)
	BIND2(viewport_set_vflip, RID, bool)

	BIND1RC(RID, viewport_get_texture, RID)

	BIND2(viewport_set_hide_scenario, RID, bool)
	BIND2(viewport_set_hide_canvas, RID, bool)
	BIND2(viewport_set_disable_environment, RID, bool)
	BIND2(viewport_set_disable_3d, RID, bool)
	BIND2(viewport_set_keep_3d_linear, RID, bool)

	BIND2(viewport_attach_camera, RID, RID)
	BIND2(viewport_set_scenario, RID, RID)
	BIND2(viewport_attach_canvas, RID, RID)

	BIND2(viewport_remove_canvas, RID, RID)
	BIND3(viewport_set_canvas_transform, RID, RID, const Transform2D &)
	BIND2(viewport_set_transparent_background, RID, bool)

	BIND2(viewport_set_global_canvas_transform, RID, const Transform2D &)
	BIND4(viewport_set_canvas_stacking, RID, RID, int, int)
	BIND2(viewport_set_shadow_atlas_size, RID, int)
	BIND3(viewport_set_shadow_atlas_quadrant_subdivision, RID, int, int)
	BIND2(viewport_set_msaa, RID, ViewportMSAA)
	BIND2(viewport_set_use_fxaa, RID, bool)
	BIND2(viewport_set_use_debanding, RID, bool)
	BIND2(viewport_set_sharpen_intensity, RID, float)
	BIND2(viewport_set_hdr, RID, bool)
	BIND2(viewport_set_use_32_bpc_depth, RID, bool)
	BIND2(viewport_set_usage, RID, ViewportUsage)

	BIND2R(int, viewport_get_render_info, RID, ViewportRenderInfo)
	BIND2(viewport_set_debug_draw, RID, ViewportDebugDraw)

	/* ENVIRONMENT API */

#undef BINDBASE
//from now on, calls forwarded to this singleton
#define BINDBASE VSG::scene_render

	BIND0R(RID, environment_create)

	BIND2(environment_set_background, RID, EnvironmentBG)
	BIND2(environment_set_sky, RID, RID)
	BIND2(environment_set_sky_custom_fov, RID, float)
	BIND2(environment_set_sky_orientation, RID, const Basis &)
	BIND2(environment_set_bg_color, RID, const Color &)
	BIND2(environment_set_bg_energy, RID, float)
	BIND2(environment_set_canvas_max_layer, RID, int)
	BIND4(environment_set_ambient_light, RID, const Color &, float, float)
	BIND2(environment_set_camera_feed_id, RID, int)
	BIND7(environment_set_ssr, RID, bool, int, float, float, float, bool)
	BIND13(environment_set_ssao, RID, bool, float, float, float, float, float, float, float, const Color &, EnvironmentSSAOQuality, EnvironmentSSAOBlur, float)

	BIND6(environment_set_dof_blur_near, RID, bool, float, float, float, EnvironmentDOFBlurQuality)
	BIND6(environment_set_dof_blur_far, RID, bool, float, float, float, EnvironmentDOFBlurQuality)
	BIND12(environment_set_glow, RID, bool, int, float, float, float, EnvironmentGlowBlendMode, float, float, float, bool, bool)

	BIND9(environment_set_tonemap, RID, EnvironmentToneMapper, float, float, bool, float, float, float, float)

	BIND6(environment_set_adjustment, RID, bool, float, float, float, RID)

	BIND5(environment_set_fog, RID, bool, const Color &, const Color &, float)
	BIND7(environment_set_fog_depth, RID, bool, float, float, float, bool, float)
	BIND5(environment_set_fog_height, RID, bool, float, float, float)

#undef BINDBASE
#define BINDBASE VSG::scene

	/* INTERPOLATION */

	BIND1(set_physics_interpolation_enabled, bool)

	/* SCENARIO API */

	BIND0R(RID, scenario_create)

	BIND2(scenario_set_debug, RID, ScenarioDebugMode)
	BIND2(scenario_set_environment, RID, RID)
	BIND3(scenario_set_reflection_atlas_size, RID, int, int)
	BIND2(scenario_set_fallback_environment, RID, RID)

	/* INSTANCING API */

	BIND0R(RID, instance_create)

	BIND2(instance_set_base, RID, RID)
	BIND2(instance_set_scenario, RID, RID)
	BIND2(instance_set_layer_mask, RID, uint32_t)
	BIND2(instance_set_transform, RID, const Transform &)
	BIND2(instance_set_interpolated, RID, bool)
	BIND1(instance_reset_physics_interpolation, RID)
	BIND2(instance_attach_object_instance_id, RID, ObjectID)
	BIND3(instance_set_blend_shape_weight, RID, int, float)
	BIND3(instance_set_surface_material, RID, int, RID)
	BIND2(instance_set_visible, RID, bool)
	BIND5(instance_set_use_lightmap, RID, RID, RID, int, const Rect2 &)

	BIND2(instance_set_custom_aabb, RID, AABB)

	BIND2(instance_attach_skeleton, RID, RID)
	BIND2(instance_set_exterior, RID, bool)

	BIND2(instance_set_extra_visibility_margin, RID, real_t)

	/* PORTALS */

	BIND2(instance_set_portal_mode, RID, InstancePortalMode)

	BIND0R(RID, ghost_create)
	BIND4(ghost_set_scenario, RID, RID, ObjectID, const AABB &)
	BIND2(ghost_update, RID, const AABB &)

	BIND0R(RID, portal_create)
	BIND2(portal_set_scenario, RID, RID)
	BIND3(portal_set_geometry, RID, const Vector<Vector3> &, real_t)
	BIND4(portal_link, RID, RID, RID, bool)
	BIND2(portal_set_active, RID, bool)

	/* ROOMGROUPS */

	BIND0R(RID, roomgroup_create)
	BIND2(roomgroup_prepare, RID, ObjectID)
	BIND2(roomgroup_set_scenario, RID, RID)
	BIND2(roomgroup_add_room, RID, RID)

	/* OCCLUDERS */

	BIND0R(RID, occluder_instance_create)
	BIND2(occluder_instance_set_scenario, RID, RID)
	BIND2(occluder_instance_link_resource, RID, RID)
	BIND2(occluder_instance_set_transform, RID, const Transform &)
	BIND2(occluder_instance_set_active, RID, bool)

	BIND0R(RID, occluder_resource_create)
	BIND2(occluder_resource_prepare, RID, OccluderType)
	BIND2(occluder_resource_spheres_update, RID, const Vector<Plane> &)
	BIND2(occluder_resource_mesh_update, RID, const Geometry::OccluderMeshData &)
	BIND1(set_use_occlusion_culling, bool)
	BIND1RC(Geometry::MeshData, occlusion_debug_get_current_polys, RID)

	/* ROOMS */

	BIND0R(RID, room_create)
	BIND2(room_set_scenario, RID, RID)
	BIND4(room_add_instance, RID, RID, const AABB &, const Vector<Vector3> &)
	BIND3(room_add_ghost, RID, ObjectID, const AABB &)
	BIND5(room_set_bound, RID, ObjectID, const Vector<Plane> &, const AABB &, const Vector<Vector3> &)
	BIND2(room_prepare, RID, int32_t)
	BIND1(rooms_and_portals_clear, RID)
	BIND2(rooms_unload, RID, String)
	BIND8(rooms_finalize, RID, bool, bool, bool, bool, String, bool, bool)
	BIND4(rooms_override_camera, RID, bool, const Vector3 &, const Vector<Plane> *)
	BIND2(rooms_set_active, RID, bool)
	BIND3(rooms_set_params, RID, int, real_t)
	BIND3(rooms_set_debug_feature, RID, RoomsDebugFeature, bool)
	BIND2(rooms_update_gameplay_monitor, RID, const Vector<Vector3> &)

	// don't use this in a game
	BIND1RC(bool, rooms_is_loaded, RID)

	// Callbacks
	BIND1(callbacks_register, VisualServerCallbacks *)

	// don't use these in a game!
	BIND2RC(Vector<ObjectID>, instances_cull_aabb, const AABB &, RID)
	BIND3RC(Vector<ObjectID>, instances_cull_ray, const Vector3 &, const Vector3 &, RID)
	BIND2RC(Vector<ObjectID>, instances_cull_convex, const Vector<Plane> &, RID)

	BIND3(instance_geometry_set_flag, RID, InstanceFlags, bool)
	BIND2(instance_geometry_set_cast_shadows_setting, RID, ShadowCastingSetting)
	BIND2(instance_geometry_set_material_override, RID, RID)
	BIND2(instance_geometry_set_material_overlay, RID, RID)

	BIND5(instance_geometry_set_draw_range, RID, float, float, float, float)
	BIND2(instance_geometry_set_as_instance_lod, RID, RID)

#undef BINDBASE
//from now on, calls forwarded to this singleton
#define BINDBASE VSG::canvas

	/* CANVAS (2D) */

	BIND0R(RID, canvas_create)
	BIND3(canvas_set_item_mirroring, RID, RID, const Point2 &)
	BIND2(canvas_set_modulate, RID, const Color &)
	BIND3(canvas_set_parent, RID, RID, float)
	BIND1(canvas_set_disable_scale, bool)

	BIND0R(RID, canvas_item_create)
	BIND2(canvas_item_set_parent, RID, RID)

	BIND2(canvas_item_set_visible, RID, bool)
	BIND2(canvas_item_set_light_mask, RID, int)

	BIND2(canvas_item_set_update_when_visible, RID, bool)

	BIND2(canvas_item_set_transform, RID, const Transform2D &)
	BIND2(canvas_item_set_clip, RID, bool)
	BIND2(canvas_item_set_distance_field_mode, RID, bool)
	BIND3(canvas_item_set_custom_rect, RID, bool, const Rect2 &)
	BIND2(canvas_item_set_modulate, RID, const Color &)
	BIND2(canvas_item_set_self_modulate, RID, const Color &)

	BIND2(canvas_item_set_draw_behind_parent, RID, bool)

	BIND6(canvas_item_add_line, RID, const Point2 &, const Point2 &, const Color &, float, bool)
	BIND5(canvas_item_add_polyline, RID, const Vector<Point2> &, const Vector<Color> &, float, bool)
	BIND5(canvas_item_add_multiline, RID, const Vector<Point2> &, const Vector<Color> &, float, bool)
	BIND3(canvas_item_add_rect, RID, const Rect2 &, const Color &)
	BIND4(canvas_item_add_circle, RID, const Point2 &, float, const Color &)
	BIND7(canvas_item_add_texture_rect, RID, const Rect2 &, RID, bool, const Color &, bool, RID)
	BIND8(canvas_item_add_texture_rect_region, RID, const Rect2 &, RID, const Rect2 &, const Color &, bool, RID, bool)
	BIND11(canvas_item_add_nine_patch, RID, const Rect2 &, const Rect2 &, RID, const Vector2 &, const Vector2 &, NinePatchAxisMode, NinePatchAxisMode, bool, const Color &, RID)
	BIND7(canvas_item_add_primitive, RID, const Vector<Point2> &, const Vector<Color> &, const Vector<Point2> &, RID, float, RID)
	BIND7(canvas_item_add_polygon, RID, const Vector<Point2> &, const Vector<Color> &, const Vector<Point2> &, RID, RID, bool)
	BIND12(canvas_item_add_triangle_array, RID, const Vector<int> &, const Vector<Point2> &, const Vector<Color> &, const Vector<Point2> &, const Vector<int> &, const Vector<float> &, RID, int, RID, bool, bool)
	BIND6(canvas_item_add_mesh, RID, const RID &, const Transform2D &, const Color &, RID, RID)
	BIND4(canvas_item_add_multimesh, RID, RID, RID, RID)
	BIND4(canvas_item_add_particles, RID, RID, RID, RID)
	BIND2(canvas_item_add_set_transform, RID, const Transform2D &)
	BIND2(canvas_item_add_clip_ignore, RID, bool)
	BIND2(canvas_item_set_sort_children_by_y, RID, bool)
	BIND2(canvas_item_set_z_index, RID, int)
	BIND2(canvas_item_set_z_as_relative_to_parent, RID, bool)
	BIND3(canvas_item_set_copy_to_backbuffer, RID, bool, const Rect2 &)
	BIND2(canvas_item_attach_skeleton, RID, RID)

	BIND1(canvas_item_clear, RID)
	BIND2(canvas_item_set_draw_index, RID, int)

	BIND2(canvas_item_set_material, RID, RID)

	BIND2(canvas_item_set_use_parent_material, RID, bool)

	BIND0R(RID, canvas_light_create)
	BIND2(canvas_light_attach_to_canvas, RID, RID)
	BIND2(canvas_light_set_enabled, RID, bool)
	BIND2(canvas_light_set_scale, RID, float)
	BIND2(canvas_light_set_transform, RID, const Transform2D &)
	BIND2(canvas_light_set_texture, RID, RID)
	BIND2(canvas_light_set_texture_offset, RID, const Vector2 &)
	BIND2(canvas_light_set_color, RID, const Color &)
	BIND2(canvas_light_set_height, RID, float)
	BIND2(canvas_light_set_energy, RID, float)
	BIND3(canvas_light_set_z_range, RID, int, int)
	BIND3(canvas_light_set_layer_range, RID, int, int)
	BIND2(canvas_light_set_item_cull_mask, RID, int)
	BIND2(canvas_light_set_item_shadow_cull_mask, RID, int)

	BIND2(canvas_light_set_mode, RID, CanvasLightMode)

	BIND2(canvas_light_set_shadow_enabled, RID, bool)
	BIND2(canvas_light_set_shadow_buffer_size, RID, int)
	BIND2(canvas_light_set_shadow_gradient_length, RID, float)
	BIND2(canvas_light_set_shadow_filter, RID, CanvasLightShadowFilter)
	BIND2(canvas_light_set_shadow_color, RID, const Color &)
	BIND2(canvas_light_set_shadow_smooth, RID, float)

	BIND0R(RID, canvas_light_occluder_create)
	BIND2(canvas_light_occluder_attach_to_canvas, RID, RID)
	BIND2(canvas_light_occluder_set_enabled, RID, bool)
	BIND2(canvas_light_occluder_set_polygon, RID, RID)
	BIND2(canvas_light_occluder_set_transform, RID, const Transform2D &)
	BIND2(canvas_light_occluder_set_light_mask, RID, int)

	BIND0R(RID, canvas_occluder_polygon_create)
	BIND3(canvas_occluder_polygon_set_shape, RID, const PoolVector<Vector2> &, bool)
	BIND2(canvas_occluder_polygon_set_shape_as_lines, RID, const PoolVector<Vector2> &)

	BIND2(canvas_occluder_polygon_set_cull_mode, RID, CanvasOccluderPolygonCullMode)

	/* BLACK BARS */

	virtual void black_bars_set_margins(int p_left, int p_top, int p_right, int p_bottom);
	virtual void black_bars_set_images(RID p_left, RID p_top, RID p_right, RID p_bottom);

	/* FREE */

	virtual void free(RID p_rid); ///< free RIDs associated with the visual server

	/* EVENT QUEUING */

	virtual void request_frame_drawn_callback(Object *p_where, const StringName &p_method, const Variant &p_userdata);

	virtual void draw(bool p_swap_buffers, double frame_step);
	virtual void sync();
	virtual bool has_changed(ChangedPriority p_priority = CHANGED_PRIORITY_ANY) const;
	virtual void init();
	virtual void finish();

	/* STATUS INFORMATION */

	virtual uint64_t get_render_info(RenderInfo p_info);
	virtual String get_video_adapter_name() const;
	virtual String get_video_adapter_vendor() const;

	virtual RID get_test_cube();

	/* TESTING */

	virtual void set_boot_image(const Ref<Image> &p_image, const Color &p_color, bool p_scale, bool p_use_filter = true);
	virtual void set_default_clear_color(const Color &p_color);
	virtual void set_shader_time_scale(float p_scale);

	virtual bool has_feature(Features p_feature) const;

	virtual bool has_os_feature(const String &p_feature) const;
	virtual void set_debug_generate_wireframes(bool p_generate);

	virtual void call_set_use_vsync(bool p_enable);

	virtual bool is_low_end() const;

	VisualServerRaster();
	~VisualServerRaster();

#undef DISPLAY_CHANGED

#undef BIND0R
#undef BIND1RC
#undef BIND2RC
#undef BIND3RC
#undef BIND4RC

#undef BIND1
#undef BIND2
#undef BIND3
#undef BIND4
#undef BIND5
#undef BIND6
#undef BIND7
#undef BIND8
#undef BIND9
#undef BIND10
};

#endif // VISUAL_SERVER_RASTER_H


text:
import { combineReducers } from 'redux';
import user from './user';
import runtime from './runtime';
import tweet from './tweet';

export default combineReducers({
  user,
  runtime,
  tweet,
});

redpajama_set_name: RedPajamaGithub


text: require 'activerecord/abstract_adapter_ext'


text:
package eta.runtime.stg;

import eta.runtime.Runtime;
import eta.runtime.thunk.*;
import eta.runtime.exception.TrampolineBounceException;
import static eta.runtime.RuntimeLogging.*;

public class Stg {
    /* Weak Pointer Operations */
    public static WeakPtr mkWeak(StgContext context, Closure key, Closure value, Closure finalizer) {
        return WeakPtr.create(key, value, finalizer);
    }

    public static WeakPtr mkWeakNoFinalizer(StgContext context, Closure key, Closure value) {
        return mkWeak(context, key, value, null);
    }

    public static int addJavaFinalizerToWeak(StgContext context, long fptr, long ptr, int flag, long eptr, WeakPtr w) {
        JavaFinalizer jfinalizer = new JavaFinalizer(flag != 0, fptr, ptr, eptr);
        if (w.isDead()) {
            return 0;
        } else {
            w.addJavaFinalizer(jfinalizer);
            return 1;
        }
    }

    public static Closure finalizeWeak(StgContext context, WeakPtr w) {
        w.lock();
        if (w.isDead()) {
            w.unlock();
            context.I1 = 0;
            return null;
        } else {
            w.die();
            w.unlock();
            w.runJavaFinalizers();
            Closure finalizer = w.finalizer;
            if (finalizer == null) {
                context.I1 = 0;
                return null;
            } else {
                context.I1 = 1;
                return finalizer;
            }
        }
    }

    public static Closure deRefWeak(StgContext context, WeakPtr w) {
        if (!w.tryLock()) {
            w.lock();
        }
        w.unlock();
        if (w.isDead()) {
            context.I1 = 0;
            return null;
        } else {
            context.I1 = 1;
            return w.getValue();
        }
    }

    public static void noDuplicate(StgContext context) {
        if (!Capability.singletonCapabilities()) {
            Capability cap = context.myCapability;
            TSO tso = context.currentTSO;
            cap.threadPaused(tso);
        }
    }

    /* Trampolining Implementation */

    public static final ThreadLocal<TrampolineBounceException> bounce =
        new ThreadLocal<TrampolineBounceException>() {
            @Override
            public TrampolineBounceException initialValue() {
                return new TrampolineBounceException();
            }
        };

    public static Closure trampoline(final StgContext context, final Closure closure) {
        if (!(closure instanceof Thunk) && !(closure instanceof DataCon)) {
            final Class<?> clazz = closure.getClass();
            throw new IllegalStateException
                ("The trampoline function expects a thunk or data constructor and not a function ["
                 + clazz + " extends "
                 + clazz.getSuperclass() + "]");
        }
        int     tailCalls  = context.tailCalls;
        Closure ret        = null;
        Closure next       = closure;
        boolean trampoline = context.trampoline;
        context.trampoline = true;
        final boolean debug = Runtime.debugTailCalls();
        if (debug) {
            debugTailCalls("Starting trampoline for " + Print.classAndIdentity(closure));
        }
        while (next != null) {
            context.tailCalls = 0;
            context.firstTime = true;
            try {
                ret  = next.enter(context);
                next = null;
            } catch (Throwable e) {
                if (e instanceof TrampolineBounceException) {
                    next = context.next;
                    if (debug) {
                        debugTailCalls("Bounced with " + Print.classAndIdentity(next));
                    }
                } else {
                    if (debug) {
                        debugTailCalls("Exiting trampoline with exception " +
                                       Print.classAndIdentity(e) + " after " + context.tailCalls +
                                       " tail calls.");
                    }
                    context.failTrampoline(e);
                    context.resetTrampoline(tailCalls, trampoline);
                    throw e;
                }
            }
        }
        if (debug) {
            debugTailCalls("Exiting trampoline sucessfully with result " +
                           Print.classAndIdentity(ret) + " after " + context.tailCalls +
                           " tail calls.");
        }
        context.finalizeTrampoline(ret);
        context.resetTrampoline(tailCalls, trampoline);
        return ret;
    }

    public static Closure trampolineIO(final StgContext context, final Closure io) {
        return trampoline(context, new ApV(io));
    }

    public static void evaluateTail(StgContext context, Closure node) {
        if (Runtime.debugTailCalls()) {
            debugTailCalls("evaluateTail: " + node.getClass());
        }
        if (context.checkTailCalls()) {
            context.next = new Ap1Upd(node);
            throw bounce.get();
        }
    }

    public static void enterTail(StgContext context, Closure node) {
        if (context.checkTailCalls()) {
            context.next = node;
            throw bounce.get();
        }
    }

    // TODO: Replace Ap* with Ap*NonUpd to avoid overhead of evaluate()
    public static void applyVTail(StgContext context, Closure node) {
        if (context.checkTailCalls()) {
            context.next = new Ap1VUpd(node);
            throw bounce.get();
        }
    }

    public static void applyNTail(StgContext context, Closure node, int n) {
        if (context.checkTailCalls()) {
            context.next = new ApI(node, n);
            throw bounce.get();
        }
    }

    public static void applyLTail(StgContext context, Closure node, long l) {
        if (context.checkTailCalls()) {
            context.next = new ApL(node, l);
            throw bounce.get();
        }
    }

    public static void applyFTail(StgContext context, Closure node, float f) {
        if (context.checkTailCalls()) {
            context.next = new ApF(node, f);
            throw bounce.get();
        }
    }

    public static void applyDTail(StgContext context, Closure node, double d) {
        if (context.checkTailCalls()) {
            context.next = new ApD(node, d);
            throw bounce.get();
        }
    }

    public static void applyOTail(StgContext context, Closure node, Object o) {
        if (context.checkTailCalls()) {
            context.next = new ApO(node, o);
            throw bounce.get();
        }
    }

    public static void apply1Tail(StgContext context, Closure node, Closure p) {
        if (context.checkTailCalls()) {
            context.next = new Ap2Upd(node, p);
            throw bounce.get();
        }
    }

    public static void apply1VTail(StgContext context, Closure node, Closure p) {
        if (context.checkTailCalls()) {
            context.next = new Ap2VUpd(node, p);
            throw bounce.get();
        }
    }

    public static void apply2Tail(StgContext context, Closure node, Closure p1, Closure p2) {
        if (context.checkTailCalls()) {
            context.next = new Ap3Upd(node, p1, p2);
            throw bounce.get();
        }
    }

    public static void apply2VTail(StgContext context, Closure node, Closure p1, Closure p2) {
        if (context.checkTailCalls()) {
            context.next = new Ap3VUpd(node, p1, p2);
            throw bounce.get();
        }
    }

    public static void apply3Tail(StgContext context, Closure node, Closure p1, Closure p2, Closure p3) {
        if (context.checkTailCalls()) {
            context.next = new Ap4Upd(node, p1, p2, p3);
            throw bounce.get();
        }
    }

    public static void apply3VTail(StgContext context, Closure node, Closure p1, Closure p2, Closure p3) {
        if (context.checkTailCalls()) {
            context.next = new Ap4VUpd(node, p1, p2, p3);
            throw bounce.get();
        }
    }

    public static void apply4Tail(StgContext context, Closure node, Closure p1, Closure p2, Closure p3, Closure p4) {
        if (context.checkTailCalls()) {
            context.next = new Ap5Upd(node, p1, p2, p3, p4);
            throw bounce.get();
        }
    }

    public static void apply5Tail(StgContext context, Closure node, Closure p1, Closure p2, Closure p3, Closure p4, Closure p5) {
        if (context.checkTailCalls()) {
            context.next = new Ap6Upd(node, p1, p2, p3, p4, p5);
            throw bounce.get();
        }
    }

    public static void apply6Tail(StgContext context, Closure node, Closure p1, Closure p2, Closure p3, Closure p4, Closure p5, Closure p6) {
        if (context.checkTailCalls()) {
            context.next = new Ap7Upd(node, p1, p2, p3, p4, p5, p6);
            throw bounce.get();
        }
    }
}


text:
#include "config.h"
#include "JSCustomPositionCallback.h"

#if ENABLE(GEOLOCATION)

#include "Frame.h"
#include "JSGeoposition.h"
#include <runtime/JSLock.h>

namespace WebCore {

using namespace JSC;

JSCustomPositionCallback::JSCustomPositionCallback(JSObject* callback, JSDOMGlobalObject* globalObject)
    : PositionCallback(globalObject->scriptExecutionContext())
    , m_data(callback, globalObject)
{
}

void JSCustomPositionCallback::handleEvent(Geoposition* geoposition)
{
    // ActiveDOMObject will null our pointer to the ScriptExecutionContext when it goes away.
    if (!scriptExecutionContext())
        return;

    RefPtr<JSCustomPositionCallback> protect(this);

    JSC::JSLock lock(SilenceAssertionsOnly);
    ExecState* exec = m_data.globalObject()->globalExec();
    MarkedArgumentBuffer args;
    args.append(toJS(exec, deprecatedGlobalObjectForPrototype(exec), geoposition));
    m_data.invokeCallback(args);
}

} // namespace WebCore

#endif // ENABLE(GEOLOCATION)


text:
package com.sun.media.sound;

import java.io.IOException;

/**
 * Resampler stream interface.
 *
 * @author Karl Helgason
 */
public interface SoftResamplerStreamer extends ModelOscillatorStream {

    void open(ModelWavetable osc, float outputsamplerate) throws IOException;
}


text:
cask "rider" do
  version "2021.1,211.6693.105"
  sha256 "d7e1a814128e874288026a100fc564b30de836c984f6b0fbfee8b22ff2c65e65"

  url "https://download.jetbrains.com/rider/JetBrains.Rider-#{version.before_comma}.dmg"
  appcast "https://data.services.jetbrains.com/products/releases?code=RD&latest=true&type=release"
  name "Jetbrains Rider"
  desc "Cross-Platform .NET IDE"
  homepage "https://www.jetbrains.com/rider/"

  auto_updates true

  app "Rider.app"

  uninstall_postflight do
    ENV["PATH"].split(File::PATH_SEPARATOR).map { |path| File.join(path, "rider") }.each do |path|
      if File.exist?(path) &&
         File.readlines(path).grep(/# see com.intellij.idea.SocketLock for the server side of this interface/).any?
        File.delete(path)
      end
    end
  end

  zap trash: [
    "~/Library/Application Support/Rider#{version.major_minor}",
    "~/Library/Caches/Rider#{version.major_minor}",
    "~/Library/Logs/Rider#{version.major_minor}",
    "~/Library/Preferences/Rider#{version.major_minor}",
    "~/Library/Preferences/jetbrains.rider.71e559ef.plist",
    "~/Library/Saved Application State/com.jetbrains.rider.savedState",
  ]
end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/normalize.css">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/main.css">
  <link rel="stylesheet" href="app.css">

Round {{currentRound}}

        <button id="start" ng-click="start()">Start</button>
        <button id="pause" ng-click="pause()">{{ isRunning ? "Pause" : "Unpause" }}</button>
        <button id="stop" ng-click="stop()">Stop</button>

GyroZ

    <canvas id="gyroCanvas" width={{width}} height="250"></canvas>

Power - Speed

    <canvas id="speedCanvas" width={{width}} height="250"></canvas>

Round Times: Best = {{ lowestRoundTime > 0 && lowestRoundTime < 999999 ? lowestRoundTime : "-" }}


text:
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.

#include "PxScene.h"
#include "PxQueryReport.h"
#include "PxBatchQueryDesc.h"
#include "extensions/PxJoint.h"
#include "PxRigidDynamic.h"
#include "extensions/PxDistanceJoint.h"
#include "extensions/PxSphericalJoint.h"
#include "PxArticulationLink.h"
#include "PxShape.h"
#include "Picking.h"
#include "RendererMemoryMacros.h"

#if defined(PX_X360) || defined(PX_LINUX) || defined(PX_APPLE)
#include <stdio.h>
#endif

using namespace physx;	// PT: please DO NOT indent the whole file

Picking::Picking(PhysXSample& frame) :
	mSelectedActor		(NULL),
	mMouseJoint			(NULL),
	mMouseActor			(NULL),
	mMouseActorToDelete	(NULL),
	mDistanceToPicked	(0.0f),
	mMouseScreenX		(0),
	mMouseScreenY		(0),
	mFrame				(frame)
{
}
Picking::~Picking() {}

bool Picking::isPicked() const
{
	return mMouseJoint!=0;
}

void Picking::moveCursor(PxI32 x, PxI32 y)
{
	mMouseScreenX = x;
	mMouseScreenY = y;
}

/*void Picking::moveCursor(PxReal deltaDepth)
{
	const PxReal range[2] = { 0.0f, 1.0f };

	const PxReal r = (range[1] - range[0]);
	const PxReal d = (mMouseDepth - range[0])/r;
	const PxReal delta = deltaDepth*0.02f*(1.0f - d);

	mMouseDepth = PxClamp(mMouseDepth + delta, range[0], range[1]);
}*/

void Picking::tick()
{
	if(mMouseJoint)
		moveActor(mMouseScreenX,mMouseScreenY);

	// PT: delete mouse actor one frame later to avoid crashes
	SAFE_RELEASE(mMouseActorToDelete);
}

void Picking::computeCameraRay(PxVec3& orig, PxVec3& dir, PxI32 x, PxI32 y) const
{
	const PxVec3& camPos = mFrame.getCamera().getPos();

	// compute picking ray
//	const PxVec3 rayOrig = unProject(x, y, 0.0f);	// PT: what the frell is that?
	const PxVec3 rayOrig = camPos;
	const PxVec3 rayDir = (unProject(x, y, 1.0f) - rayOrig).getNormalized();

	orig = rayOrig;
	dir = rayDir;
}

bool Picking::pick(int x, int y)
{
	PxScene& scene = mFrame.getActiveScene();

	PxVec3 rayOrig, rayDir;
	computeCameraRay(rayOrig, rayDir, x, y);

	// raycast rigid bodies in scene
	PxRaycastHit hit; hit.shape = NULL;
	PxRaycastBuffer hit1;
	scene.raycast(rayOrig, rayDir, PX_MAX_F32, hit1, PxHitFlag::ePOSITION);
	hit = hit1.block;

	if(hit.shape)
	{
		const char* shapeName = hit.shape->getName();
		if(shapeName)
			shdfnd::printFormatted("Picked shape name: %s\n", shapeName);

		PxRigidActor* actor = hit.actor;
		PX_ASSERT(actor);
		mSelectedActor = static_cast<PxRigidActor*>(actor->is<PxRigidDynamic>());
		if(!mSelectedActor)
			mSelectedActor = static_cast<PxRigidActor*>(actor->is<PxArticulationLink>());

		//ML::this is very useful to debug some collision problem
		PxTransform t = actor->getGlobalPose();
		PX_UNUSED(t);
	//	shdfnd::printFormatted("id = %i\n PxTransform transform(PxVec3(%f, %f, %f), PxQuat(%f, %f, %f, %f))\n", (int)actor->userData, t.p.x, t.p.y, t.p.z, t.q.x, t.q.y, t.q.z, t.q.w);
	}
	else
		mSelectedActor = 0;

	if(mSelectedActor)
	{
		shdfnd::printFormatted("Actor '%s' picked! (userData: %p)\n", mSelectedActor->getName(), mSelectedActor->userData);

		//if its a dynamic rigid body, joint it for dragging purposes:
		grabActor(hit.position, rayOrig);
	}

#ifdef VISUALIZE_PICKING_RAYS
	Ray ray;
	ray.origin = rayOrig;
	ray.dir = rayDir;
	mRays.push_back(ray);
#endif
	return true;
}

//----------------------------------------------------------------------------//

PxActor* Picking::letGo()
{
	// let go any picked actor
	if(mMouseJoint)
	{
        mMouseJoint->release();
        mMouseJoint = NULL;

        //	SAFE_RELEASE(mMouseActor);			// PT: releasing immediately crashes
        PX_ASSERT(!mMouseActorToDelete);
		mMouseActorToDelete = mMouseActor;	// PT: instead, we mark for deletion next frame
	}

	PxActor* returnedActor = mSelectedActor;

	mSelectedActor = NULL;

	return returnedActor;
}

//----------------------------------------------------------------------------//

void Picking::grabActor(const PxVec3& worldImpact, const PxVec3& rayOrigin)
{
	if(!mSelectedActor
		|| (mSelectedActor->getType() != PxActorType::eRIGID_DYNAMIC
		&& mSelectedActor->getType() != PxActorType::eARTICULATION_LINK))
		return;

	PxScene& scene = mFrame.getActiveScene();
	PxPhysics& physics = scene.getPhysics();

	//create a shape less actor for the mouse
	{
		mMouseActor = physics.createRigidDynamic(PxTransform(worldImpact, PxQuat(PxIdentity)));
		mMouseActor->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true);
		mMouseActor->setMass(1.0f);
		mMouseActor->setMassSpaceInertiaTensor(PxVec3(1.0f, 1.0f, 1.0f));

		scene.addActor(*mMouseActor);
	}
	PxRigidActor* pickedActor = static_cast<PxRigidActor*>(mSelectedActor);

#if USE_D6_JOINT_FOR_MOUSE
	mMouseJoint = PxD6JointCreate(		physics,
										mMouseActor,
										PxTransform(PxIdentity),
										pickedActor,
										PxTransform(pickedActor->getGlobalPose().transformInv(worldImpact)));
#elif USE_SPHERICAL_JOINT_FOR_MOUSE
	mMouseJoint = PxSphericalJointCreate(physics,
										mMouseActor,
										PxTransform(PxIdentity),
										pickedActor,
										PxTransform(pickedActor->getGlobalPose().transformInv(worldImpact)));
#else
	mMouseJoint = PxDistanceJointCreate(physics,
										mMouseActor,
										PxTransform(PxIdentity),
										pickedActor,
										PxTransform(pickedActor->getGlobalPose().transformInv(worldImpact)));
	mMouseJoint->setMaxDistance(0.0f);
	mMouseJoint->setMinDistance(0.0f);
	mMouseJoint->setDistanceJointFlags(PxDistanceJointFlag::eMAX_DISTANCE_ENABLED);
#endif

	mDistanceToPicked = (worldImpact - rayOrigin).magnitude();
}

//----------------------------------------------------------------------------//

void Picking::moveActor(int x, int y)
{
	if(!mMouseActor)
		return;

	PxVec3 rayOrig, rayDir;
	computeCameraRay(rayOrig, rayDir, x, y);

	const PxVec3 pos = rayOrig + mDistanceToPicked * rayDir;

	mMouseActor->setKinematicTarget(PxTransform(pos, PxQuat(PxIdentity)));
}

//----------------------------------------------------------------------------//

PxVec3 Picking::unProject(int x, int y, float depth) const
{
	SampleRenderer::Renderer* renderer = mFrame.getRenderer();
	const SampleRenderer::RendererProjection& projection = mFrame.getCamera().getProjMatrix();
	const PxTransform view = mFrame.getCamera().getViewMatrix().getInverse();

	PxU32 windowWidth  = 0;
	PxU32 windowHeight = 0;
	renderer->getWindowSize(windowWidth, windowHeight);

	const PxF32 outX = (float)x / (float)windowWidth;
	const PxF32 outY = (float)y / (float)windowHeight;

	return SampleRenderer::unproject(projection, view, outX * 2 -1, outY * 2 -1, depth * 2 - 1);
}

//----------------------------------------------------------------------------//

void Picking::project(const physx::PxVec3& v, int& xi, int& yi, float& depth) const
{
	SampleRenderer::Renderer* renderer = mFrame.getRenderer();
	SampleRenderer::RendererProjection	projection = mFrame.getCamera().getProjMatrix();
	const PxTransform view = mFrame.getCamera().getViewMatrix().getInverse();

	PxVec3 pos = SampleRenderer::project(projection, view, v);
	///* Map x, y and z to range 0-1 */
	pos.x = (pos.x + 1 ) * 0.5f;
	pos.y = (pos.y + 1 ) * 0.5f;
	pos.z = (pos.z + 1 ) * 0.5f;

	PxU32 windowWidth  = 0;
	PxU32 windowHeight = 0;
	renderer->getWindowSize(windowWidth, windowHeight);

	/* Map x,y to viewport */
	pos.x *= windowWidth;
	pos.y *= windowHeight;

	depth = (float)pos.z;

	xi = (int)(pos.x + 0.5);
	yi = (int)(pos.y + 0.5);
}


text:
package io.part6;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by chenyang on 16/10/15.
 */
public class BufferedInputFile {

    public static String
    read(String filename) throws IOException{
        BufferedReader in=new BufferedReader(new FileReader(filename));
        String s;
        StringBuilder sb= new StringBuilder();
        while ((s=in.readLine())!=null){
            sb.append(s+"\n");
        }
        return sb.toString();
    }

    public static void main(String[] args) throws IOException {
        System.out.println(read("./src/main/java/io/source/hello.txt"));
    }
}


text:
var socket = io();
var isMouseDown = false;
var data = {};
var color = "#00ff00";
var size = 3;
$(document).ready(function () {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    socket.emit('getCanvas', "Load");
    function drawData(e) {
        ctx.beginPath();
        ctx.fillStyle = e.c;
        ctx.fillRect(e.x - e.s / 2, e.y - e.s / 2, e.s, e.s);
        ctx.closePath();
    }
    function sendData() {
        socket.emit('draw', JSON.stringify(data));
        data = {};
    }
    $('#color').change(function () {
        var regex = /^[A-Fa-f0-9]+$/;
        var val = $('#color').val();
        if (regex.exec(val) == null) {
            color = "#ffffff";
            $('#color').css({ 'background-color': '#aa2222' });
        }
        else {
            color = "#" + val;
            $('#color').css({ 'background-color': color,
                'color': '#FFFFFF' });
        }
    });
    $('#size').change(function () {
        size = $('#size').val();
    });
    $('#download').click(function () {
        socket.emit("getCanvas", "Download");
    });
    canvas.addEventListener('mousedown', function () {
        isMouseDown = true;
    });
    canvas.addEventListener('mouseup', function () {
        isMouseDown = false;
    });
    canvas.addEventListener('mousemove', function (e) {
        if (isMouseDown) {
            var obj = { "x": e.offsetX,
                "y": e.offsetY,
                "c": color,
                "s": size
            };
            data[Date.now()] = obj;
            drawData(obj);
            sendData();
        }
    });
    socket.on('receive', function (json) {
        var data = JSON.parse(json);
        for (var key in data) {
            drawData(data[key]);
        }
    });
    socket.on('setCanvas', function (data) {
        console.log("setting canvas");
        $('#canvas').css({ "background-image": "url(" + data + ")" });
    });
    socket.on('downloadCanvas', function (data) {
        // Algoritm obtained from http://stackoverflow.com/questions/3906142/how-to-save-a-png-from-javascript-variable
        var download = document.createElement('a');
        download.href = data;
        download.download = "download.png";
        download.click();
    });
});


text:
package org.jruby.ast.visitor.rewriter.utils;

import org.jruby.ast.NewlineNode;
import org.jruby.ast.visitor.rewriter.ReWriteVisitor;

public class ShortIfNodeReWriteVisitor extends ReWriteVisitor {

	public ShortIfNodeReWriteVisitor(ReWriterContext config) {
		super(config);
	}

	protected void printNewlineAndIndentation() {
		print("; ");
	}

	public Object visitNewlineNode(NewlineNode iVisited) {
		if (config.getSource().charAt(getEndOffset(iVisited) - 1) == ')') {
			print('(');
			visitNode(iVisited.getNextNode());
			print(')');
		} else {
			print("; ");
			visitNode(iVisited.getNextNode());
		}
		return null;
	}
}


text:
package com.intellij.tools;

import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ExportableApplicationComponent;
import com.intellij.openapi.components.RoamingType;
import com.intellij.openapi.options.SchemesManager;
import com.intellij.openapi.options.SchemesManagerFactory;
import com.intellij.openapi.util.Comparing;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;

public class ToolManager implements ExportableApplicationComponent {

  private final ActionManagerEx myActionManager;
  private final SchemesManager<ToolsGroup,ToolsGroup> mySchemesManager;

  public static ToolManager getInstance() {
    return ApplicationManager.getApplication().getComponent(ToolManager.class);
  }

  public ToolManager(ActionManagerEx actionManagerEx, SchemesManagerFactory factory) {
    myActionManager = actionManagerEx;

    mySchemesManager = factory.createSchemesManager(
        "$ROOT_CONFIG$/tools", new ToolsProcessor(), RoamingType.PER_USER);

    mySchemesManager.loadSchemes();
    registerActions();
  }

  @Nullable
  public static String convertString(String s) {
    if (s != null && s.trim().length() == 0) return null;
    return s;
  }

  @NotNull
  public File[] getExportFiles() {
    return new File[]{mySchemesManager.getRootDirectory()};
  }

  @NotNull
  public String getPresentableName() {
    return ToolsBundle.message("tools.settings");
  }

  public void disposeComponent() {
  }

  public void initComponent() { }

  public Tool[] getTools() {
    ArrayList<Tool> result = new ArrayList<Tool>();
    for (ToolsGroup group : mySchemesManager.getAllSchemes()) {
      result.addAll(group.getElements());
    }
    return result.toArray(new Tool[result.size()]);
  }

  public Tool[] getTools(String group) {
    ArrayList<Tool> list = new ArrayList<Tool>();
    ToolsGroup groupByName = mySchemesManager.findSchemeByName(group);
    if (groupByName != null) {
      list.addAll(groupByName.getElements());
    }
    return list.toArray(new Tool[list.size()]);
  }

  /**
    * Get all not empty group names of tools in array
    */
  String[] getGroups(Tool[] tools) {
    ArrayList<String> list = new ArrayList<String>();
    for (int i = 0; i < tools.length; i++) {
      Tool tool = tools[i];
      if (!list.contains(tool.getGroup())) {
        list.add(tool.getGroup());
      }
    }
    return ArrayUtil.toStringArray(list);
  }

  public String getGroupByActionId(String actionId) {
    for (Tool tool : getTools()) {
      if (Comparing.equal(actionId, tool.getActionId())) {
        return tool.getGroup();
      }
    }
    return null;
  }

  public ToolsGroup[] getGroups() {
    Collection<ToolsGroup> groups = mySchemesManager.getAllSchemes();
    return groups.toArray(new ToolsGroup[groups.size()]);
  }

  public void setTools(ToolsGroup[] tools) {
    mySchemesManager.clearAllSchemes();
    for (ToolsGroup newGroup : tools) {
      mySchemesManager.addNewScheme(newGroup, true);
    }
    registerActions();
  }

  void registerActions() {
    unregisterActions();

    // register
    HashSet registeredIds = new HashSet(); // to prevent exception if 2 or more targets have the same name

    Tool[] tools = getTools();
    for (int i = 0; i < tools.length; i++) {
      Tool tool = tools[i];
      String actionId = tool.getActionId();

      if (!registeredIds.contains(actionId)) {
        registeredIds.add(actionId);
        myActionManager.registerAction(actionId, new ToolAction(tool));
      }
    }
  }

  private void unregisterActions() {
    // unregister Tool actions
    String[] oldIds = myActionManager.getActionIds(Tool.ACTION_ID_PREFIX);
    for (int i = 0; i < oldIds.length; i++) {
      String oldId = oldIds[i];
      myActionManager.unregisterAction(oldId);
    }
  }

  public String getComponentName() {
    return "ToolManager";
  }

}


text:
package org.apache.http.entity.mime;

/**
 *
 * @since 4.0
 */
public enum HttpMultipartMode {

    /** RFC 822, RFC 2045, RFC 2046 compliant */
    STRICT,
    /** browser-compatible mode, i.e. only write Content-Disposition; use content charset */
    BROWSER_COMPATIBLE,
    /** RFC 6532 compliant */
    RFC6532

}


text:
package org.snmp4j;

import org.snmp4j.event.*;
import java.io.IOException;

/**
 * Session defines a common interface for all classes that
 * implement SNMP protocol operations based on SNMP4J.
 *
 * @author Frank Fock
 * @version 1.2
 */
public interface Session {

  /**
   * Closes the session and frees any allocated resources, i.e. sockets.
   * After a Session has been closed it must
   * be used.
   * @throws IOException
   *    if the session could not free all resources.
   */
  public void close() throws IOException;

  /**
   * Sends a PDU to the given target and returns the received
   * response PDU.
   * @param pdu
   *    the PDU to send.
   * @param target
   *    the Target instance that specifies how and where to send
   *    the PDU.
   * @return
   *    the received response encapsulated in a ResponseEvent
   *    instance. To obtain the received response PDU call
   *    {@link ResponseEvent#getResponse()}. If the request timed out,
   *    that method will return null. If the sent pdu
   *    is an unconfirmed PDU (notification, response, or report), then
   *    null will be returned.
   * @throws IOException
   *    if the message could not be send.
   */
  public ResponseEvent send(PDU pdu, Target target) throws IOException;

  /**
   * Asynchronously sends a PDU to the given target. The response
   * is then returned by calling the supplied ResponseListener
   * instance.
   *
   * @param pdu
   *    the PDU instance to send.
   * @param target
   *    the Target instance representing the target SNMP engine where to send
   *    the pdu.
   * @param userHandle
   *    an user defined handle that is returned when the request is returned
   *    via the listener object.
   * @param listener
   *    a ResponseListener instance that is called when
   *    pdu is a confirmed PDU and the request is either answered
   *    or timed out.
   * @throws IOException
   *    if the message could not be send.
   */
  public void send(PDU pdu, Target target, Object userHandle,
                   ResponseListener listener) throws IOException;

  /**
   * Sends a PDU to the given target and returns the received
   * response PDU encapsulated in a ResponseEvent
   * object that also includes:
   *

   *
the transport address of the response sending peer,
   *
the Target information of the target,
   *
the request PDU,
   *
the response PDU (if any).
   *

   * @param pdu
   *    the PDU instance to send.
   * @param target
   *    the Target instance representing the target SNMP engine where to send
   *    the pdu.
   * @param transport
   *    specifies the TransportMapping to be used when sending
   *    the PDU. If transport is null, the associated
   *    message dispatcher will try to determine the transport mapping by the
   *    target's address.
   * @return
   *    the received response encapsulated in a ResponseEvent
   *    instance. To obtain the received response PDU call
   *    {@link ResponseEvent#getResponse()}. If the request timed out,
   *    that method will return null. If the sent pdu
   *    is an unconfirmed PDU (notification, response, or report), then
   *    null will be returned.
   * @throws IOException
   *    if the message could not be send.
   */
  public ResponseEvent send(PDU pdu, Target target,
                            TransportMapping transport) throws IOException;

  /**
   * Asynchronously sends a PDU to the given target. The response
   * is then returned by calling the supplied ResponseListener
   * instance.
   *
   * @param pdu
   *    the PDU instance to send.
   * @param target
   *    the Target instance representing the target SNMP engine where to send
   *    the pdu.
   * @param transport
   *    specifies the TransportMapping to be used when sending
   *    the PDU. If transport is null, the associated
   *    message dispatcher will try to determine the transport mapping by the
   *    target's address.
   * @param userHandle
   *    an user defined handle that is returned when the request is returned
   *    via the listener object.
   * @param listener
   *    a ResponseListener instance that is called when
   *    pdu is a confirmed PDU and the request is either answered
   *    or timed out.
   * @throws IOException
   *    if the message could not be send.
   */
  public void send(PDU pdu, Target target, TransportMapping transport,
                   Object userHandle,
                   ResponseListener listener) throws IOException;

  /**
   * Cancels an asynchronous request. Any asynchronous request must be canceled
   * when the supplied response listener is being called, even if the
   * ResponseEvent indicates an error.
   * @param request
   *    a request PDU as sent via {@link #send(PDU pdu, Target target,
   *    Object userHandle, ResponseListener listener)} or any .
   * @param listener
   *    a ResponseListener instance.
   */
  public void cancel(PDU request, ResponseListener listener);
}


text: export { default } from 'ember-flexberry-designer/controllers/fd-inheritance-edit-form';


text:
"use strict";

export default class LocationService {

  constructor() {
    this._initialized = false;
    this._currentLocation = undefined;
    this._watchId = undefined;
  }

  /**
   * Ensure that the location is watched.
   *
   * Watch is preferred over getting the current position in every request:
   *
   * - When asking the user to share the location, the outstanding request is blocked
   * - There is a performance cost on requesting the actual location every time.
   *
   * @private
   */
  _ensureInitialized() {
    if (!this._initialized) {
      this._initialized = true;

      if (!!navigator && !!navigator.geolocation) {
        const options = {
          timeout:60000
        };

        const geoLoc = navigator.geolocation;
        this._watchID = geoLoc.watchPosition(
          (position) => {
            this._currentLocation = {
              latitude: position.coords.latitude,
              longitude: position.coords.longitude
            };
          },
          () => {
            this._currentLocation = null;
          },
          options
        );
      }
    }
  }

  get currentLocation() {
    this._ensureInitialized();

    return new Promise((resolve) => {
      resolve(this._currentLocation);
    });
  }
}


text:
from microbenchmarks._utils import size2tag

import taichi as ti

class BenchmarkItem:
    name = 'item'

    def __init__(self):
        self._items = {}  # {'tag': impl, ...}

    def get(self):
        return self._items

    def get_tags(self):
        return list(self._items.keys())

    def impl(self, tag: str):
        return self._items[tag]

    def remove(self, tags: list):
        for tag in tags:
            self._items.pop(tag)

    def update(self, adict: dict):
        self._items.update(adict)

class DataType(BenchmarkItem):
    name = 'dtype'
    integer_list = ['i32', 'i64']

    def __init__(self):
        self._items = {
            str(ti.i32): ti.i32,
            str(ti.i64): ti.i64,
            str(ti.f32): ti.f32,
            str(ti.f64): ti.f64
        }

    def remove_integer(self):
        self.remove(self.integer_list)

    @staticmethod
    def is_integer(dtype: str):
        integer_list = ['i32', 'u32', 'i64', 'u64']
        return True if dtype in integer_list else False

class DataSize(BenchmarkItem):
    name = 'dsize'

    def __init__(self):
        self._items = {}
        for i in range(2, 10, 2):  # [16KB,256KB,4MB,64MB]
            size_bytes = (4**i) * 1024  # kibibytes(KiB) = 1024
            self._items[size2tag(size_bytes)] = size_bytes

class Container(BenchmarkItem):
    name = 'container'

    def __init__(self):
        self._items = {'field': ti.field, 'ndarray': ti.ndarray}

class MathOps(BenchmarkItem):
    name = 'math_op'

    #reference: https://docs.taichi-lang.org/docs/operator
    def __init__(self):
        self._items = {
            # Trigonometric
            'sin': ti.sin,
            'cos': ti.cos,
            'tan': ti.tan,
            'asin': ti.asin,
            'acos': ti.acos,
            'tanh': ti.tanh,
            # Other arithmetic
            'sqrt': ti.sqrt,
            'rsqrt': ti.rsqrt,  # A fast version for `1 / ti.sqrt(x)`.
            'exp': ti.exp,
            'log': ti.log,
            'round': ti.round,
            'floor': ti.floor,
            'ceil': ti.ceil,
            'abs': ti.abs,
        }

class AtomicOps(BenchmarkItem):
    name = 'atomic_op'

    def __init__(self):
        self._items = {
            'atomic_add': ti.atomic_add,
            'atomic_sub': ti.atomic_sub,
            'atomic_and': ti.atomic_and,
            'atomic_or': ti.atomic_or,
            'atomic_xor': ti.atomic_xor,
            'atomic_max': ti.atomic_max,
            'atomic_min': ti.atomic_min
        }

    @staticmethod
    def is_logical_op(op: str):
        logical_op_list = ['atomic_and', 'atomic_or', 'atomic_xor']
        return True if op in logical_op_list else False

    @staticmethod
    def is_supported_type(op: str, dtype: str):
        if AtomicOps.is_logical_op(op) and not DataType.is_integer(dtype):
            return False
        else:
            return True


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Polly;

namespace NuGetCatalog
{
    internal static class Globals
    {
        internal static readonly HttpClient Client = new HttpClient();

        internal static string V3Url { get; } = "https://api.nuget.org/v3/index.json";

        internal static async Task<JObject> GetJsonAsync(this HttpClient client, string url)
        {
            Trace.WriteLine("GET " + url);
            var json = await Policy.Handle<Exception>()
                .WaitAndRetryAsync(20, count => TimeSpan.FromSeconds(count))
                .ExecuteAsync(() => client.GetStringAsync(url)).ConfigureAwait(false);
            return JObject.Parse(json);
        }

        internal static Exception UnrecognizedJson()
        {
             return new InvalidOperationException("Unrecognized json from NuGet.");
        }
    }
}


text:
"""

author: pwxcoo
date: 2018-08-02
description: 多线程抓取下载词语并保存

"""

import requests, csv
from bs4 import BeautifulSoup
import time
from multiprocessing.dummy import Pool as ThreadPool

def downloader(url):
    """
    下载词语并保存
    """
    res = []
    try:
        response = requests.get(url)

        if response.status_code != 200:
            print(f'{url} is failed!')
            return len(res)

        print(f'{url} is parsing')
        html = BeautifulSoup(response.content.decode('gbk', errors='ignore'), "lxml")
        a = html.find_all('a', target="_blank")

        prefix = 'http://www.zd9999.com'
        words = [prefix + w.get('href') for w in a]

        for i in range(0, len(words)):
            print(f'{[words[i]]} is parsing')

            try:
                response  = requests.get(words[i])
                wordhtml = BeautifulSoup(response.content.decode('gbk', errors='ignore').replace('
', '\n').replace('
', '\n')\
                            , "lxml")
                td = wordhtml.find_all('table')[5].find_all('td')
                res.append([td[0].text.strip(), td[1].text.strip()])

            except Exception as e:
                with open('../data/error.csv', mode='a+', encoding='utf-8', newline='') as error_file:
                    csv.writer(error_file).writerows([0, e, words[i]])
                print(f'{words[i]} is failed! {e}')
                continue

    except Exception as e:
        with open('../data/error.csv', mode='a+', encoding='utf-8', newline='') as error_file:
            csv.writer(error_file).writerows([1, e, url])
        print(f'{url} is failed! {e}')

    with open('../data/ci.csv', mode='a+', encoding='utf-8', newline='') as csv_file:
        csv.writer(csv_file).writerows(res)

    return len(res)

if __name__ == '__main__':
    start_time = time.time()

    pool = ThreadPool(100)
    urls = ['http://www.zd9999.com/ci/index.htm']
    for i in range(2, 1959):
        urls.append(f'http://www.zd9999.com/ci/index_{i}.htm')
    responses = pool.map(downloader, urls)
    pool.close()
    pool.join()

    end_time = time.time()

    print(f'总共耗时 {end_time - start_time}, 抓取了 {sum(responses)} 条数据')


text:
package com.thoughtworks.studios.shine.io;

import java.io.IOException;
import java.io.OutputStream;

public class StringOutputStream extends OutputStream {

  private StringBuffer buf = new StringBuffer();

  @Override
  public void write(int i) throws IOException {
    buf.append((char) i);
  }

  public String contents() {
    return buf.toString();
  }
}


text:
<?php

namespace Acquia\Blt\Robo\Hooks;

use Acquia\Blt\Robo\Common\ArrayManipulator;
use Acquia\Blt\Robo\Common\IO;
use Acquia\Blt\Robo\Config\ConfigAwareTrait;
use Acquia\Blt\Robo\Console\ConfigInput;
use Consolidation\AnnotatedCommand\AnnotationData;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Robo\Contract\ConfigAwareInterface;
use Robo\Contract\IOAwareInterface;
use Robo\Tasks;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * This class defines hooks that provide user interaction.
 *
 * These hooks typically use a Wizard to evaluate the validity of config or
 * state and guide the user toward resolving issues.
 */
class CommandEventHook extends Tasks implements IOAwareInterface, ConfigAwareInterface, LoggerAwareInterface {

  use ConfigAwareTrait;
  use LoggerAwareTrait;

  /**
   * Disable any command listed in the `disable-target` config key.
   *
   * @hook command-event *
   */
  public function skipDisabledCommands(ConsoleCommandEvent $event) {
    $command = $event->getCommand();
    $disabled_commands_config = $this->getConfigValue('disable-targets');
    if ($disabled_commands_config) {
      $disabled_commands = ArrayManipulator::flattenMultidimensionalArray($disabled_commands_config, ':');
      if (in_array($command->getName(), $disabled_commands) && $disabled_commands[$command->getName()]) {
        $event->disableCommand();
        $this->output()->writeln("The {$command->getName()} command has been disabled. Skipping execution.");
      }
    }
  }

}


text:
AkDebugLoad = false
AkStartWithDebug = false

-- Lädt den EEP Simulator
local EepSimulator = require("ak.core.eep.EepSimulator")

-- Zum Test setzen wir ein paar Züge, Autos und Trams auf Gleise und Straßen
EepSimulator.setzeZugAufGleis(5, "Tuff Tuff Zug")
EepSimulator.setzeZugAufGleis(7, "Zoom Zoom Zug")
EepSimulator.setzeZugAufStrasse(3, "Feuerwehr")
EepSimulator.setzeZugAufStrasse(4, "Tram")
EepSimulator.setzeZugAufStrasse(5, "Tram")
EepSimulator.setzeZugAufStrasse(6, "Tram")

------------------------------------------------------------------------------------
-- Es folge der Import der Anlage, die getestet werden soll.
-- Ändere die folgende Zeile, wenn Du eine andere Anlage testen möchtest
------------------------------------------------------------------------------------
require("ak.template.crossing-simple")

-- Zeige erweiterte Informationen an                              --
local Scheduler = require("ak.scheduler.Scheduler")
Scheduler.debug = false
local TrafficLight = require("ak.road.TrafficLight")
TrafficLight.debug = false
local Crossing = require("ak.road.Crossing")
Crossing.debug = false
Crossing.zeigeSignalIdsAllerSignale = false
Crossing.zeigeAnforderungenAlsInfo = false
Crossing.zeigeSchaltungAlsInfo = false
local StorageUtility = require("ak.storage.StorageUtility")
StorageUtility.debug = false

-- Diese Methode nutzen wir später um vergangene Zeit in EEP zu simulieren und die EEPMain-Methode aufzurufen
local function run()
    EEPTime = EEPTime + 20
    EEPMain()
end

-- Wir rufen 50 Mal hintereinandere die run() Methode auf und simulieren so 50 EEPMain Aufrufe
-- mit aufeinanderfolgenden Zeiten
for _ = 1, 50 do run() end


text:
#pragma once
#ifndef __SEMILOGY_H__
#define __SEMILOGY_H__

#include "plot/properties/scaleProperties.h"
#include "plot/properties/plotProperties.h"

class SemiLogYPlot
    : public PlotProperties< SemiLogYPlot >
{
public:

    enum NonPos
    {
        Mask,
        Clip
    };

    SemiLogYPlot(const PVec &exogenous, const PVec &endogenous);

    virtual std::string ToString() override;

    SemiLogYPlot &SetScale(LogScale &scale);

};

#ifndef PLOTLIB_NO_HEADER_ONLY
#   include "../../src/semiLogYPlot.cpp"
#endif

#endif


text:
/*
  INF01142 - Sistemas Operacionais I
  T2FS - 2017/1

  Testes dos métodos de API: truncate

  Desenvolvido por Francisco Knebel
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "libs.h"

#define IDENTIFY_SIZE 80

int read(int handle, int size, char* buffer) {
  if(handle < 0) {
    printf("%d: Erro abrindo arquivo.\n", handle);
    return -1;
  }

  int check = read2(handle, buffer, size);
  if(check < 0) {
    printf("%d: Erro lendo arquivo.\n", check);
    return -1;
  }

  return check;
}

char *randstring(int length) {
    char *string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    size_t stringLen = 26*2+10;
    char *randomString;

    randomString = malloc(sizeof(char) * (length +1));

    if (!randomString) {
        return (char*)0;
    }

    unsigned int key = 0;
    int n;
    for (n = 0;n < length;n++) {
        key = rand() % stringLen;
        randomString[n] = string[key];
    }

    randomString[length] = '\0';

    return randomString;
}

int write(int handle, int size, char* buffer) {
  if(handle < 0) {
    printf("%d: Erro abrindo arquivo.\n", handle);
    return -1;
  }

  int check = write2(handle, buffer, size);
  if(check < 0) {
    printf("%d: Erro escrevendo arquivo.\n", check);
    return -1;
  }

  return check;
}

void readAndPrint(int handle, char* path, int size) {
  int offset = 0, check;
  char *newBuffer = malloc(sizeof(char) * size);
  strcpy(newBuffer, "");
  seek2(handle, 0);
  do {
    check = read(handle, 32, &newBuffer[offset]);
    if(check > 0) {
      offset += check;
    }
  } while(check != 0);

  newBuffer[offset] = '\0';
  printf("\nArquivo '%s' lido, com tamanho de '%d' bytes:\n", path, offset);
  printf("Pressione ENTER para imprimir o arquivo."); getchar();
  printf("%s", newBuffer);
}

int writeContiguousBlocks(char* path) {
  int handle = open2(path);

  int i = 0, loops = 30, bytesPerWrite = 64;
  for (i = 0; i < loops; i++) {
    write(handle, bytesPerWrite, randstring(bytesPerWrite));
  }

  close2(handle);

  return loops * bytesPerWrite;
}

void test_truncate_contiguous(char* path) {
  int size = writeContiguousBlocks(path);

  int handle = open2(path);

  // le o arquivo e imprime
  readAndPrint(handle, path, size);

  // seta currentPointer, para truncar, e reseta valor do buffer.
  seek2(handle, 128);
  truncate2(handle);

  // seta currentPointer para o inicio.
  seek2(handle, 0);
  readAndPrint(handle, path, 256);
}

int main() {
  char identify[IDENTIFY_SIZE];

  identify2(identify, IDENTIFY_SIZE);
  printf("%s\n\n", identify);

  initConfig();

  printf("--- TRUNCATE2 ---\n");

  test_truncate_contiguous("/file2");

  printf("--- END TRUNCATE2 ---\n");

  return 0;
}