text:
/**
 *
 * 4D Julia set app (kbi/elude @2012-2016)
 *
 */
#include "shared.h"
#include <stdlib.h>
#include "main.h"
#include "demo/demo_app.h"
#include "demo/demo_flyby.h"
#include "demo/demo_window.h"
#include "ral/ral_context.h"
#include "ral/ral_present_job.h"
#include "ral/ral_present_task.h"
#include "ral/ral_program.h"
#include "ral/ral_rendering_handler.h"
#include "ral/ral_texture.h"
#include "ral/ral_texture_view.h"
#include "system/system_assertions.h"
#include "system/system_event.h"
#include "system/system_hashed_ansi_string.h"
#include "system/system_matrix4x4.h"
#include "system/system_pixel_format.h"
#include "system/system_screen_mode.h"
#include "system/system_window.h"
#include "system/system_variant.h"
#include "ui/ui.h"
#include "stage_step_julia.h"
#include "stage_step_light.h"

INCLUDE_OPTIMUS_SUPPORT;

ral_context      _context                   = nullptr;
float            _data[4]                   = {.17995f, -0.66f, -0.239f, -0.210f};
float            _epsilon                   = 0.001f;
float            _escape                    = 1.2f * 1.5f;
demo_flyby       _flyby                     = nullptr;
float            _light_color[3]            = {1.0f,  1.0f,   1.0f};
float            _light_position[4]         = {2.76f, 1.619f, 0.0f, 1.0f};
int              _max_iterations            = 10;
uint32_t         _pipeline_stage_id         = -1;
system_matrix4x4 _projection_matrix         = nullptr;
float            _raycast_radius_multiplier = 2.65f;
ral_texture      _rt_color_texture          = nullptr;
ral_texture_view _rt_color_texture_view     = nullptr;
ral_texture      _rt_depth_texture          = nullptr;
ral_texture_view _rt_depth_texture_view     = nullptr;
bool             _shadows                   = true;
float            _specularity               = 4.4f;
demo_window      _window                    = nullptr;
system_event     _window_closed_event       = system_event_create(true); /* manual_reset */
const uint32_t   _window_height             = 480;
const uint32_t   _window_width              = 640;

/* Forward declarations */
PRIVATE void _deinit                     ();
PRIVATE void _fire_shadows               (void*          not_used,
                                          void*          not_used2);
PRIVATE void _get_a_value                (void*          user_arg,
                                          system_variant result);
PRIVATE void _get_b_value                (void*          user_arg,
                                          system_variant result);
PRIVATE void _get_c_value                (void*          user_arg,
                                          system_variant result);
PRIVATE void _get_d_value                (void*          user_arg,
                                          system_variant result);
PRIVATE void _get_epsilon_value          (void*          user_arg,
                                          system_variant result);
PRIVATE void _get_escape_threshold_value (void*          user_arg,
                                          system_variant result);
PRIVATE void _get_light_color_blue_value (void*          user_arg,
                                          system_variant result);
PRIVATE void _get_light_color_green_value(void*          user_arg,
                                          system_variant result);
PRIVATE void _get_light_color_red_value  (void*          user_arg,
                                          system_variant result);
PRIVATE void _get_light_position_x_value (void*          user_arg,
                                          system_variant result);
PRIVATE void _get_light_position_y_value (void*          user_arg,
                                          system_variant result);
PRIVATE void _get_light_position_z_value (void*          user_arg,
                                          system_variant result);
PRIVATE void _get_max_iterations_value   (void*          user_arg,
                                          system_variant result);
PRIVATE void _get_specularity_value      (void*          user_arg,
                                          system_variant result);
PRIVATE void _init                       ();
PRIVATE void _init_ui                    ();
PRIVATE void _set_a_value                (void*          user_arg,
                                          system_variant new_value);
PRIVATE void _set_b_value                (void*          user_arg,
                                          system_variant new_value);
PRIVATE void _set_c_value                (void*          user_arg,
                                          system_variant new_value);
PRIVATE void _set_d_value                (void*          user_arg,
                                          system_variant new_value);
PRIVATE void _set_epsilon_value          (void*          user_arg,
                                          system_variant new_value);
PRIVATE void _set_escape_threshold_value (void*          user_arg,
                                          system_variant new_value);
PRIVATE void _set_light_color_blue_value (void*          user_arg,
                                          system_variant new_value);
PRIVATE void _set_light_color_green_value(void*          user_arg,
                                          system_variant new_value);
PRIVATE void _set_light_color_red_value  (void*          user_arg,
                                          system_variant new_value);
PRIVATE void _set_light_position_x_value (void*          user_arg,
                                          system_variant new_value);
PRIVATE void _set_light_position_y_value (void*          user_arg,
                                          system_variant new_value);
PRIVATE void _set_light_position_z_value (void*          user_arg,
                                          system_variant new_value);
PRIVATE void _set_max_iterations_value   (void*          user_arg,
                                          system_variant new_value);
PRIVATE void _set_specularity_value      (void*          user_arg,
                                          system_variant new_value);

PRIVATE void _get_raycast_radius_multiplier_value(void*                   user_arg,
                                                  system_variant          result);
PRIVATE void _rendering_lbm_callback_handler     (system_window           window,
                                                  unsigned short          x,
                                                  unsigned short          y,
                                                  system_window_vk_status new_status,
                                                  void*                   unused);
PRIVATE void _set_raycast_radius_multiplier_value(void*                   user_arg,
                                                  system_variant          new_value);

/** TODO */
PRIVATE void _deinit()
{
    ral_texture textures_to_delete[] =
    {
        _rt_color_texture,
        _rt_depth_texture
    };
    const uint32_t n_textures_to_delete = sizeof(textures_to_delete) / sizeof(textures_to_delete[0]);

    ral_context_delete_objects(_context,
                              RAL_CONTEXT_OBJECT_TYPE_TEXTURE,
                              n_textures_to_delete,
                              reinterpret_cast<void* const*>(textures_to_delete) );

    stage_step_julia_deinit(_context);
    stage_step_light_deinit(_context);
}

/** TODO */
PRIVATE ral_present_job _draw_frame(ral_context                                                context,
                                    void*                                                      user_arg,
                                    const ral_rendering_handler_rendering_callback_frame_data* frame_data_ptr)
{
    ral_present_task_id julia_present_task_id = -1;
    ral_present_task_id light_present_task_id = -1;
    ral_present_job     present_job           = nullptr;

    present_job = ral_present_job_create();

    ral_present_job_add_task(present_job,
                             stage_step_light_get_present_task(),
                            &light_present_task_id);
    ral_present_job_add_task(present_job,
                             stage_step_julia_get_present_task(),
                            &julia_present_task_id);

    ral_present_job_connect_tasks(present_job,
                                  julia_present_task_id,
                                  0, /* n_src_task_output */
                                  light_present_task_id,
                                  0,        /* n_dst_task_input          */
                                  nullptr); /* out_opt_connection_id_ptr */
    ral_present_job_connect_tasks(present_job,
                                  julia_present_task_id,
                                  1, /* n_src_task_output */
                                  light_present_task_id,
                                  1,        /* n_dst_task_input          */
                                  nullptr); /* out_opt_connection_id_ptr */

    ral_present_job_set_presentable_output(present_job,
                                           light_present_task_id,
                                           false, /* is_input_io */
                                           0);    /* n_io        */

    return present_job;
}

/** TODO */
PRIVATE void _fire_shadows(void* not_used,
                           void* not_used2)
{
    _shadows = !_shadows;
}

/** TODO */
PRIVATE void _get_a_value(void*          user_arg,
                          system_variant result)
{
    system_variant_set_float(result,
                             _data[0]);
}

/** TODO */
PRIVATE void _get_b_value(void*          user_arg,
                          system_variant result)
{
    system_variant_set_float(result,
                             _data[1]);
}

/** TODO */
PRIVATE void _get_c_value(void*          user_arg,
                          system_variant result)
{
    system_variant_set_float(result,
                             _data[2]);
}

/** TODO */
PRIVATE void _get_d_value(void*          user_arg,
                          system_variant result)
{
    system_variant_set_float(result,
                             _data[3]);
}

/** TODO */
PRIVATE void _get_epsilon_value(void*          user_arg,
                                system_variant result)
{
    system_variant_set_float(result, _epsilon);
}

/** TODO */
PRIVATE void _get_escape_threshold_value(void*          user_arg,
                                         system_variant result)
{
    system_variant_set_float(result,
                             _escape);
}

/** TODO */
PRIVATE void _get_light_color_blue_value(void*          user_arg,
                                         system_variant result)
{
    system_variant_set_float(result,
                             _light_color[2]);
}

/** TODO */
PRIVATE void _get_light_color_green_value(void*          user_arg,
                                          system_variant result)
{
    system_variant_set_float(result,
                             _light_color[1]);
}

/** TODO */
PRIVATE void _get_light_color_red_value(void*          user_arg,
                                        system_variant result)
{
    system_variant_set_float(result,
                             _light_color[0]);
}

/** TODO */
PRIVATE void _get_light_position_x_value(void*          user_arg,
                                         system_variant result)
{
    system_variant_set_float(result,
                             _light_position[0]);
}

/** TODO */
PRIVATE void _get_light_position_y_value(void*          user_arg,
                                         system_variant result)
{
    system_variant_set_float(result,
                             _light_position[1]);
}

/** TODO */
PRIVATE void _get_light_position_z_value(void*          user_arg,
                                         system_variant result)
{
    system_variant_set_float(result,
                             _light_position[2]);
}

/** TODO */
PRIVATE void _get_max_iterations_value(void*          user_arg,
                                       system_variant result)
{
    system_variant_set_float(result,
                             (float) _max_iterations);
}

/** TODO */
PRIVATE void _get_raycast_radius_multiplier_value(void*          user_arg,
                                                  system_variant result)
{
    system_variant_set_float(result,
                             _raycast_radius_multiplier);
}

/** TODO */
PRIVATE void _get_specularity_value(void*          user_arg,
                                    system_variant result)
{
    system_variant_set_float(result,
                             _specularity);
}

PRIVATE void _init()
{
    /* Initialize rendertargets */
    ral_texture_create_info      color_texture_create_info;
    ral_texture_view_create_info color_texture_view_create_info;
    ral_texture_create_info      depth_texture_create_info;
    ral_texture_view_create_info depth_texture_view_create_info;

    color_texture_create_info.base_mipmap_depth      = 1;
    color_texture_create_info.base_mipmap_height     = _window_height;
    color_texture_create_info.base_mipmap_width      = _window_width;
    color_texture_create_info.description            = nullptr;
    color_texture_create_info.fixed_sample_locations = true;
    color_texture_create_info.format                 = RAL_FORMAT_RGBA8_UNORM;
    color_texture_create_info.n_layers               = 1;
    color_texture_create_info.n_samples              = 1;
    color_texture_create_info.type                   = RAL_TEXTURE_TYPE_2D;
    color_texture_create_info.unique_name            = system_hashed_ansi_string_create("Staging color texture");
    color_texture_create_info.usage                  = RAL_TEXTURE_USAGE_COLOR_ATTACHMENT_BIT |
                                                       RAL_TEXTURE_USAGE_BLIT_SRC_BIT;
    color_texture_create_info.use_full_mipmap_chain  = false;

    depth_texture_create_info.base_mipmap_depth      = 1;
    depth_texture_create_info.base_mipmap_height     = _window_height;
    depth_texture_create_info.base_mipmap_width      = _window_width;
    depth_texture_create_info.description            = nullptr;
    depth_texture_create_info.fixed_sample_locations = true;
    depth_texture_create_info.format                 = RAL_FORMAT_DEPTH32_FLOAT;
    depth_texture_create_info.n_layers               = 1;
    depth_texture_create_info.n_samples              = 1;
    depth_texture_create_info.type                   = RAL_TEXTURE_TYPE_2D;
    depth_texture_create_info.unique_name            = system_hashed_ansi_string_create("Staging depth texture");
    depth_texture_create_info.usage                  = RAL_TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
    depth_texture_create_info.use_full_mipmap_chain  = false;

    ral_context_create_textures(_context,
                                1, /* n_textures */
                               &color_texture_create_info,
                               &_rt_color_texture);
    ral_context_create_textures(_context,
                                1, /* n_textures */
                               &depth_texture_create_info,
                               &_rt_depth_texture);

    color_texture_view_create_info = ral_texture_view_create_info::ral_texture_view_create_info(_rt_color_texture);
    depth_texture_view_create_info = ral_texture_view_create_info::ral_texture_view_create_info(_rt_depth_texture);

    _rt_color_texture_view = ral_texture_get_view(&color_texture_view_create_info);
    _rt_depth_texture_view = ral_texture_get_view(&depth_texture_view_create_info);

    /* Initialize workers */
    stage_step_julia_init(_context,
                          _rt_color_texture_view,
                          _rt_depth_texture_view);
    stage_step_light_init(_context,
                          _rt_color_texture_view,
                          _rt_depth_texture_view);

    /* Initialize the UI */
    _init_ui();

    /* Initialize flyby */
    const float camera_pos[]          = {-0.1611f, 4.5528f, -6.0926f};
    const float camera_movement_delta = 0.025f;
    const float camera_pitch          = -0.6f;
    const float camera_yaw            = 0.024f;
    const bool  flyby_active          = true;

    demo_window_get_property(_window,
                             DEMO_WINDOW_PROPERTY_FLYBY,
                             &_flyby);

    demo_flyby_set_property(_flyby,
                            DEMO_FLYBY_PROPERTY_CAMERA_LOCATION,
                            camera_pos);
    demo_flyby_set_property(_flyby,
                            DEMO_FLYBY_PROPERTY_IS_ACTIVE,
                           &flyby_active);
    demo_flyby_set_property(_flyby,
                            DEMO_FLYBY_PROPERTY_MOVEMENT_DELTA,
                           &camera_movement_delta);
    demo_flyby_set_property(_flyby,
                            DEMO_FLYBY_PROPERTY_PITCH,
                           &camera_pitch);
    demo_flyby_set_property(_flyby,
                            DEMO_FLYBY_PROPERTY_YAW,
                           &camera_yaw);
}

/** TODO */
PRIVATE void _init_ui()
{
    /* Initialize UI */
    const float scrollbar_1_x1y1[]  = {0.8f, 0.0f};
    const float scrollbar_2_x1y1[]  = {0.8f, 0.1f};
    const float scrollbar_3_x1y1[]  = {0.8f, 0.2f};
    const float scrollbar_4_x1y1[]  = {0.8f, 0.3f};
    const float scrollbar_5_x1y1[]  = {0.8f, 0.4f};
    const float scrollbar_6_x1y1[]  = {0.8f, 0.5f};
    const float scrollbar_7_x1y1[]  = {0.8f, 0.6f};
    const float scrollbar_8_x1y1[]  = {0.8f, 0.7f};
    const float scrollbar_9_x1y1[]  = {0.8f, 0.8f};
    const float scrollbar_10_x1y1[] = {0.0f, 0.2f};
    const float scrollbar_11_x1y1[] = {0.0f, 0.3f};
    const float scrollbar_12_x1y1[] = {0.0f, 0.4f};
    const float scrollbar_13_x1y1[] = {0.0f, 0.5f};
    const float scrollbar_14_x1y1[] = {0.0f, 0.6f};
    const float scrollbar_15_x1y1[] = {0.0f, 0.7f};
    const float checkbox_1_x1y1[]   = {0.0f, 0.1f};

    ral_rendering_handler rh;
    ui                    rh_ui;

    demo_window_get_property          (_window,
                                       DEMO_WINDOW_PROPERTY_RENDERING_HANDLER,
                                      &rh);
    ral_rendering_handler_get_property(rh,
                                       RAL_RENDERING_HANDLER_PROPERTY_UI,
                                      &rh_ui);

    ui_add_scrollbar(rh_ui,
                     system_hashed_ansi_string_create("A"),
                     UI_SCROLLBAR_TEXT_LOCATION_ABOVE_SLIDER,
                     system_variant_create_float(-1.5f),
                     system_variant_create_float(1.5f),
                     scrollbar_1_x1y1,
                     _get_a_value,
                     NULL,         /* get_current_value_user_arg */
                     _set_a_value,
                     NULL);        /* set_current_value_user_arg */
    ui_add_scrollbar(rh_ui,
                     system_hashed_ansi_string_create("B"),
                     UI_SCROLLBAR_TEXT_LOCATION_ABOVE_SLIDER,
                     system_variant_create_float(-1.5f),
                     system_variant_create_float(1.5f),
                     scrollbar_2_x1y1,
                     _get_b_value,
                     NULL,         /* get_current_value_user_arg */
                     _set_b_value,
                     NULL);        /* set_current_value_user_arg */
    ui_add_scrollbar(rh_ui,
                     system_hashed_ansi_string_create("C"),
                     UI_SCROLLBAR_TEXT_LOCATION_ABOVE_SLIDER,
                     system_variant_create_float(-1.5f),
                     system_variant_create_float(1.5f),
                     scrollbar_3_x1y1,
                     _get_c_value,
                     NULL,         /* get_current_value_user_arg */
                     _set_c_value,
                     NULL);        /* set_current_value_user_arg */
    ui_add_scrollbar(rh_ui,
                     system_hashed_ansi_string_create("D"),
                     UI_SCROLLBAR_TEXT_LOCATION_ABOVE_SLIDER,
                     system_variant_create_float(-1.5f),
                     system_variant_create_float(1.5f),
                     scrollbar_4_x1y1,
                     _get_d_value,
                     NULL,         /* get_current_value_user_arg */
                     _set_d_value,
                     NULL);        /* set_current_value_user_arg */
    ui_add_scrollbar(rh_ui,
                     system_hashed_ansi_string_create("Epsilon"),
                     UI_SCROLLBAR_TEXT_LOCATION_ABOVE_SLIDER,
                     system_variant_create_float(0.00001f),
                     system_variant_create_float(0.01f),
                     scrollbar_5_x1y1,
                     _get_epsilon_value,
                     NULL,               /* get_current_value_user_arg */
                     _set_epsilon_value,
                     NULL);              /* set_current_value_user_arg */
    ui_add_scrollbar(rh_ui,
                     system_hashed_ansi_string_create("Escape threshold"),
                     UI_SCROLLBAR_TEXT_LOCATION_ABOVE_SLIDER,
                     system_variant_create_float(0.01f),
                     system_variant_create_float(8.0f),
                     scrollbar_6_x1y1,
                     _get_escape_threshold_value,
                     NULL,                        /* get_current_value_user_arg */
                     _set_escape_threshold_value,
                     NULL);                       /* set_current_value_user_arg */
    ui_add_scrollbar(rh_ui,
                     system_hashed_ansi_string_create("Max iterations"),
                     UI_SCROLLBAR_TEXT_LOCATION_ABOVE_SLIDER,
                     system_variant_create_float(1),
                     system_variant_create_float(10),
                     scrollbar_7_x1y1,
                     _get_max_iterations_value,
                     NULL,                      /* get_current_value_user_arg */
                     _set_max_iterations_value,
                     NULL);                     /* set_current_value_user_arg */
    ui_add_scrollbar(rh_ui,
                     system_hashed_ansi_string_create("Raycast radius"),
                     UI_SCROLLBAR_TEXT_LOCATION_ABOVE_SLIDER,
                     system_variant_create_float(1),
                     system_variant_create_float(4.0f),
                     scrollbar_8_x1y1,
                     _get_raycast_radius_multiplier_value,
                     NULL,                                 /* get_current_value_user_arg */
                     _set_raycast_radius_multiplier_value,
                     NULL);                                /* set_current_value_user_arg */
    ui_add_scrollbar(rh_ui,
                     system_hashed_ansi_string_create("Specularity"),
                     UI_SCROLLBAR_TEXT_LOCATION_ABOVE_SLIDER,
                     system_variant_create_float(0.0001f),
                     system_variant_create_float(40.0f),
                     scrollbar_9_x1y1,
                     _get_specularity_value,
                     NULL,                   /* get_current_value_user_arg */
                     _set_specularity_value,
                     NULL);                  /* set_current_value_user_arg */

    ui_add_checkbox (rh_ui,
                     system_hashed_ansi_string_create("Shadows"),
                     checkbox_1_x1y1,
                     _shadows,
                     _fire_shadows,
                     NULL);         /* fire_user_arg */

    ui_add_scrollbar(rh_ui,
                     system_hashed_ansi_string_create("Light Color R"),
                     UI_SCROLLBAR_TEXT_LOCATION_ABOVE_SLIDER,
                     system_variant_create_float(0.0f),
                     system_variant_create_float(1.0f),
                     scrollbar_10_x1y1,
                     _get_light_color_red_value,
                     NULL,                       /* get_current_value_user_arg */
                     _set_light_color_red_value,
                     NULL);                      /* set_current_value_user_arg */
    ui_add_scrollbar(rh_ui,
                     system_hashed_ansi_string_create("Light Color G"),
                     UI_SCROLLBAR_TEXT_LOCATION_ABOVE_SLIDER,
                     system_variant_create_float(0.0f),
                     system_variant_create_float(1.0f),
                     scrollbar_11_x1y1,
                     _get_light_color_green_value,
                     NULL,                         /* get_current_value_user_arg */
                     _set_light_color_green_value,
                     NULL);                        /* set_current_value_user_arg */
    ui_add_scrollbar(rh_ui,
                     system_hashed_ansi_string_create("Light Color B"),
                     UI_SCROLLBAR_TEXT_LOCATION_ABOVE_SLIDER,
                     system_variant_create_float(0.0f),
                     system_variant_create_float(1.0f),
                     scrollbar_12_x1y1,
                     _get_light_color_blue_value,
                     NULL,                        /* get_current_value_user_arg */
                     _set_light_color_blue_value,
                     NULL);                       /* set_current_value_user_arg */
    ui_add_scrollbar(rh_ui,
                     system_hashed_ansi_string_create("Light Position X"),
                     UI_SCROLLBAR_TEXT_LOCATION_ABOVE_SLIDER,
                     system_variant_create_float(-3.0f),
                     system_variant_create_float(3.0f),
                     scrollbar_13_x1y1,
                     _get_light_position_x_value,
                     NULL,                        /* get_current_value_user_arg */
                     _set_light_position_x_value,
                     NULL);                       /* set_current_value_user_arg */
    ui_add_scrollbar(rh_ui,
                     system_hashed_ansi_string_create("Light Position Y"),
                     UI_SCROLLBAR_TEXT_LOCATION_ABOVE_SLIDER,
                     system_variant_create_float(-3.0f),
                     system_variant_create_float(3.0f),
                     scrollbar_14_x1y1,
                     _get_light_position_y_value,
                     NULL,                        /* get_current_value_user_arg */
                     _set_light_position_y_value,
                     NULL);                       /* set_current_value_user_arg */
    ui_add_scrollbar(rh_ui,
                     system_hashed_ansi_string_create("Light Position Z"),
                     UI_SCROLLBAR_TEXT_LOCATION_ABOVE_SLIDER,
                     system_variant_create_float(-3.0f),
                     system_variant_create_float(3.0f),
                     scrollbar_15_x1y1,
                     _get_light_position_z_value,
                     NULL,                        /* get_current_value_user_arg */
                     _set_light_position_z_value,
                     NULL);                       /* set_current_value_user_arg */
}

PRIVATE void _rendering_lbm_callback_handler(system_window           window,
                                             unsigned short          x,
                                             unsigned short          y,
                                             system_window_vk_status new_status,
                                             void*                   unused)
{
    system_event_set(_window_closed_event);
}

/** TODO */
PRIVATE void _set_a_value(void*          user_arg,
                          system_variant new_value)
{
    system_variant_get_float(new_value,
                             _data + 0);
}

/** TODO */
PRIVATE void _set_b_value(void*          user_arg,
                          system_variant new_value)
{
    system_variant_get_float(new_value,
                             _data + 1);
}

/** TODO */
PRIVATE void _set_c_value(void*          user_arg,
                          system_variant new_value)
{
    system_variant_get_float(new_value,
                             _data + 2);
}

/** TODO */
PRIVATE void _set_d_value(void*          user_arg,
                          system_variant new_value)
{
    system_variant_get_float(new_value,
                             _data + 3);
}

/** TODO */
PRIVATE void _set_epsilon_value(void*          user_arg,
                                system_variant new_value)
{
    system_variant_get_float(new_value,
                            &_epsilon);
}

/** TODO */
PRIVATE void _set_escape_threshold_value(void*          user_arg,
                                         system_variant new_value)
{
    system_variant_get_float(new_value,
                            &_escape);
}

/** TODO */
PRIVATE void _set_light_color_blue_value(void*          user_arg,
                                         system_variant new_value)
{
    system_variant_get_float(new_value,
                             _light_color + 2);
}

/** TODO */
PRIVATE void _set_light_color_green_value(void*          user_arg,
                                          system_variant new_value)
{
    system_variant_get_float(new_value,
                             _light_color + 1);
}

/** TODO */
PRIVATE void _set_light_color_red_value(void*          user_arg,
                                        system_variant new_value)
{
    system_variant_get_float(new_value,
                             _light_color + 0);
}

/** TODO */
PRIVATE void _set_light_position_x_value(void*          user_arg,
                                         system_variant new_value)
{
    system_variant_get_float(new_value,
                             _light_position + 0);
}

/** TODO */
PRIVATE void _set_light_position_y_value(void*          user_arg,
                                         system_variant new_value)
{
    system_variant_get_float(new_value,
                             _light_position + 1);
}

/** TODO */
PRIVATE void _set_light_position_z_value(void*          user_arg,
                                         system_variant new_value)
{
    system_variant_get_float(new_value,
                             _light_position + 2);
}

/** TODO */
PRIVATE void _set_max_iterations_value(void*          user_arg,
                                       system_variant new_value)
{
    float new_max_iterations = 0;

    system_variant_get_float(new_value,
                            &new_max_iterations);

    _max_iterations = (int) new_max_iterations;
}

/** TODO */
PRIVATE void _set_raycast_radius_multiplier_value(void*          user_arg,
                                                  system_variant new_value)
{
    system_variant_get_float(new_value,
                            &_raycast_radius_multiplier);
}

/** TODO */
PRIVATE void _set_specularity_value(void*          user_arg,
                                    system_variant new_value)
{
    system_variant_get_float(new_value,
                            &_specularity);
}

/** TODO */
PRIVATE void _window_closed_callback_handler(system_window window,
                                             void*         unused)
{
    system_event_set(_window_closed_event);
}

/** TODO */
PRIVATE void _window_closing_callback_handler(system_window window,
                                              void*         unused)
{
    _deinit();
}

/** Please see header for specification */
const float* main_get_data_vector()
{
    return _data;
}

/** Please see header for specification */
float main_get_epsilon()
{
    return _epsilon;
}

/** Please see header for specification */
float main_get_escape_threshold()
{
    return _escape;
}

/** Please see header for specification */
const float* main_get_light_color()
{
    return _light_color;
}

/** Please see header for specification */
const float* main_get_light_position()
{
    return _light_position;
}

/** Please see header for specification */
system_matrix4x4 main_get_projection_matrix()
{
    return _projection_matrix;
}

/** Please see header for specification */
int main_get_max_iterations()
{
    return _max_iterations;
}

/** Please see header for specification */
float main_get_raycast_radius_multiplier()
{
    return _raycast_radius_multiplier;
}

/** Please see header for specification */
bool main_get_shadows_status()
{
    return _shadows;
}

/** Please see header for specification */
float main_get_specularity()
{
    return _specularity;
}

/** Entry point */
#ifdef _WIN32
    int WINAPI WinMain(HINSTANCE instance_handle,
                       HINSTANCE,
                       LPTSTR,
                       int)
#else
    int main()
#endif
{
    PFNRALRENDERINGHANDLERRENDERINGCALLBACK pfn_callback_proc    = _draw_frame;
    ral_rendering_handler                   rendering_handler    = NULL;
    demo_window_create_info                 window_create_info;
    const system_hashed_ansi_string         window_name          = system_hashed_ansi_string_create("Julia 4D test app");

    window_create_info.resolution[0] = _window_width;
    window_create_info.resolution[1] = _window_height;

    _window = demo_app_create_window(window_name,
                                     window_create_info,
                                     RAL_BACKEND_TYPE_GL,
                                     false /* use_timeline */);

    demo_window_get_property(_window,
                             DEMO_WINDOW_PROPERTY_RENDERING_CONTEXT,
                            &_context);
    demo_window_get_property(_window,
                             DEMO_WINDOW_PROPERTY_RENDERING_HANDLER,
                            &rendering_handler);

    ral_rendering_handler_set_property(rendering_handler,
                                       RAL_RENDERING_HANDLER_PROPERTY_RENDERING_CALLBACK,
                                      &pfn_callback_proc);

    /* Set up matrices */
    _projection_matrix = system_matrix4x4_create_perspective_projection_matrix(45.0f,                                        /* fov_y  */
                                                                               float(_window_width) / float(_window_height), /* ar     */
                                                                               0.001f,                                       /* z_near */
                                                                               500.0f);                                      /* z_far  */

    /* Set up callbacks */
    demo_window_add_callback_func(_window,
                                  SYSTEM_WINDOW_CALLBACK_FUNC_PRIORITY_NORMAL,
                                  SYSTEM_WINDOW_CALLBACK_FUNC_RIGHT_BUTTON_DOWN,
                                  (void*) _rendering_lbm_callback_handler,
                                  NULL); /* callback_func_user_arg */
    demo_window_add_callback_func(_window,
                                  SYSTEM_WINDOW_CALLBACK_FUNC_PRIORITY_NORMAL,
                                  SYSTEM_WINDOW_CALLBACK_FUNC_WINDOW_CLOSED,
                                  (void*) _window_closed_callback_handler,
                                  NULL);
    demo_window_add_callback_func(_window,
                                  SYSTEM_WINDOW_CALLBACK_FUNC_PRIORITY_NORMAL,
                                  SYSTEM_WINDOW_CALLBACK_FUNC_WINDOW_CLOSING,
                                  (void*) _window_closing_callback_handler,
                                  NULL);

    /* Set up rendering-related stuff */
    _init();

    /* Carry on */
    demo_window_start_rendering(_window,
                                0 /* rendering_start_time */);

    system_event_wait_single(_window_closed_event);

    /* Clean up */
    demo_app_destroy_window(window_name);

    /* Deinitialize GL objects */
    system_matrix4x4_release(_projection_matrix);
    system_event_release    (_window_closed_event);

    main_force_deinit();

    return 0;
}


text:
@*
 * Copyright 2022 HM Revenue & Customs
 *
 * 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 utils.URIInformation
@import config.AppConfig
@import config.LocalFormPartialRetriever
@import views.templatemodels.PageTitle

@this(
        govukLayoutWrapper: GovukLayoutWrapper,
        config: AppConfig,
        localFormPartialRetriever: LocalFormPartialRetriever,
        uriInformation: URIInformation,
        formWithCSRF: FormWithCSRF
)

@(
        bikList: RegistrationList,
        taxYearRange:TaxYearRange,
        empRef: EmpRef
)(implicit request:Request[_], messages: Messages)

@govukLayoutWrapper(PageTitle(messages("AddBenefits.Confirm.Multiple.Title")), Some(taxYearRange), Some(empRef.toString), empRef = Some(empRef.toString)) {

        @messages("Overview.next.heading", taxYearRange.cy + "", taxYearRange.cyplus1 + "")
            @messages("AddBenefits.Confirm.Multiple.Title")

        @formWithCSRF(action = controllers.registration.routes.ManageRegistrationController.addNextYearRegisteredBenefitTypes, 'onsubmit -> "gaEventConfirmAddBenefits()") {

                    @for(item <- bikList.active.indices) {

                                @messages("BenefitInKind.label." + bikList.active(item).id.toString)

                    }

                    @messages("AddBenefits.Confirm.help.desc")

            <input type="submit" role="button" class="govuk-button" id="button-confirm" value='@messages("Service.confirmAndContinue")'>
        }

}

redpajama_set_name: RedPajamaGithub


text:
@implementation VSSentenceCellViewTableViewCell

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

static const int kLabelWith = 304;
static const int kVerticalMargin = 12;

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

+(CGFloat)heightWithSentence:(NSString *)sentence
{
    CGSize size = [sentence sizeWithFont:[UIFont systemFontOfSize:12]
                       constrainedToSize:CGSizeMake(kLabelWith, MAXFLOAT)
                           lineBreakMode:NSLineBreakByWordWrapping];
    return size.height + 15 + kVerticalMargin * 2;
}

#pragma GCC diagnostic pop

-(void) configureWithSentenceVO:(SentenceVO*)sentenceVO
{
    self.sentenceLabel.text = sentenceVO.sentence;
    self.sentenceLabel.textColor = sentenceVO.color;
    [self.sentenceLabel sizeToFit];
}

@end


text:
<?php
namespace Prooms\RoomsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="rooms_constraints")
 */
class RoomConstraint
{
    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="Room", inversedBy="constraints")
     * @ORM\JoinColumn(name="room_id", referencedColumnName="id")
     */
    private $room;

    /**
     * @ORM\Id
     * @ORM\Column(type="string", length=30)
     */
    private $instrument;

    public function getRoom() {
        return $this->room;
    }

    public function setRoom(Room $room) {
        $this->room = $room;
    }

    public function getInstrument() {
        return $this->instrument;
    }

    public function setInstrument($instrument) {
        $this->instrument = $instrument;
    }
}


text:
<?php
define('DT_REWRITE', true);
require 'config.inc.php';
require '../common.inc.php';
$action = 'company';
require DT_ROOT.'/module/'.$module.'/news.inc.php';
?>


text:
#pragma once

#include <memory>
#include <utility>

#include <folly/IPAddress.h>
#include <folly/IPAddressV6.h>
#include <folly/SocketAddress.h>

namespace folly {

class AsyncServerSocket;
class ScopedEventBaseThread;

/***
 *  ScopedBoundPort
 *
 *  Binds to an ephemeral port in the ctor but does not listen. Unbinds from the
 *  port in the dtor.
 *
 *  While an instance is in scope, we know at least one port which is guaranteed
 *  not to be listening - the port the instance binds but does not listen.
 *
 *  Useful for testing server-down cases.
 *
 *  Example:
 *
 *    TEST(MyClient, WhenTheServerIsDown_ThrowsServerDownException) {
 *      folly::ScopedBoundPort bound;
 *      MyClient client(bound.getAddress(), 100ms);
 *      EXPECT_THROW(client.getData(), ServerDownException);
 *    }
 */
class ScopedBoundPort {
 public:
  explicit ScopedBoundPort(IPAddress host = IPAddressV6("::1"));
  ~ScopedBoundPort();
  SocketAddress getAddress() const;

 private:
  std::unique_ptr<ScopedEventBaseThread> ebth_;
  std::shared_ptr<AsyncServerSocket> sock_;
};
} // namespace folly


text:
package cr_ee

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// LayerTasksItem is a nested struct in cr response
type LayerTasksItem struct {
	SyncLayerTaskId string `json:"SyncLayerTaskId" xml:"SyncLayerTaskId"`
	TaskStatus      string `json:"TaskStatus" xml:"TaskStatus"`
	Digest          string `json:"Digest" xml:"Digest"`
	Size            int64  `json:"Size" xml:"Size"`
	SyncedSize      int64  `json:"SyncedSize" xml:"SyncedSize"`
}


text:
@interface RedXcode : NSObject

@end


text:
import ailment

from ...analysis import Analysis

class OptimizationPass(Analysis):

    ARCHES = [ ]  # strings of supported architectures
    PLATFORMS = [ ]  # strings of supported platforms. Can be one of the following: "win32", "linux"

    def __init__(self, func, blocks=None):

        self._func = func
        self._blocks = blocks

    @property
    def blocks(self):
        return self._blocks

    def analyze(self):

        ret, cache = self._check()
        if ret:
            self._analyze(cache=cache)

    def _check(self):
        """
        Check if this optimization applies to this function.

        :returns: a tuple of (does_apply, cache) where cache is a way to pass
                  information to _analyze so it does not have to be recalculated
        """
        raise NotImplementedError()

    def _analyze(self, cache=None):
        """
        Run the analysis.

        :param cache: information passed from _check so it does not have to be
                      recalculated
        :returns: None
        """
        raise NotImplementedError()

    #
    # Util methods
    #

    def _get_block(self, addr, size=None):

        original_block = self._func.get_node(addr)
        if original_block is None:
            # this block does not exist
            return None

        if size is None:
            size = original_block.size

        if not self._blocks:
            return original_block
        else:
            return self._blocks.get((addr, size), original_block)

    def _update_block(self, old_block, new_block):

        addr, size = old_block.addr, old_block.original_size
        if self._blocks is None:
            self._blocks = { }
        self._blocks[(addr, size)] = new_block

    def _remove_block(self, block):

        addr, size = block.addr, block.original_size
        if self._blocks is None:
            self._blocks = { }
        self._blocks[(addr, size)] = None

    def _is_add(self, expr):
        return isinstance(expr, ailment.Expr.BinaryOp) and expr.op == "Add"

    def _is_sub(self, expr):
        return isinstance(expr, ailment.Expr.BinaryOp) and expr.op == "Sub"


text:
package lu.sfeir.sid.splunk.consumer;

import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import lu.sfeir.sid.splunk.broker.BrokerAcknowledgmentEvent;
import lu.sfeir.sid.splunk.message.SwiftAcknowledgment;
import lu.sfeir.sid.splunk.message.SwiftMessage;
import lu.sfeir.sid.splunk.utils.Failures;
import lu.sfeir.sid.splunk.utils.Threads;
import lu.sfeir.sid.splunk.utils.UUIDs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.util.concurrent.ExecutorService;

public class Consumer
{

    private static final Logger LOG = LoggerFactory.getLogger(Consumer.class);
    private final EventBus eventBus;
    private final ExecutorService pool;

    public Consumer(final EventBus eventBus, final ExecutorService pool)
    {
        this.eventBus = eventBus;
        this.pool = pool;
        eventBus.register(this);
    }

    @Subscribe
    @AllowConcurrentEvents
    public void onEvent(final ConsumerMessageEvent event)
    {
        pool.execute(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    MDC.put("UUID", UUIDs.newUUID());
                    LOG.info("event=consumer-message, state=start");
                    final SwiftMessage swift = event.getPayload();
                    LOG.info("{}", swift);

                    Threads.sleep(100, 350);

                    Failures.fail(0.076, "[C076] Failed to process swift message [%s]", swift.getReference());

                    final SwiftAcknowledgment ack = new SwiftAcknowledgment(swift);
                    LOG.info("{}", ack);

                    Failures.fail(0.027, "[C027] Failed to send acknowledgment [%s]", ack.getReference());

                    eventBus.post(new BrokerAcknowledgmentEvent(ack));
                    LOG.info("event=consumer-message, state=success");
                }
                catch (Exception ex)
                {
                    LOG.error("event=consumer-message, state=error", ex);
                }
            }
        });
    }
}


text:
using System;
using System.Linq;
using System.Linq.Expressions;
using SaaSPro.Common.Helpers;
using SaaSPro.Common;
using SaaSPro.Domain;

namespace SaaSPro.Services.Helpers
{
    public static class QueryExtensions
    {
        public static IQueryable<T> WhereIf<T>(this IQueryable<T> source, bool criteria, Expression<Func<T, bool>> predicate)
        {
            if (criteria)
            {
                source = source.Where(predicate);
            }

            return source;
        }

        public static ReferenceList GetBySystemName(this IRepository<ReferenceList> repo, string systemName)
        {
            Ensure.Argument.NotNullOrEmpty(systemName, "systemName");
            return repo.Query().FirstOrDefault(x => x.SystemName == systemName);
        }
    }
}


text:
package com.matianl.explore.java7concurrency.Chapter7.ch7_recipe06.src.com.packtpub.java7.concurrency.chapter7.recipe06.task;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

/**
 * Task that will be executed in the Fork/Join framework. It calculates
 * the sum of all array elements
 *
 */
public class MyRecursiveTask extends RecursiveTask<Integer> {

	/**
	 * Serial Version UID
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Array to be summed
	 */
	private int array[];

	/**
	 * Start and end positions of the part of the array to be summed by this task
	 */
	private int start, end;

	/**
	 * Constructor of the class. It initializes the  attributes of the task
	 * @param array Array to be summed
	 * @param start Start position of the block of the array to be summed by this task
	 * @param end End position of the block of the array to be summed by this task
	 */
	public MyRecursiveTask(int array[],int start, int end) {
		this.array=array;
		this.start=start;
		this.end=end;
	}

	/**
	 * Main method of the task. If the task has less than 100 elements to sum, it calculates
	 * the sum of these elements directly. Else, it creates two subtask to process the two
	 * halves of the block.
	 *
	 * It also calls the addTask() method of the thread that is executing the task to
	 * updates its internal counter of tasks
	 */
	@Override
	protected Integer compute() {
		Integer ret;
		MyWorkerThread thread=(MyWorkerThread)Thread.currentThread();
		thread.addTask();
		if (end-start>100) {
			int mid=(start+end)/2;
			MyRecursiveTask task1=new MyRecursiveTask(array,start,mid);
			MyRecursiveTask task2=new MyRecursiveTask(array,mid,end);
			invokeAll(task1,task2);
			ret=addResults(task1,task2);
		} else {
			int add=0;
			for (int i=start; i<end; i++) {
				add+=array[i];
			}
			ret=new Integer(add);
		}
		try {
			TimeUnit.MILLISECONDS.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		return ret;
	}

	/**
	 * Method that adds the results of the two subtasks create by this task
	 * @param task1 First task
	 * @param task2 Second task
	 * @return The sum of the results of the two tasks
	 */
	private Integer addResults(MyRecursiveTask task1, MyRecursiveTask task2) {
		int value;
		try {
			value = task1.get().intValue()+task2.get().intValue();
		} catch (InterruptedException e) {
			e.printStackTrace();
			value=0;
		} catch (ExecutionException e) {
			e.printStackTrace();
			value=0;
		}
		return new Integer(value);
	}

}


text:
<!DOCTYPE HTML>
<meta charset="utf-8"/>

    <link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.1/leaflet.css" rel="stylesheet" />

    <link href="https://cdn-webgl.wrld3d.com/wrldjs/addons/resources/latest/css/wrld.css" rel="stylesheet"/>

    <link rel="stylesheet" href="css/style.css">


text:
<?php

namespace Magento\Backend\Model\View\Layout;

use Magento\Framework\App;
use Magento\Framework\Event;
use Magento\Framework\View;

class Builder extends \Magento\Framework\View\Layout\Builder
{
    /**
     * @var Filter\Acl
     */
    protected $aclFilter;

    /**
     * @param View\LayoutInterface $layout
     * @param App\Request\Http $request
     * @param Event\ManagerInterface $eventManager
     * @param Filter\Acl $aclFilter
     */
    public function __construct(
        View\LayoutInterface $layout,
        App\Request\Http $request,
        Event\ManagerInterface $eventManager,
        Filter\Acl $aclFilter
    ) {
        parent::__construct($layout, $request, $eventManager);
        $this->aclFilter = $aclFilter;
    }

    /**
     * @return $this
     */
    protected function beforeGenerateBlock()
    {
        $this->aclFilter->filterAclNodes($this->layout->getNode());
        return $this;
    }

    /**
     * @return $this
     */
    protected function afterGenerateBlock()
    {
        $this->layout->initMessages();
        return $this;
    }
}


text:
Title: Risotto aux champignons
Category: Recette
Tags: recette, plat, végétarien, moyen
Summary: Recette pour du risotto aux champignons, une recette italienne, qui réchauffe bien !

Recette pour du risotto aux champignons, une recette italienne, qui réchauffe bien !

- *Préparation* : 5 minutes
- *Cuisson* : 25 minutes.

## Ingrédients
> Pour 4 personnes.

- 250 g de riz *arborio*, spécial risotto (on en trouve dans tous les supermarchés),
- une petite boite de conserve (230 g) de champignons de votre choix (je préfère les champignons de Paris, mais on peut aussi utiliser des girolles, cèpes, etc),
- 2 cubes de bouillon de légumes,
- 1 oignon blanc,
- 20 cl de vin blanc (de cuisine),
- 15 cl de crème fraîche,
- 100 g de parmesan râpé,
- une gousse d'ail,
- une noix de beurre,
- une cuillère à soupe d'huile d'olive,
- sel et poivre.

## Préparation
1. Préparer les champignons : égoutter la boite. Faire fondre une noix de beurre dans une poêle et y faire revenir la gousse d'ail émincée, pendant 2 minutes. Ajouter les champignons et laisser les cuire environ 3 minutes. Ajouter 3 cuillères à soupe de vin blanc et laisser cuire 2 minutes jusqu'à ce qu'il réduise. Ajouter la crème fraîche et mélanger. Saler, poivrer et réserver.
2. Faites bouillir (dans une casserole) un litre d'eau dans lequel vous diluerer les cubes de bouillon.
3. Dans une sauteuse, faites chauffer l'huile d'olive pour y faire blondir l'oignon émincé pendant 3 minutes. Ajouter le riz et laisser-le cuire en remuant pendant 2 minutes jusqu'à ce qu'il soit un peu transparent.
4. Ajouter 10 cl de vin blanc (1/2 verre) et une fois qu'il est absorbé par le riz, ajouter une louche de bouillon, puis mélanger. Une fois que le bouillon est bien absorbé, ajouter une nouvelle louche, et ainsi de suite jusqu'à épuisement du bouillon (environ 20 bonnes minutes).
    > Note : cette étape est assez longue, on peut préférer du riz spécial risotto à cuisson rapide et le préparer plus rapidement, mais ce sera moins bon.
5. Ajouter la moitié du parmesan et les champignons, attendre 2 minutes puis mélanger vivement.
6. Servir très chaud, avec le reste du parmesan.

## Photo
[![TODO]({static}images/blank.png)](#)

## Remarques
- :cutlery: Servir chaud, avec du parmesan rappé en plus pour les amateur-trice-s.
- :wine_glass: Servir avec un vin blanc, par exemple un Bourgogne.


text:
namespace Editor
{
	using namespace std;
	using namespace BF;
	using namespace BF::Graphics;
	using namespace BF::Graphics::Renderers;
	using namespace BF::Graphics::GUI;
	using namespace BF::Graphics::API;
	using namespace BF::Application;
	using namespace BF::Math;

	ScenePanel::ScenePanel(Scene& scene, TileSheetPanel& tileSheetPanel) :
		tileSheetPanel(tileSheetPanel), grid(Math::Rectangle((int)position.x, (int)position.y, 10, 10)), paintTile(grid, tilemap), Panel(scene), position(750.0f, 0.0f)
	{
	}

	ScenePanel::~ScenePanel()
	{
	}

	void ScenePanel::Initialize(SpriteRenderer& spriteRenderer, int zLayer)
	{
		Panel::Initialize(spriteRenderer, zLayer);
		paintTile.Initialize(spriteRenderer);
		grid.Initialize(spriteRenderer);
		tilemap.Initialize();
	}

	void ScenePanel::Load(const StyleSheet& StyleSheet, const string& widgetName)
	{
		Panel::Load(StyleSheet, widgetName);
		//paintTile.SetCurrentTile(Sprite(&tileSheetPanel.texture, Vector2(0.0f, 0.0f), 0, Math::Rectangle(0, 0, grid.tileWidth, grid.tileHeight), Color(1.0f)));
		SetRectangle(Math::Rectangle((int)position.x, (int)position.y, 1130, 1010));
		//SetContentRectangle(Math::Rectangle((int)position.x, (int)position.y, texture.GetTextureData().width, texture.GetTextureData().height));
	}

	void ScenePanel::Update()
	{
		Panel::Update();
		paintTile.Update();
	}

	void ScenePanel::Render()
	{
		Panel::Render();
		grid.Render();
		paintTile.Render();
	}

	void ScenePanel::RenderTileMap()
	{
		tilemap.Render();
	}
}


text:
<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>This is my first EAR attempt</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">

        <!-- Place favicon.ico and apple-touch-icon.png in the root directory -->

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
        <script src="js/vendor/modernizr-2.6.2.min.js"></script>
        <style>
            canvas#canvas {
                background-color: #0BD;
                margin: 50px;
            }
        </style>
    </head>
    <body>

        <!-- Add your site or application content here -->
        <canvas id="canvas" height="700" width="700">Joo cannot see me!</canvas>

        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.2.min.js"><\/script>')</script>
        <script src="js/plugins.js"></script>
        <script src="js/main.js"></script>

        <script>

            // Canvas Initialization
            var canvas = document.getElementById('canvas');
            var ctx = canvas.getContext("2d");

            // Objects
            var character = 0;
            var characterPosX = 0;
            var characterWidth = 50;

            function block() {
                this.posY = 0;
            }

            // Events
            document.onmousemove = moveChar;
            document.onclick = dropBlock;

            // Actions
            function moveChar(e) {
                characterPosX = e.pageX - 60;
                if(characterPosX < characterWidth) {characterPosX = 0;}
                if(characterPosX > canvas.width - characterWidth) {characterPosX = canvas.width - characterWidth;}
            };

            function dropBlock() {
                blocky = new block();
                blocky.posX = characterPosX;
                setInterval(function(){
                    blocky.posY++;

                    ctx.fillStyle = "green";
                    ctx.strokeStyle = "yellow";
                    ctx.fillRect(blocky.posX, blocky.posY, characterWidth, characterWidth);
                }, 1)
            };

            function crash() {
            };

            // Rendering
            function clear() {
                ctx.fillStyle = "#0BD";
                ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
            };

            function render() {
                clear();
                ctx.fillStyle = "red";
                ctx.strokeStyle = "blue";
                ctx.fillRect(characterPosX, 0, characterWidth, characterWidth);
            };

            // Execution
            window.setInterval(render, 30);

        </script>

        <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
        <script>
            var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
            (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
            g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
            s.parentNode.insertBefore(g,s)}(document,'script'));
        </script>
    </body>
</html>


text:
from time import time
from six.moves.urllib.parse import urlparse, urlunparse, urldefrag

from twisted.web.client import HTTPClientFactory
from twisted.web.http import HTTPClient
from twisted.internet import defer

from scrapy.http import Headers
from scrapy.utils.httpobj import urlparse_cached
from scrapy.responsetypes import responsetypes

def _parsed_url_args(parsed):
    path = urlunparse(('', '', parsed.path or '/', parsed.params, parsed.query, ''))
    host = parsed.hostname
    port = parsed.port
    scheme = parsed.scheme
    netloc = parsed.netloc
    if port is None:
        port = 443 if scheme == 'https' else 80
    return scheme, netloc, host, port, path

def _parse(url):
    url = url.strip()
    parsed = urlparse(url)
    return _parsed_url_args(parsed)

class ScrapyHTTPPageGetter(HTTPClient):

    delimiter = '\n'

    def connectionMade(self):
        self.headers = Headers() # bucket for response headers

        # Method command
        self.sendCommand(self.factory.method, self.factory.path)
        # Headers
        for key, values in self.factory.headers.items():
            for value in values:
                self.sendHeader(key, value)
        self.endHeaders()
        # Body
        if self.factory.body is not None:
            self.transport.write(self.factory.body)

    def lineReceived(self, line):
        return HTTPClient.lineReceived(self, line.rstrip())

    def handleHeader(self, key, value):
        self.headers.appendlist(key, value)

    def handleStatus(self, version, status, message):
        self.factory.gotStatus(version, status, message)

    def handleEndHeaders(self):
        self.factory.gotHeaders(self.headers)

    def connectionLost(self, reason):
        self._connection_lost_reason = reason
        HTTPClient.connectionLost(self, reason)
        self.factory.noPage(reason)

    def handleResponse(self, response):
        if self.factory.method.upper() == 'HEAD':
            self.factory.page('')
        elif self.length is not None and self.length > 0:
            self.factory.noPage(self._connection_lost_reason)
        else:
            self.factory.page(response)
        self.transport.loseConnection()

    def timeout(self):
        self.transport.loseConnection()
        self.factory.noPage(\
                defer.TimeoutError("Getting %s took longer than %s seconds." % \
                (self.factory.url, self.factory.timeout)))

class ScrapyHTTPClientFactory(HTTPClientFactory):
    """Scrapy implementation of the HTTPClientFactory overwriting the
    serUrl method to make use of our Url object that cache the parse
    result.
    """

    protocol = ScrapyHTTPPageGetter
    waiting = 1
    noisy = False
    followRedirect = False
    afterFoundGet = False

    def __init__(self, request, timeout=180):
        self.url = urldefrag(request.url)[0]
        self.method = request.method
        self.body = request.body or None
        self.headers = Headers(request.headers)
        self.response_headers = None
        self.timeout = request.meta.get('download_timeout') or timeout
        self.start_time = time()
        self.deferred = defer.Deferred().addCallback(self._build_response, request)

        # Fixes Twisted 11.1.0+ support as HTTPClientFactory is expected
        # to have _disconnectedDeferred. See Twisted r32329.
        # As Scrapy implements it's own logic to handle redirects is not
        # needed to add the callback _waitForDisconnect.
        # Specifically this avoids the AttributeError exception when
        # clientConnectionFailed method is called.
        self._disconnectedDeferred = defer.Deferred()

        self._set_connection_attributes(request)

        # set Host header based on url
        self.headers.setdefault('Host', self.netloc)

        # set Content-Length based len of body
        if self.body is not None:
            self.headers['Content-Length'] = len(self.body)
            # just in case a broken http/1.1 decides to keep connection alive
            self.headers.setdefault("Connection", "close")

    def _build_response(self, body, request):
        request.meta['download_latency'] = self.headers_time-self.start_time
        status = int(self.status)
        headers = Headers(self.response_headers)
        respcls = responsetypes.from_args(headers=headers, url=self.url)
        return respcls(url=self.url, status=status, headers=headers, body=body)

    def _set_connection_attributes(self, request):
        parsed = urlparse_cached(request)
        self.scheme, self.netloc, self.host, self.port, self.path = _parsed_url_args(parsed)
        proxy = request.meta.get('proxy')
        if proxy:
            self.scheme, _, self.host, self.port, _ = _parse(proxy)
            self.path = self.url

    def gotHeaders(self, headers):
        self.headers_time = time()
        self.response_headers = headers


text:
using std::min;
using std::max;
#include "multi_bspline_eval_sse_c_impl.h"


text:
import React from 'react';
import renderer from 'react-test-renderer';

import { ThemeProvider } from '@ui/theme';
import ExpiringAccountCard from './';

describe('the ExpiringAccountCard component', () => {
  it('should render with name, expirationDate, dateFormat, onPress, and iconFill', () => {
    const tree = renderer.create(
      <ThemeProvider>
        <ExpiringAccountCard
          name="Bank Account"
          expirationDate="02/20"
          dateFormat="lll"
          onPress={() => {}}
          iconFill="#ffffff"
        />
      </ThemeProvider>,
    );
    expect(tree).toMatchSnapshot();
  });
});


text:
package team2655.scriptcrafter.engine;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.Arrays;

import javax.swing.CellEditor;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

import team2655.scriptcrafter.gui.ConfigEditor;
import team2655.scriptcrafter.gui.ScriptCrafter;
import team2655.scriptcrafter.listener.CommandsListener;
import team2655.scriptcrafter.values.Values;

public class ScriptCrafterEngine implements ActionListener, WindowListener, Values, CommandsListener, ItemListener, PopupMenuListener, TableModelListener {

	ScriptCrafter crafter;

	public ScriptCrafterEngine(ScriptCrafter crafter){

		this.crafter = crafter;

	}

	//Handles Button Presses
	@Override
	public void actionPerformed(ActionEvent e){

		Object src = e.getSource();

		if(src == crafter.btnEditCommands){

			new ConfigEditor(this);

		}else if(src == crafter.btnFileNew){

			try{

				Object returned = JOptionPane.showInputDialog(new JDialog(), "New file name: ", "Create New File ", JOptionPane.QUESTION_MESSAGE);

				if(returned != null){

					if(returned.toString().matches(FILE_NAME_PATTERN)){

						CSVController.createScript(returned.toString());

						try{

							CSVController.saveFileQuiet(crafter.fileSelector.getSelectedItem().toString(), (DefaultTableModel)crafter.table.getModel());

						}catch(Exception error){

							System.out.println(error.getClass().getName() + ": " + error.getMessage());

						}

						crafter.clearTable();
						crafter.scanFiles(returned.toString());
						CSVController.loadScript(returned.toString(), (DefaultTableModel)crafter.table.getModel(), crafter);

					}else{

						JOptionPane.showMessageDialog(new JDialog(), "Invalid file name. File names can only contain letters, numbers and dashes or underscores.", "Invalid Name!", JOptionPane.WARNING_MESSAGE);

					}

				}

			}catch(Exception er){

				System.out.println("ERROR AT CREATE.....:::::\n\n\n");
				er.printStackTrace();
				System.out.println("END.....:::::\n\n\n\n\n");

			}

		}else if(src == crafter.btnFileRename){

			Object returned = JOptionPane.showInputDialog(new JDialog(), "Rename to: ", "Rename '" + crafter.fileSelector.getSelectedItem().toString() + "'", JOptionPane.QUESTION_MESSAGE, null, null, crafter.fileSelector.getSelectedItem().toString());

			if(returned != null){

				if(returned.toString().matches(FILE_NAME_PATTERN)){

					boolean done = CSVController.renameFile(crafter.fileSelector.getSelectedItem().toString(), returned.toString());

					if(done){

						crafter.scanFiles(returned.toString());

					}

				}else{

					JOptionPane.showMessageDialog(new JDialog(), "Invalid file name. File names can only contain letters, numbers and dashes or underscores.", "Invalid Name!", JOptionPane.WARNING_MESSAGE);

				}

			}

		}else if(src == crafter.btnFileDelete){

			int returned = JOptionPane.showConfirmDialog(new JDialog(), "Are you sure you want to delete '" + crafter.fileSelector.getSelectedItem().toString() + "'?", "Delete?", JOptionPane.YES_NO_OPTION);
			if(returned == JOptionPane.YES_OPTION){

				try {

					CSVController.deleteFile(crafter.fileSelector.getSelectedItem().toString());
					crafter.scanFiles(null);
					CSVController.loadScript(crafter.fileSelector.getSelectedItem().toString(), (DefaultTableModel) crafter.table.getModel(), crafter);

				} catch (Exception er) {
					er.printStackTrace();
					crafter.clearTable();
				}

			}

		}else if(src == crafter.btnSave){

			Object selectedItem = crafter.fileSelector.getSelectedItem();
			if(selectedItem == null){
				selectedItem = "";
			}

			if(selectedItem.toString().trim().equals("")){
				try{

					Object returned = JOptionPane.showInputDialog(new JDialog(), "New file name: ", "Create New File ", JOptionPane.QUESTION_MESSAGE);

					if(returned != null){

						if(returned.toString().matches(FILE_NAME_PATTERN)){

							CSVController.createScript(returned.toString());

							crafter.scanFiles(returned.toString());

						}else{

							JOptionPane.showMessageDialog(new JDialog(), "Invalid file name. File names can only contain letters, numbers and dashes or underscores.", "Invalid Name!", JOptionPane.WARNING_MESSAGE);

						}

					}

				}catch(Exception er){

					System.out.println("ERROR AT CREATE.....:::::\n\n\n");
					er.printStackTrace();
					System.out.println("END.....:::::\n\n\n\n\n");

				}
			}

			try{

				CellEditor editor = crafter.table.getCellEditor();

				if(editor != null){

					editor.stopCellEditing();

				}

				CSVController.saveFile(crafter.fileSelector.getSelectedItem().toString(), (DefaultTableModel)crafter.table.getModel());

			}catch(Exception er){

				JOptionPane.showMessageDialog(new JDialog(), "Save failed (is the driver station open?).", "Save Error!", JOptionPane.ERROR_MESSAGE);

			}

		}else if(src == crafter.btnDiscard){

			int rtn = JOptionPane.showConfirmDialog(new JDialog(), "Are you sure you want to discard ALL changes since the last save?", "Discard?", JOptionPane.YES_NO_CANCEL_OPTION);

			if(rtn == JOptionPane.YES_OPTION){

				try {

					DefaultTableModel model = (DefaultTableModel) crafter.table.getModel();

     			   	for (int i = model.getRowCount() - 1; i >= 0; i--) {

     			   		model.removeRow(i);

     			   	}

     			   	CSVController.loadScript(crafter.fileSelector.getSelectedItem().toString(), model, crafter);

				} catch (Exception er) {
					er.printStackTrace();
					crafter.clearTable();
				}

			}

		}else if(src == crafter.btnUp){

			crafter.moveRowUp();

		}else if(src == crafter.btnDown){

			crafter.moveRowDown();

		}else if(src == crafter.btnDelete){

			crafter.deleteRow();

		}

	}

	//Handles window events
	@Override
	public void windowActivated(WindowEvent e) {}

	@Override
	public void windowClosed(WindowEvent e) {}

	@Override
	public void windowClosing(WindowEvent e) {

		int rtn = JOptionPane.showConfirmDialog(new JDialog(), "Save before exit?", "Save?", JOptionPane.YES_NO_CANCEL_OPTION);

		if(rtn == JOptionPane.YES_OPTION){

			crafter.removeBlankRows();

			try {

				CellEditor editor = crafter.table.getCellEditor();

				if(editor != null){

					editor.stopCellEditing();

				}

				CSVController.saveFile(crafter.fileSelector.getSelectedItem().toString(), (DefaultTableModel)crafter.table.getModel());
				System.exit(0);

			} catch (Exception er) {

				int returned = JOptionPane.showConfirmDialog(new JDialog(), "The file was not saved (is the driver station open?). Exit anyways (will discard changes)?", "Save Error!", JOptionPane.ERROR_MESSAGE);
				er.printStackTrace();
				if(returned == JOptionPane.YES_OPTION){

					System.exit(0);

				}else{

				}

			}

		}else if(rtn == JOptionPane.NO_OPTION){

			System.exit(0);

		}

	}

	@Override
	public void windowDeactivated(WindowEvent e) {}

	@Override
	public void windowDeiconified(WindowEvent e) {}

	@Override
	public void windowIconified(WindowEvent e) {}

	@Override
	public void windowOpened(WindowEvent e) {}

	@Override
	public void commandsChanged() {

		crafter.setupColumnTypes();

	}

	//File selector events
	@Override
    public void itemStateChanged(ItemEvent e) {

		Object src = e.getSource();

		if(src == crafter.fileSelector && !crafter.scanning){

			if (e.getStateChange() == ItemEvent.SELECTED) {

				String newItem = (String) crafter.fileSelector.getSelectedItem();

				if(newItem != null){

					if(!newItem.equals(crafter.lastFileSelected)){

						try {

							CSVController.loadScript(crafter.fileSelector.getSelectedItem().toString(), (DefaultTableModel) crafter.table.getModel(), crafter);
							crafter.lastFileSelected = crafter.fileSelector.getSelectedItem().toString();

						} catch (Exception er) {
							er.printStackTrace();
							crafter.clearTable();
						}

					}

				}else{

					try{

						CSVController.createScript("DUMMY");

					}catch(Exception ex){

					}

				}

			}

		}

	}

	@Override
	public void popupMenuCanceled(PopupMenuEvent arg0) {}

	@Override
	public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {

		if(crafter.fileSelector.getSelectedItem().toString().equals(crafter.lastFileSelected)){

			crafter.blankRowCorrection();

		} //Otherwise the load will run and take care of it from the itemEvent

	}

	@Override
	public void popupMenuWillBecomeVisible(PopupMenuEvent e) {

		crafter.scanFiles(crafter.fileSelector.getSelectedItem().toString());

		int rtn = JOptionPane.YES_OPTION;
		if(rtn == JOptionPane.YES_OPTION){

			crafter.removeBlankRows();

			try {

				CellEditor editor = crafter.table.getCellEditor();

				if(editor != null){

					editor.stopCellEditing();

				}

				CSVController.saveFileQuiet(crafter.fileSelector.getSelectedItem().toString(), (DefaultTableModel)crafter.table.getModel());

			} catch (Exception er) {

				JOptionPane.showMessageDialog(new JDialog(), "The file was not saved (is the driver station open?).", "Save Error!", JOptionPane.ERROR_MESSAGE);
				er.printStackTrace();

			}

		}else if(rtn == JOptionPane.NO_OPTION){

		}

	}

	//Table change events
	@Override
	public void tableChanged(TableModelEvent e) {

		if(e.getColumn() == 0){

			try{

				ArrayList<String> commands = new ArrayList<>(Arrays.asList(CSVController.loadCommands()));
    			ArrayList<String> arguments = new ArrayList<>(Arrays.asList(CSVController.loadArguments()));
    			String command = ((DefaultTableModel)crafter.table.getModel()).getValueAt(e.getFirstRow(),  0).toString();
    			ArrayList<String> secArguments = new ArrayList<>(Arrays.asList(CSVController.loadSecondArguments()));

    			String argType = "";
    			String secArgType = "";

	        	try{

	        		argType = arguments.get(commands.indexOf(command));
	        		secArgType = secArguments.get(commands.indexOf(command));

	        	}catch(Exception er){

	        	}

	        	if(argType.equals(ARGUMENT_TYPE_NONE) || argType.trim().equals("")){

	        		((DefaultTableModel)crafter.table.getModel()).setValueAt("", e.getFirstRow(), 1);

	        	}

	        	if(secArgType.equals(ARGUMENT_TYPE_NONE) || argType.trim().equals("")){

	        		((DefaultTableModel)crafter.table.getModel()).setValueAt("", e.getFirstRow(), 2);

	        	}

			}catch(Exception er){

			}

		}

		if(!crafter.removing){

			crafter.blankRowCorrection();

		}

	}

}


text:
"VADER (Valence Aware Dictionary and sEntiment Reasoner) is a lexicon and rule-based sentiment analysis tool that is specifically attuned to sentiments expressed in social media."

Previously VADER was only available in python (https://github.com/cjhutto/vaderSentiment). I wanted to use it in C# so ported it over.

# Getting Started

VaderSharp supports:

- .NET Core
- .NET Framework 3.5 and above
- Mono & Xamarin
- UWP

To install VaderSharp, run the following command in the Package Manager Console:

```
Install-Package CodingUpAStorm.VaderSharp
```

# Usage

Import the package at the top of the page:

```c#
using VaderSharp;
```

Then just initialize an instance of SentimentIntensityAnalyzer and call it's PolarityScores method:

```c#
SentimentIntensityAnalyzer analyzer = new SentimentIntensityAnalyzer();

var results = analyzer.PolarityScores("Wow, this package is amazingly easy to use");

Console.WriteLine("Positive score: " + results.Positive);
Console.WriteLine("Negative score: " + results.Negative);
Console.WriteLine("Neutral score: " + results.Neutral);
Console.WriteLine("Compound score: " + results.Compound);
```


text:
#include ZZ_Prelude_hh
#include "CreateTestVectors.hh"
#include "zz/Generics/Set.hh"
#include "zz/Generics/Map.hh"
#include "Parser.hh"

/*
Creates input test-vectors for the basic types:
  Bool
  Int
  Int -> Bool
  Int -> Int
  (Int, Int) -> Int
  List<Int> -> List<Int>

and composite types:
    List<A>
    (A, B)
    (A, B, C)

Each basic type is subdivided into categories (small ints, big ints, negative ints, short lists
etc.). When creating tuples, first categories are combined, then elements of those categories.
*/

namespace ZZ {
using namespace std;

//mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm

struct TestGen {
    virtual Array<double const> catWeights() const = 0;
        // -- higher weights means proportionally more samples from that category will be used.

    virtual String generate(uint64& seed, uint cat) const = 0;
        // -- generate a sample from category 'cat'

    virtual ~TestGen() {}
};

// From now on, a generator 'Gen' is a shared pointer to a constant TestGen...
namespace { typedef shared_ptr<TestGen const> Gen; }

function<String()> getMixer(uint64 seed, Gen gen, Vec<uint> cats)
{
    Vec<double> weights = map(cats, [&](uint i){ return gen->catWeights()[i]; });
    double scale = 1.0 / foldl(weights, -std::numeric_limits<double>::infinity(), max_<double>);
    for (double& w : weights) w *= scale;

    Arr<uint>   cs(cats);
    Arr<double> ws(weights);
    return [=]() mutable {
        // Inefficient, but will do.
        for(;;){
            uint i = irand(seed, cs.size());
            if (drand(seed) < ws[i]) return fmt("%_", gen->generate(seed, cs[i]));
        }
    };
}

inline function<String()> getMixer(uint64 seed, Gen gen) {
    return getMixer(seed, gen, enumTo<uint>(gen->catWeights().size())); }

//=================================================================================================
// -- Bool:

struct TestGen_Bool : TestGen {
    Array<double const> catWeights() const override {
        static double const weights[] = { 1.0 };
        return Array_new(weights, elemsof(weights)); }

    String generate(uint64& seed, uint cat) const override {
        assert(cat == 0);
        return (irand(seed, 2) == 0) ? "_0" : "_1"; }
};

//=================================================================================================
// -- Int:

struct TestGen_Int : TestGen {
    Array<double const> catWeights() const override {
        // -- small, big, negative, pathological
        static double const weights[] = { 4, 2, 2, 1 };
        return Array_new(weights, elemsof(weights)); }

    String generate(uint64& seed, uint cat) const override;
};

template<int64 k=5>
int64 logPick(uint64& seed, int64 lim)
{
  #if defined(GOOGLE_CODE)
    const double logk = log(k);
  #else
    constexpr double logk = log(k);
  #endif
    assert(lim > 0);
    assert(lim < INT64_MAX);
    double r = drand(seed);
    int64 ret = int64(exp(r * (log(lim+k) - logk) + logk) - k);
    assert(ret >= 0);
    assert(ret < lim);
    return ret;
}

String TestGen_Int::generate(uint64& seed, uint cat) const
{
    auto helper = [&]() -> int64 {
        switch (cat){
        case 0: return logPick(seed, 20);
        case 1: return logPick(seed, 1ll << 30);
        case 2: return ~logPick<1>(seed, 1ll << 30);
        case 3:{
            switch (irand(seed, 6)){
            case 0: case 1: return INT64_MAX - logPick(seed, 5);
            case 2: case 3: return INT64_MIN + logPick(seed, 5);
            case 4:         return (INT64_MAX >> 1) + logPick(seed, 11) - 5;
            case 5:         return (INT64_MIN >> 1) + logPick(seed, 11) - 5;
            default: assert(false); }
        }
        default: assert(false); }
    };
    return fmt("%_", helper());
}

//=================================================================================================
// -- List<A>:

// Half of the lists will be from a single category of 'a_gen', half will be mixed.
struct TestGen_List : TestGen {
    Gen         a_gen;
    Arr<double> weights;
    String      type_name;
    mutable function<String()> a_mix;       // -- initialized at first call to 'generate()'

    TestGen_List(Gen a, String const& type_name);

    Array<double const> catWeights() const override { return weights.slice(); }
    String generate(uint64& seed, uint cat) const override;
};

TestGen_List::TestGen_List(Gen a, String const& type_name) :
    a_gen(a),
    type_name(type_name)
{
    Vec<double> ws;
    double sum = 0;
    for (double w : a_gen->catWeights()){
        sum += w;
        ws.push(w);     // -- single category
    }
    ws.push(sum);       // -- fully mixed category

    weights = Arr<double>(ws);
}

String TestGen_List::generate(uint64& seed, uint cat) const
{
    if (!a_mix)
        a_mix = getMixer(splitSeed(seed), a_gen);

    uint len = logPick<1>(seed, 50);
    Vec<String> result;
    if (cat == a_gen->catWeights().size()){
        for (uint i = 0; i < len; i++)
            result.push(a_mix());
    }else{
        for (uint i = 0; i < len; i++)
            result.push(a_gen->generate(seed, cat));
    }
    return fmt("list_[:%_ %_]", type_name, join(", ", result));
}

//=================================================================================================
// -- (A, B):

struct TestGen_Pair : TestGen {
    Gen         a_gen;
    Gen         b_gen;
    Arr<double> weights;

    TestGen_Pair(Gen a, Gen b);

    Array<double const> catWeights() const override { return weights.slice(); }
    String generate(uint64& seed, uint cat) const override;
};

TestGen_Pair::TestGen_Pair(Gen a, Gen b) :
    a_gen(a),
    b_gen(b)
{
    Vec<double> ws;
    for (double wa : a_gen->catWeights())
    for (double wb : b_gen->catWeights())
        ws.push(wa * wb);
    weights = Arr<double>(ws);
}

String TestGen_Pair::generate(uint64& seed, uint cat) const
{
    uint nb = b_gen->catWeights().size();
    return fmt("(%_, %_)", a_gen->generate(seed, cat / nb), b_gen->generate(seed, cat % nb));
}

//=================================================================================================
// -- (A, B, C):

struct TestGen_Trip : TestGen {
    Gen         a_gen;
    Gen         b_gen;
    Gen         c_gen;
    Arr<double> weights;

    TestGen_Trip(Gen a, Gen b, Gen c);

    Array<double const> catWeights() const override { return weights.slice(); }
    String generate(uint64& seed, uint cat) const override;
};

TestGen_Trip::TestGen_Trip(Gen a, Gen b, Gen c) :
    a_gen(a),
    b_gen(b),
    c_gen(c)
{
    Vec<double> ws;
    for (double wa : a_gen->catWeights())
    for (double wb : b_gen->catWeights())
    for (double wc : c_gen->catWeights())
        ws.push(wa * wb * wc);
    weights = Arr<double>(ws);
}

String TestGen_Trip::generate(uint64& seed, uint cat) const
{
    uint c = cat % c_gen->catWeights().size(); cat /= c_gen->catWeights().size();
    uint b = cat % b_gen->catWeights().size(); cat /= b_gen->catWeights().size();
    uint a = cat; assert(a < a_gen->catWeights().size());
    return fmt("(%_, %_, %_)", a_gen->generate(seed, a), b_gen->generate(seed, b), c_gen->generate(seed, c));
}

//=================================================================================================
// -- Finite set:

struct TestGen_FiniteSet : TestGen {
    Vec<String> set;
    TestGen_FiniteSet(Vec<String> const& set0) : set(copy_, set0) {}
    template<size_t sz> TestGen_FiniteSet(cchar* (&set0) [sz]) : set(copy_, Array_new(set0, elemsof(set0))) {}

    Array<double const> catWeights() const override {
        static double const weights[] = { 1.0 };
        return Array_new(weights, elemsof(weights)); }

    String generate(uint64& seed, uint cat) const override {
        assert(cat == 0);
        return set[irand(seed, set.size())]; }
};

static cchar* funs_Int_to_Bool[] = {
    "is_zero_",
    "is_even_",
    "is_pow2_",
    "is_nonzero_",
};

static cchar* funs_Int_to_Int[] = {
    "rand_unop_",
    "dec_",
    "inc_",
    "sq_",
    "dbl_",
    "abs_",
    "sign_",
    "neg_",
    "inv_",
};

static cchar* funs_IntInt_to_Int[] = {
    "rand_binop_",
    "add_",
    "sub_",
    "mul_",
    "div_",
    "mod_",
    "lshift_",
    "rshift_",
    "urshift_",
    "bit_and_",
    "bit_or_",
    "bit_xor_",
};

static cchar* funs_Ints_to_Ints[] = {
    "list_reverse_<Int>",
    "list_rotate_<Int>",
    "tail_<Int>",
};

//mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
// Main:

class TestGenMgr {
    Map<Type, Gen> type2gen;
public:
    Gen getGen(Type const& type);
};

Gen TestGenMgr::getGen(Type const& type)
{
    Gen* val;
    if (!type2gen.getI(type, val)){
        if (type == Type(a_Bool))
            *val = make_shared<TestGen_Bool>();
        else if (type == Type(a_Int))
            *val = make_shared<TestGen_Int>();
        else if (type.name == a_List)
            *val = make_shared<TestGen_List>(getGen(type[0]), fmt("%_", type[0]));
        else if (type == Type(a_Fun, Type(a_Int), Type(a_Bool)))
            *val = make_shared<TestGen_FiniteSet>(funs_Int_to_Bool);
        else if (type == Type(a_Fun, Type(a_Int), Type(a_Int)))
            *val = make_shared<TestGen_FiniteSet>(funs_Int_to_Int);
        else if (type == Type(a_Fun, Type(a_Tuple, Type(a_Int), Type(a_Int)), Type(a_Int)))
            *val = make_shared<TestGen_FiniteSet>(funs_IntInt_to_Int);
        else if (type == Type(a_Fun, Type(a_List, Type(a_Int)), Type(a_List, Type(a_Int))))
            *val = make_shared<TestGen_FiniteSet>(funs_Ints_to_Ints);
        else if (type.name == a_Tuple){
            if (type.size() == 2)
                *val = make_shared<TestGen_Pair>(getGen(type[0]), getGen(type[1]));
            else if (type.size() == 3)
                *val = make_shared<TestGen_Trip>(getGen(type[0]), getGen(type[1]), getGen(type[2]));
            else{
                wrLn("ERROR! Cannot handle tuples of size > 3 in testpattern generation.");
                exit(1);
            }
        }else{
            wrLn("ERROR! No testpattern generator defined for: %_", type);
            exit(1);
        }
    }
    return *val;
}

static
Vec<String> genN(function<String()>& mix, uint n_patterns, uint64& seed)
{
    Set<String> result;
    uint n_tries = 0;
    while (result.size() < n_patterns && n_tries < 1000){
        if (result.add(mix()))
            n_tries++;      // -- test-pattern already exists
        else
            n_tries = 0;
    }

    Vec<String> vec;
    For_Set(result){ vec.push(Set_Key(result)); }
    shuffle(seed, vec);

    return vec;
}

static
void writeTestVectors(Out& out, Type const& type, function<String()>& mix, uint n_patterns, uint64& seed)
{
    wrLn("##if (match<T, %_>,", type);
    wrLn(out, "    [:%_", type);
    for (String const& text : genN(mix, n_patterns, seed))
        wrLn(out, "        %_,", text);
    wrLn(out, "    ],");
}

static
void addSubtypes(Vec<Type>& types, Type const& t)
{
    if (!has(types, t)) types.push(t);
    for (Type const& s : t)
        addSubtypes(types, s);
}

// 'cat' is just used for debugging test-pattern generation. 'closed_set' means add subtypes of 'types' to itself.
void genTestVectors(Out& out, String var_name, uint n_patterns, uint64 seed, uint cat, Vec<Type> const& types0, bool closed_set)
{
    Vec<Type> types(copy_, types0);
    if (closed_set)
        for (Type const& t : types0)
            addSubtypes(types, t);

    TestGenMgr mgr;

    wrLn(out, "##include \"std.evo\";\n");
    wrLn(out, "rec %_<T> : [T] =", var_name);
    for (Type const& type : types){
        auto mix = (cat == UINT_MAX) ? getMixer(seed, mgr.getGen(type)) : getMixer(seed, mgr.getGen(type), {cat});
        writeTestVectors(out, type, mix, n_patterns, seed);
    }
    wrLn(out, "##error :T \"No test pattern defined for type\"%)r;", types.size());

    // Instantiate templates for incremental compilation:
    newLn(out);
    for (Type const& type : types)
        wrLn(out, "%_<%_>;", var_name, type);
}

void genTestVectors(Out& out, String var_name, uint n_patterns, uint64 seed, uint cat, String types_filename, bool closed_set)
{
    Str text = readFile(types_filename);
    if (!text){ wrLn("ERROR! Could not read file: %_", types_filename); exit(1); }
    Vec<Str> fs;
    strictSplitArray(text, ";", fs);
    Vec<Type> types;
    for (Str type_text : fs){
        try{
            String text(type_text);
            trim(text);
            if (text.size() > 0)
                types.push(parseType(text.c_str()));
        }catch (Excp_ParseError err){
            wrLn("PARSE ERROR! %_", err.msg); exit(1);
        }
    }
    dispose(text);

    genTestVectors(out, var_name, n_patterns, seed, cat, types, closed_set);
}

//mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
}


text:
namespace divida
{
	extern const std::string c_toStringInvalidWeakPointer;
	extern const std::string c_toStringNull;
	extern const std::string c_toStringObjectBegin;
	extern const std::string c_toStringObjectEnd;
	extern const std::string c_toStringDelimiter;
}

// output stream operators for divida types
std::ostream& operator<<(std::ostream& o, const divida::beneficiary& beneficiary);
std::ostream& operator<<(std::ostream& o, const divida::date& date);
std::ostream& operator<<(std::ostream& o, const divida::expense& expense);
std::ostream& operator<<(std::ostream& o, const divida::item& item);
std::ostream& operator<<(std::ostream& o, const divida::person& person);
std::ostream& operator<<(std::ostream& o, const divida::transaction& transaction);

// output stream operators for generic common types
template<typename T>
std::ostream& operator<<(std::ostream& o, const std::vector<T>& vector)
{
	o << divida::c_toStringObjectBegin;
	for (unsigned int i = 0; i < vector.size(); i++)
	{
		o << vector[i];
		if (i < vector.size() - 1)
			o << divida::c_toStringDelimiter;
	}
	o << divida::c_toStringObjectEnd;

	return o;
}

template<typename T>
std::ostream& operator<<(std::ostream& o, const std::unique_ptr<T>& ptr)
{
	if (ptr != nullptr)
		return o << *ptr;
	else
		return o << divida::c_toStringNull;
}

template<typename T>
std::ostream& operator<<(std::ostream& o, const std::shared_ptr<T>& ptr)
{
	if (ptr != nullptr)
		return o << *ptr;
	else
		return o << divida::c_toStringNull;
}

template<typename T>
std::ostream& operator<<(std::ostream& o, const std::weak_ptr<T>& ptr)
{
	if (auto sharedPtr = ptr.lock())
		return o << sharedPtr;
	else
		return o << divida::c_toStringInvalidWeakPointer;
}

namespace divida
{
	template<typename T>
	std::string to_string(const std::unique_ptr<T>& ptr)
	{
		std::ostringstream s;
		s << ptr;
		return s.str();
	}

	template<typename T>
	std::string to_string(const std::shared_ptr<T>& ptr)
	{
		std::ostringstream s;
		s << ptr;
		return s.str();
	}

	template<typename T>
	std::string to_string(const std::weak_ptr<T>& ptr)
	{
		std::ostringstream s;
		s << ptr;
		return s.str();
	}

	std::string to_string(const divida::beneficiary& beneficiary);
	std::string to_string(const divida::date& date);
	std::string to_string(const divida::expense& expense);
	std::string to_string(const divida::item& item);
	std::string to_string(const divida::person& person);
	std::string to_string(const divida::transaction& transaction);
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Laurus parthenoxylon Jack

### Remarks
null


text:
favicon::LargeIconService* LargeIconServiceFactory::GetForBrowserContext(
    content::BrowserContext* context) {
  return static_cast<favicon::LargeIconService*>(
      GetInstance()->GetServiceForBrowserContext(context, true));
}

// static
LargeIconServiceFactory* LargeIconServiceFactory::GetInstance() {
  return base::Singleton<LargeIconServiceFactory>::get();
}

LargeIconServiceFactory::LargeIconServiceFactory()
    : BrowserContextKeyedServiceFactory(
        "LargeIconService",
        BrowserContextDependencyManager::GetInstance()) {
  DependsOn(FaviconServiceFactory::GetInstance());
}

LargeIconServiceFactory::~LargeIconServiceFactory() {}

KeyedService* LargeIconServiceFactory::BuildServiceInstanceFor(
    content::BrowserContext* context) const {
  favicon::FaviconService* favicon_service =
      FaviconServiceFactory::GetForProfile(Profile::FromBrowserContext(context),
                                           ServiceAccessType::EXPLICIT_ACCESS);
  return new favicon::LargeIconService(
      favicon_service, content::BrowserThread::GetBlockingPool()
                           ->GetTaskRunnerWithShutdownBehavior(
                               base::SequencedWorkerPool::SKIP_ON_SHUTDOWN));
}

bool LargeIconServiceFactory::ServiceIsNULLWhileTesting() const {
  return true;
}


text: package foo<caret>