max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,968 |
//////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: <EMAIL>
//
//////////////////////////////////////////////////////////////////////////////
package com.ansca.corona.maps;
public class MapMarkerTask implements com.ansca.corona.CoronaRuntimeTask {
MapMarker fMarker;
public MapMarkerTask(MapMarker marker)
{
fMarker = marker;
}
@Override
public void executeUsing(com.ansca.corona.CoronaRuntime runtime) {
if (fMarker.getListener() == com.ansca.corona.CoronaLua.REFNIL ||
fMarker.getListener() == com.ansca.corona.CoronaLua.NOREF) {
return;
}
com.ansca.corona.JavaToNativeShim.mapMarkerEvent(
runtime, fMarker.getMarkerId(), fMarker.getListener(), fMarker.getLatitude(), fMarker.getLongitude());
}
}
| 304 |
335 |
<filename>code/src/mupen64plus-video-paraLLEl/parallel-rdp/vulkan/command_buffer.hpp
/* Copyright (c) 2017-2020 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "buffer.hpp"
#include "buffer_pool.hpp"
#include "vulkan_headers.hpp"
#include "image.hpp"
#include "pipeline_event.hpp"
#include "query_pool.hpp"
#include "render_pass.hpp"
#include "sampler.hpp"
#include "shader.hpp"
#include "vulkan_common.hpp"
#include <string.h>
namespace Vulkan
{
class DebugChannelInterface;
enum CommandBufferDirtyBits
{
COMMAND_BUFFER_DIRTY_STATIC_STATE_BIT = 1 << 0,
COMMAND_BUFFER_DIRTY_PIPELINE_BIT = 1 << 1,
COMMAND_BUFFER_DIRTY_VIEWPORT_BIT = 1 << 2,
COMMAND_BUFFER_DIRTY_SCISSOR_BIT = 1 << 3,
COMMAND_BUFFER_DIRTY_DEPTH_BIAS_BIT = 1 << 4,
COMMAND_BUFFER_DIRTY_STENCIL_REFERENCE_BIT = 1 << 5,
COMMAND_BUFFER_DIRTY_STATIC_VERTEX_BIT = 1 << 6,
COMMAND_BUFFER_DIRTY_PUSH_CONSTANTS_BIT = 1 << 7,
COMMAND_BUFFER_DYNAMIC_BITS = COMMAND_BUFFER_DIRTY_VIEWPORT_BIT | COMMAND_BUFFER_DIRTY_SCISSOR_BIT |
COMMAND_BUFFER_DIRTY_DEPTH_BIAS_BIT |
COMMAND_BUFFER_DIRTY_STENCIL_REFERENCE_BIT
};
using CommandBufferDirtyFlags = uint32_t;
#define COMPARE_OP_BITS 3
#define STENCIL_OP_BITS 3
#define BLEND_FACTOR_BITS 5
#define BLEND_OP_BITS 3
#define CULL_MODE_BITS 2
#define FRONT_FACE_BITS 1
union PipelineState {
struct
{
// Depth state.
unsigned depth_write : 1;
unsigned depth_test : 1;
unsigned blend_enable : 1;
unsigned cull_mode : CULL_MODE_BITS;
unsigned front_face : FRONT_FACE_BITS;
unsigned depth_bias_enable : 1;
unsigned depth_compare : COMPARE_OP_BITS;
unsigned stencil_test : 1;
unsigned stencil_front_fail : STENCIL_OP_BITS;
unsigned stencil_front_pass : STENCIL_OP_BITS;
unsigned stencil_front_depth_fail : STENCIL_OP_BITS;
unsigned stencil_front_compare_op : COMPARE_OP_BITS;
unsigned stencil_back_fail : STENCIL_OP_BITS;
unsigned stencil_back_pass : STENCIL_OP_BITS;
unsigned stencil_back_depth_fail : STENCIL_OP_BITS;
unsigned stencil_back_compare_op : COMPARE_OP_BITS;
unsigned alpha_to_coverage : 1;
unsigned alpha_to_one : 1;
unsigned sample_shading : 1;
unsigned src_color_blend : BLEND_FACTOR_BITS;
unsigned dst_color_blend : BLEND_FACTOR_BITS;
unsigned color_blend_op : BLEND_OP_BITS;
unsigned src_alpha_blend : BLEND_FACTOR_BITS;
unsigned dst_alpha_blend : BLEND_FACTOR_BITS;
unsigned alpha_blend_op : BLEND_OP_BITS;
unsigned primitive_restart : 1;
unsigned topology : 4;
unsigned wireframe : 1;
unsigned subgroup_control_size : 1;
unsigned subgroup_full_group : 1;
unsigned subgroup_minimum_size_log2 : 3;
unsigned subgroup_maximum_size_log2 : 3;
unsigned conservative_raster : 1;
uint32_t write_mask;
} state;
uint32_t words[4];
};
struct PotentialState
{
float blend_constants[4];
uint32_t spec_constants[VULKAN_NUM_SPEC_CONSTANTS];
uint8_t spec_constant_mask;
};
struct DynamicState
{
float depth_bias_constant = 0.0f;
float depth_bias_slope = 0.0f;
uint8_t front_compare_mask = 0;
uint8_t front_write_mask = 0;
uint8_t front_reference = 0;
uint8_t back_compare_mask = 0;
uint8_t back_write_mask = 0;
uint8_t back_reference = 0;
};
struct VertexAttribState
{
uint32_t binding;
VkFormat format;
uint32_t offset;
};
struct IndexState
{
VkBuffer buffer;
VkDeviceSize offset;
VkIndexType index_type;
};
struct VertexBindingState
{
VkBuffer buffers[VULKAN_NUM_VERTEX_BUFFERS];
VkDeviceSize offsets[VULKAN_NUM_VERTEX_BUFFERS];
};
enum CommandBufferSavedStateBits
{
COMMAND_BUFFER_SAVED_BINDINGS_0_BIT = 1u << 0,
COMMAND_BUFFER_SAVED_BINDINGS_1_BIT = 1u << 1,
COMMAND_BUFFER_SAVED_BINDINGS_2_BIT = 1u << 2,
COMMAND_BUFFER_SAVED_BINDINGS_3_BIT = 1u << 3,
COMMAND_BUFFER_SAVED_BINDINGS_4_BIT = 1u << 4,
COMMAND_BUFFER_SAVED_BINDINGS_5_BIT = 1u << 5,
COMMAND_BUFFER_SAVED_BINDINGS_6_BIT = 1u << 6,
COMMAND_BUFFER_SAVED_BINDINGS_7_BIT = 1u << 7,
COMMAND_BUFFER_SAVED_VIEWPORT_BIT = 1u << 8,
COMMAND_BUFFER_SAVED_SCISSOR_BIT = 1u << 9,
COMMAND_BUFFER_SAVED_RENDER_STATE_BIT = 1u << 10,
COMMAND_BUFFER_SAVED_PUSH_CONSTANT_BIT = 1u << 11
};
static_assert(VULKAN_NUM_DESCRIPTOR_SETS == 8, "Number of descriptor sets != 8.");
using CommandBufferSaveStateFlags = uint32_t;
struct CommandBufferSavedState
{
CommandBufferSaveStateFlags flags = 0;
ResourceBindings bindings;
VkViewport viewport;
VkRect2D scissor;
PipelineState static_state;
PotentialState potential_static_state;
DynamicState dynamic_state;
};
struct DeferredPipelineCompile
{
Program *program;
const RenderPass *compatible_render_pass;
PipelineState static_state;
PotentialState potential_static_state;
VertexAttribState attribs[VULKAN_NUM_VERTEX_ATTRIBS];
VkDeviceSize strides[VULKAN_NUM_VERTEX_BUFFERS];
VkVertexInputRate input_rates[VULKAN_NUM_VERTEX_BUFFERS];
unsigned subpass_index;
Util::Hash hash;
VkPipelineCache cache;
};
class CommandBuffer;
struct CommandBufferDeleter
{
void operator()(CommandBuffer *cmd);
};
class Device;
class CommandBuffer : public Util::IntrusivePtrEnabled<CommandBuffer, CommandBufferDeleter, HandleCounter>
{
public:
friend struct CommandBufferDeleter;
enum class Type
{
Generic,
AsyncGraphics,
AsyncCompute,
AsyncTransfer,
Count
};
~CommandBuffer();
VkCommandBuffer get_command_buffer() const
{
return cmd;
}
void begin_region(const char *name, const float *color = nullptr);
void end_region();
Device &get_device()
{
return *device;
}
bool swapchain_touched() const
{
return uses_swapchain;
}
void set_thread_index(unsigned index_)
{
thread_index = index_;
}
unsigned get_thread_index() const
{
return thread_index;
}
void set_is_secondary()
{
is_secondary = true;
}
bool get_is_secondary() const
{
return is_secondary;
}
void clear_image(const Image &image, const VkClearValue &value);
void clear_image(const Image &image, const VkClearValue &value, VkImageAspectFlags aspect);
void clear_quad(unsigned attachment, const VkClearRect &rect, const VkClearValue &value,
VkImageAspectFlags = VK_IMAGE_ASPECT_COLOR_BIT);
void clear_quad(const VkClearRect &rect, const VkClearAttachment *attachments, unsigned num_attachments);
void fill_buffer(const Buffer &dst, uint32_t value);
void fill_buffer(const Buffer &dst, uint32_t value, VkDeviceSize offset, VkDeviceSize size);
void copy_buffer(const Buffer &dst, VkDeviceSize dst_offset, const Buffer &src, VkDeviceSize src_offset,
VkDeviceSize size);
void copy_buffer(const Buffer &dst, const Buffer &src);
void copy_buffer(const Buffer &dst, const Buffer &src, const VkBufferCopy *copies, size_t count);
void copy_image(const Image &dst, const Image &src);
void copy_image(const Image &dst, const Image &src,
const VkOffset3D &dst_offset, const VkOffset3D &src_offset,
const VkExtent3D &extent,
const VkImageSubresourceLayers &dst_subresource,
const VkImageSubresourceLayers &src_subresource);
void copy_buffer_to_image(const Image &image, const Buffer &buffer, VkDeviceSize buffer_offset,
const VkOffset3D &offset, const VkExtent3D &extent, unsigned row_length,
unsigned slice_height, const VkImageSubresourceLayers &subresrouce);
void copy_buffer_to_image(const Image &image, const Buffer &buffer, unsigned num_blits, const VkBufferImageCopy *blits);
void copy_image_to_buffer(const Buffer &buffer, const Image &image, unsigned num_blits, const VkBufferImageCopy *blits);
void copy_image_to_buffer(const Buffer &dst, const Image &src, VkDeviceSize buffer_offset, const VkOffset3D &offset,
const VkExtent3D &extent, unsigned row_length, unsigned slice_height,
const VkImageSubresourceLayers &subresrouce);
void full_barrier();
void pixel_barrier();
void barrier(VkPipelineStageFlags src_stage, VkAccessFlags src_access, VkPipelineStageFlags dst_stage,
VkAccessFlags dst_access);
PipelineEvent signal_event(VkPipelineStageFlags stages);
void wait_events(unsigned num_events, const VkEvent *events,
VkPipelineStageFlags src_stages, VkPipelineStageFlags dst_stages,
unsigned barriers, const VkMemoryBarrier *globals,
unsigned buffer_barriers, const VkBufferMemoryBarrier *buffers,
unsigned image_barriers, const VkImageMemoryBarrier *images);
void barrier(VkPipelineStageFlags src_stages, VkPipelineStageFlags dst_stages,
unsigned barriers, const VkMemoryBarrier *globals,
unsigned buffer_barriers, const VkBufferMemoryBarrier *buffers,
unsigned image_barriers, const VkImageMemoryBarrier *images);
void buffer_barrier(const Buffer &buffer, VkPipelineStageFlags src_stage, VkAccessFlags src_access,
VkPipelineStageFlags dst_stage, VkAccessFlags dst_access);
void image_barrier(const Image &image, VkImageLayout old_layout, VkImageLayout new_layout,
VkPipelineStageFlags src_stage, VkAccessFlags src_access, VkPipelineStageFlags dst_stage,
VkAccessFlags dst_access);
void blit_image(const Image &dst,
const Image &src,
const VkOffset3D &dst_offset0, const VkOffset3D &dst_extent,
const VkOffset3D &src_offset0, const VkOffset3D &src_extent, unsigned dst_level, unsigned src_level,
unsigned dst_base_layer = 0, uint32_t src_base_layer = 0, unsigned num_layers = 1,
VkFilter filter = VK_FILTER_LINEAR);
// Prepares an image to have its mipmap generated.
// Puts the top-level into TRANSFER_SRC_OPTIMAL, and all other levels are invalidated with an UNDEFINED -> TRANSFER_DST_OPTIMAL.
void barrier_prepare_generate_mipmap(const Image &image, VkImageLayout base_level_layout, VkPipelineStageFlags src_stage, VkAccessFlags src_access,
bool need_top_level_barrier = true);
// The image must have been transitioned with barrier_prepare_generate_mipmap before calling this function.
// After calling this function, the image will be entirely in TRANSFER_SRC_OPTIMAL layout.
// Wait for TRANSFER stage to drain before transitioning away from TRANSFER_SRC_OPTIMAL.
void generate_mipmap(const Image &image);
void begin_render_pass(const RenderPassInfo &info, VkSubpassContents contents = VK_SUBPASS_CONTENTS_INLINE);
void next_subpass(VkSubpassContents contents = VK_SUBPASS_CONTENTS_INLINE);
void end_render_pass();
void submit_secondary(Util::IntrusivePtr<CommandBuffer> secondary);
inline unsigned get_current_subpass() const
{
return pipeline_state.subpass_index;
}
Util::IntrusivePtr<CommandBuffer> request_secondary_command_buffer(unsigned thread_index, unsigned subpass);
static Util::IntrusivePtr<CommandBuffer> request_secondary_command_buffer(Device &device,
const RenderPassInfo &rp, unsigned thread_index, unsigned subpass);
void set_program(Program *program);
#ifdef GRANITE_VULKAN_FILESYSTEM
// Convenience functions for one-off shader binds.
void set_program(const std::string &vertex, const std::string &fragment, const std::vector<std::pair<std::string, int>> &defines = {});
void set_program(const std::string &compute, const std::vector<std::pair<std::string, int>> &defines = {});
#endif
void set_buffer_view(unsigned set, unsigned binding, const BufferView &view);
void set_input_attachments(unsigned set, unsigned start_binding);
void set_texture(unsigned set, unsigned binding, const ImageView &view);
void set_unorm_texture(unsigned set, unsigned binding, const ImageView &view);
void set_srgb_texture(unsigned set, unsigned binding, const ImageView &view);
void set_texture(unsigned set, unsigned binding, const ImageView &view, const Sampler &sampler);
void set_texture(unsigned set, unsigned binding, const ImageView &view, StockSampler sampler);
void set_storage_texture(unsigned set, unsigned binding, const ImageView &view);
void set_sampler(unsigned set, unsigned binding, const Sampler &sampler);
void set_sampler(unsigned set, unsigned binding, StockSampler sampler);
void set_uniform_buffer(unsigned set, unsigned binding, const Buffer &buffer);
void set_uniform_buffer(unsigned set, unsigned binding, const Buffer &buffer, VkDeviceSize offset,
VkDeviceSize range);
void set_storage_buffer(unsigned set, unsigned binding, const Buffer &buffer);
void set_storage_buffer(unsigned set, unsigned binding, const Buffer &buffer, VkDeviceSize offset,
VkDeviceSize range);
void set_bindless(unsigned set, VkDescriptorSet desc_set);
void push_constants(const void *data, VkDeviceSize offset, VkDeviceSize range);
void *allocate_constant_data(unsigned set, unsigned binding, VkDeviceSize size);
template <typename T>
T *allocate_typed_constant_data(unsigned set, unsigned binding, unsigned count)
{
return static_cast<T *>(allocate_constant_data(set, binding, count * sizeof(T)));
}
void *allocate_vertex_data(unsigned binding, VkDeviceSize size, VkDeviceSize stride,
VkVertexInputRate step_rate = VK_VERTEX_INPUT_RATE_VERTEX);
void *allocate_index_data(VkDeviceSize size, VkIndexType index_type);
void *update_buffer(const Buffer &buffer, VkDeviceSize offset, VkDeviceSize size);
void *update_image(const Image &image, const VkOffset3D &offset, const VkExtent3D &extent, uint32_t row_length,
uint32_t image_height, const VkImageSubresourceLayers &subresource);
void *update_image(const Image &image, uint32_t row_length = 0, uint32_t image_height = 0);
void set_viewport(const VkViewport &viewport);
const VkViewport &get_viewport() const;
void set_scissor(const VkRect2D &rect);
void set_vertex_attrib(uint32_t attrib, uint32_t binding, VkFormat format, VkDeviceSize offset);
void set_vertex_binding(uint32_t binding, const Buffer &buffer, VkDeviceSize offset, VkDeviceSize stride,
VkVertexInputRate step_rate = VK_VERTEX_INPUT_RATE_VERTEX);
void set_index_buffer(const Buffer &buffer, VkDeviceSize offset, VkIndexType index_type);
void draw(uint32_t vertex_count, uint32_t instance_count = 1, uint32_t first_vertex = 0,
uint32_t first_instance = 0);
void draw_indexed(uint32_t index_count, uint32_t instance_count = 1, uint32_t first_index = 0,
int32_t vertex_offset = 0, uint32_t first_instance = 0);
void dispatch(uint32_t groups_x, uint32_t groups_y, uint32_t groups_z);
void draw_indirect(const Buffer &buffer, uint32_t offset, uint32_t draw_count, uint32_t stride);
void draw_indexed_indirect(const Buffer &buffer, uint32_t offset, uint32_t draw_count, uint32_t stride);
void draw_multi_indirect(const Buffer &buffer, uint32_t offset, uint32_t draw_count, uint32_t stride,
const Buffer &count, uint32_t count_offset);
void draw_indexed_multi_indirect(const Buffer &buffer, uint32_t offset, uint32_t draw_count, uint32_t stride,
const Buffer &count, uint32_t count_offset);
void dispatch_indirect(const Buffer &buffer, uint32_t offset);
void set_opaque_state();
void set_quad_state();
void set_opaque_sprite_state();
void set_transparent_sprite_state();
void save_state(CommandBufferSaveStateFlags flags, CommandBufferSavedState &state);
void restore_state(const CommandBufferSavedState &state);
#define SET_STATIC_STATE(value) \
do \
{ \
if (pipeline_state.static_state.state.value != value) \
{ \
pipeline_state.static_state.state.value = value; \
set_dirty(COMMAND_BUFFER_DIRTY_STATIC_STATE_BIT); \
} \
} while (0)
#define SET_POTENTIALLY_STATIC_STATE(value) \
do \
{ \
if (pipeline_state.potential_static_state.value != value) \
{ \
pipeline_state.potential_static_state.value = value; \
set_dirty(COMMAND_BUFFER_DIRTY_STATIC_STATE_BIT); \
} \
} while (0)
inline void set_depth_test(bool depth_test, bool depth_write)
{
SET_STATIC_STATE(depth_test);
SET_STATIC_STATE(depth_write);
}
inline void set_wireframe(bool wireframe)
{
SET_STATIC_STATE(wireframe);
}
inline void set_depth_compare(VkCompareOp depth_compare)
{
SET_STATIC_STATE(depth_compare);
}
inline void set_blend_enable(bool blend_enable)
{
SET_STATIC_STATE(blend_enable);
}
inline void set_blend_factors(VkBlendFactor src_color_blend, VkBlendFactor src_alpha_blend,
VkBlendFactor dst_color_blend, VkBlendFactor dst_alpha_blend)
{
SET_STATIC_STATE(src_color_blend);
SET_STATIC_STATE(dst_color_blend);
SET_STATIC_STATE(src_alpha_blend);
SET_STATIC_STATE(dst_alpha_blend);
}
inline void set_blend_factors(VkBlendFactor src_blend, VkBlendFactor dst_blend)
{
set_blend_factors(src_blend, src_blend, dst_blend, dst_blend);
}
inline void set_blend_op(VkBlendOp color_blend_op, VkBlendOp alpha_blend_op)
{
SET_STATIC_STATE(color_blend_op);
SET_STATIC_STATE(alpha_blend_op);
}
inline void set_blend_op(VkBlendOp blend_op)
{
set_blend_op(blend_op, blend_op);
}
inline void set_depth_bias(bool depth_bias_enable)
{
SET_STATIC_STATE(depth_bias_enable);
}
inline void set_color_write_mask(uint32_t write_mask)
{
SET_STATIC_STATE(write_mask);
}
inline void set_stencil_test(bool stencil_test)
{
SET_STATIC_STATE(stencil_test);
}
inline void set_stencil_front_ops(VkCompareOp stencil_front_compare_op, VkStencilOp stencil_front_pass,
VkStencilOp stencil_front_fail, VkStencilOp stencil_front_depth_fail)
{
SET_STATIC_STATE(stencil_front_compare_op);
SET_STATIC_STATE(stencil_front_pass);
SET_STATIC_STATE(stencil_front_fail);
SET_STATIC_STATE(stencil_front_depth_fail);
}
inline void set_stencil_back_ops(VkCompareOp stencil_back_compare_op, VkStencilOp stencil_back_pass,
VkStencilOp stencil_back_fail, VkStencilOp stencil_back_depth_fail)
{
SET_STATIC_STATE(stencil_back_compare_op);
SET_STATIC_STATE(stencil_back_pass);
SET_STATIC_STATE(stencil_back_fail);
SET_STATIC_STATE(stencil_back_depth_fail);
}
inline void set_stencil_ops(VkCompareOp stencil_compare_op, VkStencilOp stencil_pass, VkStencilOp stencil_fail,
VkStencilOp stencil_depth_fail)
{
set_stencil_front_ops(stencil_compare_op, stencil_pass, stencil_fail, stencil_depth_fail);
set_stencil_back_ops(stencil_compare_op, stencil_pass, stencil_fail, stencil_depth_fail);
}
inline void set_primitive_topology(VkPrimitiveTopology topology)
{
SET_STATIC_STATE(topology);
}
inline void set_primitive_restart(bool primitive_restart)
{
SET_STATIC_STATE(primitive_restart);
}
inline void set_multisample_state(bool alpha_to_coverage, bool alpha_to_one = false, bool sample_shading = false)
{
SET_STATIC_STATE(alpha_to_coverage);
SET_STATIC_STATE(alpha_to_one);
SET_STATIC_STATE(sample_shading);
}
inline void set_front_face(VkFrontFace front_face)
{
SET_STATIC_STATE(front_face);
}
inline void set_cull_mode(VkCullModeFlags cull_mode)
{
SET_STATIC_STATE(cull_mode);
}
inline void set_blend_constants(const float blend_constants[4])
{
SET_POTENTIALLY_STATIC_STATE(blend_constants[0]);
SET_POTENTIALLY_STATIC_STATE(blend_constants[1]);
SET_POTENTIALLY_STATIC_STATE(blend_constants[2]);
SET_POTENTIALLY_STATIC_STATE(blend_constants[3]);
}
inline void set_specialization_constant_mask(uint32_t spec_constant_mask)
{
VK_ASSERT((spec_constant_mask & ~((1u << VULKAN_NUM_SPEC_CONSTANTS) - 1u)) == 0u);
SET_POTENTIALLY_STATIC_STATE(spec_constant_mask);
}
template <typename T>
inline void set_specialization_constant(unsigned index, const T &value)
{
VK_ASSERT(index < VULKAN_NUM_SPEC_CONSTANTS);
static_assert(sizeof(value) == sizeof(uint32_t), "Spec constant data must be 32-bit.");
if (memcmp(&pipeline_state.potential_static_state.spec_constants[index], &value, sizeof(value)))
{
memcpy(&pipeline_state.potential_static_state.spec_constants[index], &value, sizeof(value));
if (pipeline_state.potential_static_state.spec_constant_mask & (1u << index))
set_dirty(COMMAND_BUFFER_DIRTY_STATIC_STATE_BIT);
}
}
inline void enable_subgroup_size_control(bool subgroup_control_size)
{
SET_STATIC_STATE(subgroup_control_size);
}
inline void set_subgroup_size_log2(bool subgroup_full_group,
uint8_t subgroup_minimum_size_log2,
uint8_t subgroup_maximum_size_log2)
{
VK_ASSERT(subgroup_minimum_size_log2 < 8);
VK_ASSERT(subgroup_maximum_size_log2 < 8);
SET_STATIC_STATE(subgroup_full_group);
SET_STATIC_STATE(subgroup_minimum_size_log2);
SET_STATIC_STATE(subgroup_maximum_size_log2);
}
inline void set_conservative_rasterization(bool conservative_raster)
{
SET_STATIC_STATE(conservative_raster);
}
#define SET_DYNAMIC_STATE(state, flags) \
do \
{ \
if (dynamic_state.state != state) \
{ \
dynamic_state.state = state; \
set_dirty(flags); \
} \
} while (0)
inline void set_depth_bias(float depth_bias_constant, float depth_bias_slope)
{
SET_DYNAMIC_STATE(depth_bias_constant, COMMAND_BUFFER_DIRTY_DEPTH_BIAS_BIT);
SET_DYNAMIC_STATE(depth_bias_slope, COMMAND_BUFFER_DIRTY_DEPTH_BIAS_BIT);
}
inline void set_stencil_front_reference(uint8_t front_compare_mask, uint8_t front_write_mask,
uint8_t front_reference)
{
SET_DYNAMIC_STATE(front_compare_mask, COMMAND_BUFFER_DIRTY_STENCIL_REFERENCE_BIT);
SET_DYNAMIC_STATE(front_write_mask, COMMAND_BUFFER_DIRTY_STENCIL_REFERENCE_BIT);
SET_DYNAMIC_STATE(front_reference, COMMAND_BUFFER_DIRTY_STENCIL_REFERENCE_BIT);
}
inline void set_stencil_back_reference(uint8_t back_compare_mask, uint8_t back_write_mask, uint8_t back_reference)
{
SET_DYNAMIC_STATE(back_compare_mask, COMMAND_BUFFER_DIRTY_STENCIL_REFERENCE_BIT);
SET_DYNAMIC_STATE(back_write_mask, COMMAND_BUFFER_DIRTY_STENCIL_REFERENCE_BIT);
SET_DYNAMIC_STATE(back_reference, COMMAND_BUFFER_DIRTY_STENCIL_REFERENCE_BIT);
}
inline void set_stencil_reference(uint8_t compare_mask, uint8_t write_mask, uint8_t reference)
{
set_stencil_front_reference(compare_mask, write_mask, reference);
set_stencil_back_reference(compare_mask, write_mask, reference);
}
inline Type get_command_buffer_type() const
{
return type;
}
QueryPoolHandle write_timestamp(VkPipelineStageFlagBits stage);
void add_checkpoint(const char *tag);
void set_backtrace_checkpoint();
void end();
void enable_profiling();
bool has_profiling() const;
void begin_debug_channel(DebugChannelInterface *iface, const char *tag, VkDeviceSize size);
void end_debug_channel();
void extract_pipeline_state(DeferredPipelineCompile &compile) const;
static VkPipeline build_graphics_pipeline(Device *device, const DeferredPipelineCompile &compile);
static VkPipeline build_compute_pipeline(Device *device, const DeferredPipelineCompile &compile);
bool flush_pipeline_state_without_blocking();
private:
friend class Util::ObjectPool<CommandBuffer>;
CommandBuffer(Device *device, VkCommandBuffer cmd, VkPipelineCache cache, Type type);
Device *device;
const VolkDeviceTable &table;
VkCommandBuffer cmd;
Type type;
const Framebuffer *framebuffer = nullptr;
const RenderPass *actual_render_pass = nullptr;
const Vulkan::ImageView *framebuffer_attachments[VULKAN_NUM_ATTACHMENTS + 1] = {};
IndexState index_state = {};
VertexBindingState vbo = {};
ResourceBindings bindings;
VkDescriptorSet bindless_sets[VULKAN_NUM_DESCRIPTOR_SETS] = {};
VkDescriptorSet allocated_sets[VULKAN_NUM_DESCRIPTOR_SETS] = {};
VkPipeline current_pipeline = VK_NULL_HANDLE;
VkPipelineLayout current_pipeline_layout = VK_NULL_HANDLE;
PipelineLayout *current_layout = nullptr;
VkSubpassContents current_contents = VK_SUBPASS_CONTENTS_INLINE;
unsigned thread_index = 0;
VkViewport viewport = {};
VkRect2D scissor = {};
CommandBufferDirtyFlags dirty = ~0u;
uint32_t dirty_sets = 0;
uint32_t dirty_sets_dynamic = 0;
uint32_t dirty_vbos = 0;
uint32_t active_vbos = 0;
bool uses_swapchain = false;
bool is_compute = true;
bool is_secondary = false;
void set_dirty(CommandBufferDirtyFlags flags)
{
dirty |= flags;
}
CommandBufferDirtyFlags get_and_clear(CommandBufferDirtyFlags flags)
{
auto mask = dirty & flags;
dirty &= ~flags;
return mask;
}
DeferredPipelineCompile pipeline_state = {};
DynamicState dynamic_state = {};
#ifndef _MSC_VER
static_assert(sizeof(pipeline_state.static_state.words) >= sizeof(pipeline_state.static_state.state),
"Hashable pipeline state is not large enough!");
#endif
bool flush_render_state(bool synchronous);
bool flush_compute_state(bool synchronous);
void clear_render_state();
bool flush_graphics_pipeline(bool synchronous);
bool flush_compute_pipeline(bool synchronous);
void flush_descriptor_sets();
void begin_graphics();
void flush_descriptor_set(uint32_t set);
void rebind_descriptor_set(uint32_t set);
void begin_compute();
void begin_context();
BufferBlock vbo_block;
BufferBlock ibo_block;
BufferBlock ubo_block;
BufferBlock staging_block;
void set_texture(unsigned set, unsigned binding, VkImageView float_view, VkImageView integer_view,
VkImageLayout layout,
uint64_t cookie);
void init_viewport_scissor(const RenderPassInfo &info, const Framebuffer *framebuffer);
bool profiling = false;
std::string debug_channel_tag;
Vulkan::BufferHandle debug_channel_buffer;
DebugChannelInterface *debug_channel_interface = nullptr;
static void update_hash_graphics_pipeline(DeferredPipelineCompile &compile, uint32_t &active_vbos);
static void update_hash_compute_pipeline(DeferredPipelineCompile &compile);
};
#ifdef GRANITE_VULKAN_FILESYSTEM
struct CommandBufferUtil
{
static void draw_fullscreen_quad(CommandBuffer &cmd, const std::string &vertex, const std::string &fragment,
const std::vector<std::pair<std::string, int>> &defines = {});
static void draw_fullscreen_quad_depth(CommandBuffer &cmd, const std::string &vertex, const std::string &fragment,
bool depth_test, bool depth_write, VkCompareOp depth_compare,
const std::vector<std::pair<std::string, int>> &defines = {});
static void set_fullscreen_quad_vertex_state(CommandBuffer &cmd);
static void set_quad_vertex_state(CommandBuffer &cmd);
static void setup_fullscreen_quad(CommandBuffer &cmd, const std::string &vertex, const std::string &fragment,
const std::vector<std::pair<std::string, int>> &defines = {},
bool depth_test = false, bool depth_write = false,
VkCompareOp depth_compare = VK_COMPARE_OP_ALWAYS);
static void draw_fullscreen_quad(CommandBuffer &cmd, unsigned instances = 1);
static void draw_quad(CommandBuffer &cmd, unsigned instances = 1);
};
#endif
using CommandBufferHandle = Util::IntrusivePtr<CommandBuffer>;
}
| 11,801 |
11,010 |
/*
* Copyright (C) 2010 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.persist.finder;
import java.lang.reflect.Method;
/**
* Utility that helps you introspect dynamic finder methods.
*
* @author <EMAIL> (<NAME>)
*/
public final class DynamicFinder {
private final Method method;
private final Finder finder;
public DynamicFinder(Method method) {
this.method = method;
this.finder = method.getAnnotation(Finder.class);
}
/**
* Returns some metadata if the method is annotated {@code @Finder} or null.
*
* @param method a method you want to test as a dynamic finder
*/
public static DynamicFinder from(Method method) {
return method.isAnnotationPresent(Finder.class) ? new DynamicFinder(method) : null;
}
public Finder metadata() {
return finder;
}
}
| 392 |
5,250 |
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.rest.app.properties;
import java.util.Collections;
import java.util.Set;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
/**
* Properties for the rest app.
*
* @author <NAME>
* @author <NAME>
*/
@ConfigurationProperties(prefix = "flowable.rest.app")
public class RestAppProperties {
/**
* Configures the way user credentials are verified when doing a REST API call:
* 'any-user' : the user needs to exist and the password need to match. Any user is allowed to do the call (this is the pre 6.3.0 behavior)
* 'verify-privilege' : the user needs to exist, the password needs to match and the user needs to have the 'rest-api' privilege
* If nothing set, defaults to 'verify-privilege'
*/
private String authenticationMode = "verify-privilege";
/**
* Deploys demo process definitions that allows to have some example data when using the REST APIs
*/
private boolean createDemoDefinitions = true;
/**
* Enable/disable whether the docs are available on /docs
*/
private boolean swaggerDocsEnabled = true;
@NestedConfigurationProperty
private final Cors cors = new Cors();
@NestedConfigurationProperty
private final Admin admin = new Admin();
/**
* The default role prefix that needs to be used by Spring Security.
*/
private String rolePrefix = "ROLE_";
public String getAuthenticationMode() {
return authenticationMode;
}
public void setAuthenticationMode(String authenticationMode) {
this.authenticationMode = authenticationMode;
}
public boolean isCreateDemoDefinitions() {
return createDemoDefinitions;
}
public void setCreateDemoDefinitions(boolean createDemoDefinitions) {
this.createDemoDefinitions = createDemoDefinitions;
}
public boolean isSwaggerDocsEnabled() {
return swaggerDocsEnabled;
}
public void setSwaggerDocsEnabled(boolean swaggerDocsEnabled) {
this.swaggerDocsEnabled = swaggerDocsEnabled;
}
public Cors getCors() {
return cors;
}
public Admin getAdmin() {
return admin;
}
public String getRolePrefix() {
return rolePrefix;
}
public void setRolePrefix(String rolePrefix) {
this.rolePrefix = rolePrefix;
}
public static class Admin {
private String userId;
private String password;
private String firstName;
private String lastName;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
public static class Cors {
/**
* Enable/disable CORS filter.
*/
private boolean enabled = false;
/**
* Allow/disallow CORS credentials.
*/
private boolean allowCredentials = false;
/**
* Allowed CORS origins, use * for all, but not in production. Default empty.
*/
private Set<String> allowedOrigins;
/**
* Allowed CORS headers, use * for all, but not in production. Default empty.
*/
private Set<String> allowedHeaders;
/**
* Exposed CORS headers, use * for all, but not in production. Default empty.
*/
private Set<String> exposedHeaders;
/**
* Allowed CORS methods, use * for all, but not in production. Default empty.
*/
private Set<String> allowedMethods;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isAllowCredentials() {
return allowCredentials;
}
public void setAllowCredentials(boolean allowCredentials) {
this.allowCredentials = allowCredentials;
}
public Set<String> getAllowedOrigins() {
return allowedOrigins == null ? Collections.emptySet() : allowedOrigins;
}
public void setAllowedOrigins(Set<String> allowedOrigins) {
this.allowedOrigins = allowedOrigins;
}
public Set<String> getAllowedHeaders() {
return allowedHeaders == null ? Collections.emptySet() : allowedHeaders;
}
public void setAllowedHeaders(Set<String> allowedHeaders) {
this.allowedHeaders = allowedHeaders;
}
public Set<String> getExposedHeaders() {
return exposedHeaders == null ? Collections.emptySet() : exposedHeaders;
}
public void setExposedHeaders(Set<String> exposedHeaders) {
this.exposedHeaders = exposedHeaders;
}
public Set<String> getAllowedMethods() {
return allowedMethods == null ? Collections.emptySet() : allowedMethods;
}
public void setAllowedMethods(Set<String> allowedMethods) {
this.allowedMethods = allowedMethods;
}
}
}
| 2,370 |
1,456 |
<reponame>t-imamichi/qiskit-core
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""The Iterative Quantum Phase Estimation Algorithm."""
from typing import Optional, Union
import numpy
import qiskit
from qiskit.circuit import QuantumCircuit, QuantumRegister
from qiskit.circuit.classicalregister import ClassicalRegister
from qiskit.providers import Backend
from qiskit.utils import QuantumInstance
from .phase_estimator import PhaseEstimator
from .phase_estimator import PhaseEstimatorResult
class IterativePhaseEstimation(PhaseEstimator):
"""Run the Iterative quantum phase estimation (QPE) algorithm.
Given a unitary circuit and a circuit preparing an eigenstate, return the phase of the
eigenvalue as a number in :math:`[0,1)` using the iterative phase estimation algorithm.
[1]: Dobsicek et al. (2006), Arbitrary accuracy iterative phase estimation algorithm as a two
qubit benchmark, `arxiv/quant-ph/0610214 <https://arxiv.org/abs/quant-ph/0610214>`_
"""
def __init__(
self,
num_iterations: int,
quantum_instance: Optional[Union[QuantumInstance, Backend]] = None,
) -> None:
"""Args:
num_iterations: The number of iterations (rounds) of the phase estimation to run.
quantum_instance: The quantum instance on which the circuit will be run.
Raises:
ValueError: if num_iterations is not greater than zero.
"""
if isinstance(quantum_instance, Backend):
quantum_instance = QuantumInstance(quantum_instance)
self._quantum_instance = quantum_instance
if num_iterations <= 0:
raise ValueError("`num_iterations` must be greater than zero.")
self._num_iterations = num_iterations
def construct_circuit(
self,
unitary: QuantumCircuit,
state_preparation: QuantumCircuit,
k: int,
omega: float = 0,
measurement: bool = False,
) -> QuantumCircuit:
"""Construct the kth iteration Quantum Phase Estimation circuit.
For details of parameters, see Fig. 2 in https://arxiv.org/pdf/quant-ph/0610214.pdf.
Args:
unitary: The circuit representing the unitary operator whose eigenvalue (via phase)
will be measured.
state_preparation: The circuit that prepares the state whose eigenphase will be
measured. If this parameter is omitted, no preparation circuit
will be run and input state will be the all-zero state in the
computational basis.
k: the iteration idx.
omega: the feedback angle.
measurement: Boolean flag to indicate if measurement should
be included in the circuit.
Returns:
QuantumCircuit: the quantum circuit per iteration
"""
k = self._num_iterations if k is None else k
# The auxiliary (phase measurement) qubit
phase_register = QuantumRegister(1, name="a")
eigenstate_register = QuantumRegister(unitary.num_qubits, name="q")
qc = QuantumCircuit(eigenstate_register)
qc.add_register(phase_register)
if isinstance(state_preparation, QuantumCircuit):
qc.append(state_preparation, eigenstate_register)
elif state_preparation is not None:
qc += state_preparation.construct_circuit("circuit", eigenstate_register)
# hadamard on phase_register[0]
qc.h(phase_register[0])
# controlled-U
# TODO: We may want to allow flexibility in how the power is computed
# For example, it may be desirable to compute the power via Trotterization, if
# we are doing Trotterization anyway.
unitary_power = unitary.power(2 ** (k - 1)).control()
qc = qc.compose(unitary_power, list(range(1, unitary.num_qubits + 1)) + [0])
qc.p(omega, phase_register[0])
# hadamard on phase_register[0]
qc.h(phase_register[0])
if measurement:
c = ClassicalRegister(1, name="c")
qc.add_register(c)
qc.measure(phase_register, c)
return qc
def _estimate_phase_iteratively(self, unitary, state_preparation):
"""
Main loop of iterative phase estimation.
"""
omega_coef = 0
# k runs from the number of iterations back to 1
for k in range(self._num_iterations, 0, -1):
omega_coef /= 2
if self._quantum_instance.is_statevector:
qc = self.construct_circuit(
unitary, state_preparation, k, -2 * numpy.pi * omega_coef, measurement=False
)
result = self._quantum_instance.execute(qc)
complete_state_vec = result.get_statevector(qc)
ancilla_density_mat = qiskit.quantum_info.partial_trace(
complete_state_vec, range(unitary.num_qubits)
)
ancilla_density_mat_diag = numpy.diag(ancilla_density_mat)
max_amplitude = max(
ancilla_density_mat_diag.min(), ancilla_density_mat_diag.max(), key=abs
)
x = numpy.where(ancilla_density_mat_diag == max_amplitude)[0][0]
else:
qc = self.construct_circuit(
unitary, state_preparation, k, -2 * numpy.pi * omega_coef, measurement=True
)
measurements = self._quantum_instance.execute(qc).get_counts(qc)
x = 1 if measurements.get("1", 0) > measurements.get("0", 0) else 0
omega_coef = omega_coef + x / 2
return omega_coef
# pylint: disable=arguments-differ
def estimate(
self, unitary: QuantumCircuit, state_preparation: QuantumCircuit
) -> "IterativePhaseEstimationResult":
"""
Estimate the eigenphase of the input unitary and initial-state pair.
Args:
unitary: The circuit representing the unitary operator whose eigenvalue (via phase)
will be measured.
state_preparation: The circuit that prepares the state whose eigenphase will be
measured. If this parameter is omitted, no preparation circuit
will be run and input state will be the all-zero state in the
computational basis.
Returns:
Estimated phase in an IterativePhaseEstimationResult object.
"""
phase = self._estimate_phase_iteratively(unitary, state_preparation)
return IterativePhaseEstimationResult(self._num_iterations, phase)
class IterativePhaseEstimationResult(PhaseEstimatorResult):
"""Phase Estimation Result."""
def __init__(self, num_iterations: int, phase: float) -> None:
"""
Args:
num_iterations: number of iterations used in the phase estimation.
phase: the estimated phase.
"""
self._num_iterations = num_iterations
self._phase = phase
@property
def phase(self) -> float:
r"""Return the estimated phase as a number in :math:`[0.0, 1.0)`.
1.0 corresponds to a phase of :math:`2\pi`. It is assumed that the input vector is an
eigenvector of the unitary so that the peak of the probability density occurs at the bit
string that most closely approximates the true phase.
"""
return self._phase
@property
def num_iterations(self) -> int:
r"""Return the number of iterations used in the estimation algorithm."""
return self._num_iterations
| 3,306 |
3,034 |
<gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.perf.jmh;
import org.apache.logging.log4j.util.StringBuilders;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import java.util.concurrent.TimeUnit;
/**
* This benchmark tests encoding implementations.
*/
// ============================== HOW TO RUN THIS TEST: ====================================
//
// java -jar log4j-perf/target/benchmarks.jar ".*StringBuilderEscapeBenchmark.*" -f 1 -wi 5 -i 10
//
// Usage help:
// java -jar log4j-perf/target/benchmarks.jar -help
//
@State(Scope.Benchmark)
public class StringBuilderEscapeBenchmark {
private static final String EVERY_CHARACTER_MUST_BE_ESCAPED_JSON = repeat("\t\"", 1024);
private static final String EVERY_CHARACTER_MUST_BE_ESCAPED_XML = repeat("<\"&>", 512);
@State(Scope.Thread)
public static class ThreadState {
StringBuilder buffer = new StringBuilder(1024 * 4);
}
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public int escapeJsonLargeString(final ThreadState state) {
state.buffer.setLength(0);
state.buffer.append(EVERY_CHARACTER_MUST_BE_ESCAPED_JSON);
StringBuilders.escapeJson(state.buffer, 0);
return state.buffer.length();
}
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public int escapeXmlLargeString(final ThreadState state) {
state.buffer.setLength(0);
state.buffer.append(EVERY_CHARACTER_MUST_BE_ESCAPED_XML);
StringBuilders.escapeXml(state.buffer, 0);
return state.buffer.length();
}
private static String repeat(String str, int times) {
StringBuilder sb = new StringBuilder(str.length() * times);
for (int i = 0; i < times; i++) {
sb.append(str);
}
return sb.toString();
}
}
| 1,000 |
2,293 |
package com.googlecode.bshforandroid;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import com.googlecode.android_scripting.AsyncTaskListener;
import com.googlecode.android_scripting.InterpreterInstaller;
import com.googlecode.android_scripting.InterpreterUninstaller;
import com.googlecode.android_scripting.activity.Main;
import com.googlecode.android_scripting.exception.Sl4aException;
import com.googlecode.android_scripting.interpreter.InterpreterDescriptor;
public class BshMain extends Main {
private static enum MenuId {
PREFENCES;
public int getId() {
return ordinal() + Menu.FIRST;
}
}
@Override
protected InterpreterDescriptor getDescriptor() {
return new BshDescriptor();
}
@Override
protected InterpreterInstaller getInterpreterInstaller(InterpreterDescriptor descriptor,
Context context, AsyncTaskListener<Boolean> listener) throws Sl4aException {
return new BshInstaller(descriptor, context, listener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, MenuId.PREFENCES.getId(), Menu.NONE, "Preferences").setIcon(
android.R.drawable.ic_menu_preferences);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (MenuId.PREFENCES.getId() == id) {
startActivity(new Intent(this, BshPreferences.class));
}
return true;
}
@Override
protected InterpreterUninstaller getInterpreterUninstaller(InterpreterDescriptor descriptor,
Context context, AsyncTaskListener<Boolean> listener) throws Sl4aException {
return new BshUninstaller(descriptor, context, listener);
}
}
| 583 |
575 |
<reponame>Azile-Ttenneb/ppapi
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PPAPI_SHARED_IMPL_TEST_GLOBALS_H_
#define PPAPI_SHARED_IMPL_TEST_GLOBALS_H_
#include <stdint.h>
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "base/memory/unsafe_shared_memory_region.h"
#include "ppapi/shared_impl/callback_tracker.h"
#include "ppapi/shared_impl/ppapi_globals.h"
#include "ppapi/shared_impl/resource_tracker.h"
#include "ppapi/shared_impl/var_tracker.h"
namespace ppapi {
class TestVarTracker : public VarTracker {
public:
TestVarTracker() : VarTracker(THREAD_SAFE) {}
~TestVarTracker() override {}
PP_Var MakeResourcePPVarFromMessage(
PP_Instance instance,
const IPC::Message& creation_message,
int pending_renderer_id,
int pending_browser_id) override {
return PP_MakeNull();
}
ResourceVar* MakeResourceVar(PP_Resource pp_resource) override {
return NULL;
}
ArrayBufferVar* CreateArrayBuffer(uint32_t size_in_bytes) override {
return NULL;
}
ArrayBufferVar* CreateShmArrayBuffer(
uint32_t size_in_bytes,
base::UnsafeSharedMemoryRegion region) override {
return NULL;
}
void DidDeleteInstance(PP_Instance instance) override {}
int TrackSharedMemoryRegion(PP_Instance instance,
base::UnsafeSharedMemoryRegion region,
uint32_t size_in_bytes) override {
return -1;
}
bool StopTrackingSharedMemoryRegion(int id,
PP_Instance instance,
base::UnsafeSharedMemoryRegion* region,
uint32_t* size_in_bytes) override {
return false;
}
};
// Implementation of PpapiGlobals for tests that don't need either the host- or
// plugin-specific implementations.
class TestGlobals : public PpapiGlobals {
public:
TestGlobals();
explicit TestGlobals(PpapiGlobals::PerThreadForTest);
~TestGlobals() override;
// PpapiGlobals implementation.
ResourceTracker* GetResourceTracker() override;
VarTracker* GetVarTracker() override;
CallbackTracker* GetCallbackTrackerForInstance(PP_Instance instance) override;
thunk::PPB_Instance_API* GetInstanceAPI(PP_Instance instance) override;
thunk::ResourceCreationAPI* GetResourceCreationAPI(
PP_Instance instance) override;
PP_Module GetModuleForInstance(PP_Instance instance) override;
void LogWithSource(PP_Instance instance,
PP_LogLevel level,
const std::string& source,
const std::string& value) override;
void BroadcastLogWithSource(PP_Module module,
PP_LogLevel level,
const std::string& source,
const std::string& value) override;
MessageLoopShared* GetCurrentMessageLoop() override;
base::TaskRunner* GetFileTaskRunner() override;
// PpapiGlobals overrides:
bool IsHostGlobals() const override;
private:
ResourceTracker resource_tracker_;
TestVarTracker var_tracker_;
scoped_refptr<CallbackTracker> callback_tracker_;
DISALLOW_COPY_AND_ASSIGN(TestGlobals);
};
} // namespace ppapi
#endif // PPAPI_SHARED_IMPL_TEST_GLOBALS_H_
| 1,344 |
1,350 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
/*
* Portions Copyright (c) Microsoft Corporation
*/
package com.azure.cosmos.implementation.apachecommons.lang;
public class EnumUtils {
/**
* This constructor is public to permit tools that require a JavaBean
* instance to operate.
*/
private EnumUtils() {
}
/**
* <p>Gets the enum for the class, returning {@code null} if not found.</p>
*
* <p>This method differs from {@link Enum#valueOf} in that it does not throw an exception
* for an invalid enum name and performs case insensitive matching of the name.</p>
*
* @param <E> the type of the enumeration
* @param enumClass the class of the enum to query, not null
* @param enumName the enum name, null returns null
* @return the enum, null if not found
*/
public static <E extends Enum<E>> E getEnumIgnoreCase(final Class<E> enumClass, final String enumName) {
if (enumName == null || !enumClass.isEnum()) {
return null;
}
for (final E each : enumClass.getEnumConstants()) {
if (each.name().equalsIgnoreCase(enumName)) {
return each;
}
}
return null;
}
}
| 674 |
446 |
<gh_stars>100-1000
package com.plumdo.flow.rest.task.resource;
import java.util.*;
import org.flowable.engine.common.api.query.QueryProperty;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.api.history.HistoricTaskInstanceQuery;
import org.flowable.task.service.impl.HistoricTaskInstanceQueryProperty;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.plumdo.common.resource.PageResponse;
import com.plumdo.common.utils.ObjectUtils;
import com.plumdo.flow.constant.ErrorConstant;
import com.plumdo.flow.rest.task.TaskDetailResponse;
import com.plumdo.flow.rest.task.TaskEditRequest;
import com.plumdo.flow.rest.task.TaskPaginateList;
import com.plumdo.flow.rest.task.TaskResponse;
/**
* 任务基础接口
*
* @author wengwh
* @date 2018/12/6
*/
@RestController
public class TaskResource extends BaseTaskResource {
private static Map<String, QueryProperty> allowedSortProperties = new HashMap<>();
static {
allowedSortProperties.put("deleteReason", HistoricTaskInstanceQueryProperty.DELETE_REASON);
allowedSortProperties.put("duration", HistoricTaskInstanceQueryProperty.DURATION);
allowedSortProperties.put("endTime", HistoricTaskInstanceQueryProperty.END);
allowedSortProperties.put("executionId", HistoricTaskInstanceQueryProperty.EXECUTION_ID);
allowedSortProperties.put("taskInstanceId", HistoricTaskInstanceQueryProperty.HISTORIC_TASK_INSTANCE_ID);
allowedSortProperties.put("processDefinitionId", HistoricTaskInstanceQueryProperty.PROCESS_DEFINITION_ID);
allowedSortProperties.put("processInstanceId", HistoricTaskInstanceQueryProperty.PROCESS_INSTANCE_ID);
allowedSortProperties.put("assignee", HistoricTaskInstanceQueryProperty.TASK_ASSIGNEE);
allowedSortProperties.put("taskDefinitionKey", HistoricTaskInstanceQueryProperty.TASK_DEFINITION_KEY);
allowedSortProperties.put("description", HistoricTaskInstanceQueryProperty.TASK_DESCRIPTION);
allowedSortProperties.put("dueDate", HistoricTaskInstanceQueryProperty.TASK_DUE_DATE);
allowedSortProperties.put("name", HistoricTaskInstanceQueryProperty.TASK_NAME);
allowedSortProperties.put("owner", HistoricTaskInstanceQueryProperty.TASK_OWNER);
allowedSortProperties.put("priority", HistoricTaskInstanceQueryProperty.TASK_PRIORITY);
allowedSortProperties.put("tenantId", HistoricTaskInstanceQueryProperty.TENANT_ID_);
allowedSortProperties.put("startTime", HistoricTaskInstanceQueryProperty.START);
}
@GetMapping(value = "/tasks", name = "任务查询")
public PageResponse getTasks(@RequestParam Map<String, String> requestParams) {
HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery();
if (ObjectUtils.isNotEmpty(requestParams.get("taskId"))) {
query.taskId(requestParams.get("taskId"));
}
if (ObjectUtils.isNotEmpty(requestParams.get("processInstanceId"))) {
query.processInstanceId(requestParams.get("processInstanceId"));
}
if (ObjectUtils.isNotEmpty(requestParams.get("processInstanceBusinessKey"))) {
query.processInstanceBusinessKeyLike(ObjectUtils.convertToLike(requestParams.get("processInstanceBusinessKey")));
}
if (ObjectUtils.isNotEmpty(requestParams.get("processDefinitionKey"))) {
query.processDefinitionKeyLike(ObjectUtils.convertToLike(requestParams.get("processDefinitionKey")));
}
if (ObjectUtils.isNotEmpty(requestParams.get("processDefinitionId"))) {
query.processDefinitionId(requestParams.get("processDefinitionId"));
}
if (ObjectUtils.isNotEmpty(requestParams.get("processDefinitionName"))) {
query.processDefinitionNameLike(ObjectUtils.convertToLike(requestParams.get("processDefinitionName")));
}
if (ObjectUtils.isNotEmpty(requestParams.get("executionId"))) {
query.executionId(requestParams.get("executionId"));
}
if (ObjectUtils.isNotEmpty(requestParams.get("taskName"))) {
query.taskNameLike(ObjectUtils.convertToLike(requestParams.get("taskName")));
}
if (ObjectUtils.isNotEmpty(requestParams.get("taskDescription"))) {
query.taskDescriptionLike(ObjectUtils.convertToLike(requestParams.get("taskDescription")));
}
if (ObjectUtils.isNotEmpty(requestParams.get("taskDefinitionKey"))) {
query.taskDefinitionKeyLike(ObjectUtils.convertToLike(requestParams.get("taskDefinitionKey")));
}
if (ObjectUtils.isNotEmpty(requestParams.get("taskAssignee"))) {
query.taskAssignee(requestParams.get("taskAssignee"));
}
if (ObjectUtils.isNotEmpty(requestParams.get("taskOwner"))) {
query.taskOwner(requestParams.get("taskOwner"));
}
if (ObjectUtils.isNotEmpty(requestParams.get("taskInvolvedUser"))) {
query.taskInvolvedUser(requestParams.get("taskInvolvedUser"));
}
if (ObjectUtils.isNotEmpty(requestParams.get("taskPriority"))) {
query.taskPriority(ObjectUtils.convertToInteger(requestParams.get("taskPriority")));
}
if (ObjectUtils.isNotEmpty(requestParams.get("finished"))) {
boolean isFinished = ObjectUtils.convertToBoolean(requestParams.get("finished"));
if (isFinished) {
query.finished();
} else {
query.unfinished();
}
}
if (ObjectUtils.isNotEmpty(requestParams.get("processFinished"))) {
boolean isProcessFinished = ObjectUtils.convertToBoolean(requestParams.get("processFinished"));
if (isProcessFinished) {
query.processFinished();
} else {
query.processUnfinished();
}
}
if (ObjectUtils.isNotEmpty(requestParams.get("parentTaskId"))) {
query.taskParentTaskId(requestParams.get("parentTaskId"));
}
if (ObjectUtils.isNotEmpty(requestParams.get("dueDateAfter"))) {
query.taskDueAfter(ObjectUtils.convertToDatetime(requestParams.get("dueDateAfter")));
}
if (ObjectUtils.isNotEmpty(requestParams.get("dueDateBefore"))) {
query.taskDueBefore(ObjectUtils.convertToDatetime(requestParams.get("dueDateBefore")));
}
if (ObjectUtils.isNotEmpty(requestParams.get("taskCreatedBefore"))) {
query.taskCreatedBefore(ObjectUtils.convertToDatetime(requestParams.get("taskCreatedBefore")));
}
if (ObjectUtils.isNotEmpty(requestParams.get("taskCreatedAfter"))) {
query.taskCreatedAfter(ObjectUtils.convertToDatetime(requestParams.get("taskCreatedAfter")));
}
if (ObjectUtils.isNotEmpty(requestParams.get("taskCompletedBefore"))) {
query.taskCompletedBefore(ObjectUtils.convertToDatetime(requestParams.get("taskCompletedBefore")));
}
if (ObjectUtils.isNotEmpty(requestParams.get("taskCompletedAfter"))) {
query.taskCompletedAfter(ObjectUtils.convertToDatetime(requestParams.get("taskCompletedAfter")));
}
if (ObjectUtils.isNotEmpty(requestParams.get("tenantId"))) {
query.taskTenantId(requestParams.get("tenantId"));
}
if (ObjectUtils.isNotEmpty(requestParams.get("taskCandidateUser"))) {
query.taskCandidateUser(requestParams.get("taskCandidateUser"));
}
if (ObjectUtils.isNotEmpty(requestParams.get("taskCandidateGroup"))) {
query.taskCandidateGroup(requestParams.get("taskCandidateGroup"));
}
if (ObjectUtils.isNotEmpty(requestParams.get("taskCandidateGroups"))) {
String[] candidateGroups = requestParams.get("taskCandidateGroups").split(",");
query.taskCandidateGroupIn(Arrays.asList(candidateGroups));
}
return new TaskPaginateList(restResponseFactory).paginateList(getPageable(requestParams), query, allowedSortProperties);
}
@GetMapping(value = "/tasks/{taskId}", name = "根据ID任务查询")
public TaskDetailResponse getTaskById(@PathVariable("taskId") String taskId) {
HistoricTaskInstance historicTaskInstance = getHistoricTaskFromRequest(taskId);
Task task = null;
if (historicTaskInstance.getEndTime() == null) {
task = getTaskFromRequest(taskId);
}
String formKey = formService.getTaskFormKey(historicTaskInstance.getProcessDefinitionId(), historicTaskInstance.getTaskDefinitionKey());
return restResponseFactory.createTaskDetailResponse(historicTaskInstance, task, formKey);
}
@PutMapping(value = "/tasks/{taskId}", name = "任务修改")
public TaskResponse updateTask(@PathVariable String taskId, @RequestBody TaskEditRequest taskEditRequest) {
Task task = getTaskFromRequest(taskId);
task.setName(taskEditRequest.getName());
task.setDescription(taskEditRequest.getDescription());
task.setAssignee(taskEditRequest.getAssignee());
task.setOwner(taskEditRequest.getOwner());
task.setDueDate(taskEditRequest.getDueDate());
task.setPriority(taskEditRequest.getPriority());
task.setCategory(taskEditRequest.getCategory());
taskService.saveTask(task);
return restResponseFactory.createTaskResponse(task);
}
@DeleteMapping(value = "/tasks/{taskId}", name = "任务删除")
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void deleteTask(@PathVariable String taskId) {
HistoricTaskInstance task = getHistoricTaskFromRequest(taskId);
if (task.getEndTime() == null) {
exceptionFactory.throwForbidden(ErrorConstant.TASK_RUN_NOT_DELETE, taskId);
}
historyService.deleteHistoricTaskInstance(task.getId());
}
}
| 3,998 |
6,989 |
<gh_stars>1000+
#include "../lib/zstd.h" /* inclink generated by yamaker */
| 29 |
446 |
<filename>Source/MediaInfo/Video/File_CineForm.h
/* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// Information about CineForm video streams
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//---------------------------------------------------------------------------
#ifndef MediaInfo_CineFormH
#define MediaInfo_CineFormH
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/File__Analyze.h"
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Class File_CineForm
//***************************************************************************
class File_CineForm : public File__Analyze
{
public :
//constructor/Destructor
File_CineForm();
private :
//Streams management
void Streams_Fill();
//Buffer - Global
void Read_Buffer_Continue();
};
} //NameSpace
#endif
| 331 |
678 |
<gh_stars>100-1000
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport
*/
#import <OfficeImport/ODICycle3.h>
__attribute__((visibility("hidden")))
@interface ODICycle4 : ODICycle3 {
}
+ (unsigned)nodeCountWithState:(id)state; // 0x2b2315
@end
| 118 |
6,036 |
<filename>onnxruntime/test/providers/cpu/tensor/eyelike_op_test.cc<gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "gtest/gtest.h"
#include "test/providers/provider_test_utils.h"
namespace onnxruntime {
namespace test {
TEST(EyeLikeOpTest, EyeLikeDefault) {
OpTester test("EyeLike", 9);
test.AddInput<float>("T1", {3, 2}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f});
test.AddOutput<float>("T2", {3, 2}, {1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f});
test.Run();
}
TEST(EyeLikeOpTest, EyeLike_DifferentDtype) {
OpTester test("EyeLike", 9);
test.AddAttribute("dtype", int64_t(7));
test.AddInput<float>("T1", {3, 3}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f});
test.AddOutput<int64_t>("T2", {3, 3}, {1, 0, 0, 0, 1, 0, 0, 0, 1});
test.Run();
}
TEST(EyeLikeOpTest, EyeLike_K_EgdeCase_1) {
OpTester test("EyeLike", 9);
test.AddInput<int64_t>("T1", {3, 2}, {0, 0, 0, 0, 0, 0});
test.AddAttribute("k", int64_t(3));
test.AddAttribute("dtype", int64_t(7));
test.AddOutput<int64_t>("T2", {3, 2}, {0, 0, 0, 0, 0, 0});
test.Run();
}
TEST(EyeLikeOpTest, EyeLike_K_EgdeCase_2) {
OpTester test("EyeLike", 9);
test.AddInput<int64_t>("T1", {3, 2}, {0, 0, 0, 0, 0, 0});
test.AddAttribute("k", int64_t(-3));
test.AddOutput<int64_t>("T2", {3, 2}, {0, 0, 0, 0, 0, 0});
test.Run();
}
TEST(EyeLikeOpTest, EyeLike_UpperDiagonal) {
OpTester test("EyeLike", 9);
test.AddInput<float>("T1", {3, 4}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f});
test.AddAttribute("k", int64_t(2));
test.AddOutput<float>("T2", {3, 4}, {0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f});
test.Run();
}
TEST(EyeLikeOpTest, EyeLike_UpperrDiagonal2) {
OpTester test("EyeLike", 9);
test.AddInput<float>("T1", {3, 2}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f});
test.AddAttribute("k", int64_t(1));
test.AddOutput<float>("T2", {3, 2}, {0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f});
test.Run();
}
TEST(EyeLikeOpTest, EyeLike_LowerDiagonal) {
OpTester test("EyeLike", 9);
test.AddInput<float>("T1", {3, 2}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f});
test.AddAttribute("k", int64_t(-1));
test.AddAttribute("dtype", int64_t(1));
test.AddOutput<float>("T2", {3, 2}, {0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f});
test.Run();
}
TEST(EyeLikeOpTest, EyeLike_LowerDiagonal2) {
OpTester test("EyeLike", 9);
test.AddInput<float>("T1", {3, 4}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f});
test.AddAttribute("k", int64_t(-2));
test.AddAttribute("dtype", int64_t(1));
test.AddOutput<float>("T2", {3, 4}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f});
test.Run();
}
} // namespace test
} // namespace onnxruntime
| 1,449 |
310 |
"""
Copyright (c) 2020 Intel Corporation
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 sys
from argparse import ArgumentParser
from typing import NamedTuple, Any
import torch
from os import listdir, makedirs
from os.path import isfile, join, exists
from shutil import copyfile
from nncf.torch.quantization.layers import SymmetricQuantizer, AsymmetricQuantizer
class ParameterToAdd(NamedTuple):
name: str
value: Any
def main(argv):
parser = ArgumentParser()
parser.add_argument('-i', '--input-folder', help='Path to directory with given checkpoints to modify',
required=True)
parser.add_argument('-o', '--output-folder', help='Path to directory to save modified checkpoints', required=True)
parser.add_argument('-b', '--bitwidth', help='Bitwidth to initialize quantizer',
required=False, default=8, type=int)
parser.add_argument('-v', '--verbose', help='Print all new names of parameters', required=False,
action='store_true')
args = parser.parse_args(args=argv)
src_dir = args.input_folder
dst_dir = args.output_folder
if not exists(dst_dir):
makedirs(dst_dir)
param_list = [ParameterToAdd('_num_bits', torch.IntTensor([args.bitwidth])),
ParameterToAdd('enabled', torch.IntTensor([1]))]
pth_files = [(join(src_dir, f), join(dst_dir, f)) for f in listdir(src_dir) if
isfile(join(src_dir, f)) and ('.pth' in f or '.sd' in f)]
files_to_copy = []
for pair in pth_files:
src_file, dst_file = pair
if 'binarization' in src_file:
files_to_copy.append(pair)
continue
sd = pth = torch.load(src_file)
if 'state_dict' in pth:
sd = pth['state_dict']
hooks = [SymmetricQuantizer.SCALE_PARAM_NAME, AsymmetricQuantizer.INPUT_LOW_PARAM_NAME]
new_keys = {}
for new_parameter in param_list:
old_keys = list(sd.keys())
for k in sd.keys():
for h in hooks:
new_key = k.replace(h, new_parameter.name)
if ('.' + h in k) and ('.' + new_parameter.name not in k) and (new_key not in old_keys):
new_keys[new_key] = new_parameter.value
if new_keys:
print(f'\nAdding #{len(new_keys)} of new keys')
if args.verbose:
print('New keys:', new_keys, sep='\n')
for new_key, value in new_keys.items():
sd[new_key] = value
pth['state_dict'] = sd
torch.save(pth, dst_file)
else:
files_to_copy.append(pair)
for src_file, dst_file in files_to_copy:
print("\nCopying {}".format(dst_file))
copyfile(src_file, dst_file)
if __name__ == '__main__':
main(sys.argv[1:])
| 1,421 |
1,074 |
# -----------------------------------------------------------------------------
# Copyright (c) 2009-2016 <NAME>. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import numpy as np
from glumpy.api.matplotlib import *
# Create a new figure
figure = Figure((24,12))
# Create a subplot on left, using trackball interface (3d)
left = figure.add_axes( [0.010, 0.01, 0.485, 0.98],
interface = Trackball(name="trackball"),
facecolor=(1,0,0,0.25), aspect=1 )
# Create a subplot on right, using panzoom interface (2d)
right = figure.add_axes( [0.505, 0.01, 0.485, 0.98],
interface = PanZoom(name="panzoom", aspect=1),
facecolor=(0,0,1,0.25), aspect=1 )
# Create a new collection of points
collection = PointCollection("agg")
# Add a view of the collection on the left subplot
left.add_drawable(collection)
# Add a view of the collection on the right subplot
right.add_drawable(collection)
# Change xscale range on left subplot
left.transform['zscale']['range'] = -0.5,+0.5
# Set trackball view
left.transform['trackball']["phi"] = 0
left.transform['trackball']["theta"] = 0
# Add some points
collection.append(np.random.normal(0.0,0.5,(10000,3)))
# Show figure
figure.show()
| 494 |
1,676 |
package sdk.chat.core.dao;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Unique;
import sdk.chat.core.base.AbstractEntity;
@Entity
public class PublicKey extends AbstractEntity {
@Id
private Long id;
@Unique
private String entityID;
private String key;
private String identifier;
@Generated(hash = 981958860)
public PublicKey(Long id, String entityID, String key, String identifier) {
this.id = id;
this.entityID = entityID;
this.key = key;
this.identifier = identifier;
}
@Generated(hash = 285518041)
public PublicKey() {
}
@Override
public void setEntityID(String entityID) {
this.entityID = entityID;
}
@Override
public String getEntityID() {
return entityID;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getKey() {
return this.key;
}
public void setKey(String key) {
this.key = key;
}
public String getIdentifier() {
return this.identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
}
| 547 |
798 |
/*
* The MIT License
*
* Copyright (c) 2010 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package picard.fingerprint;
/**
* Represents the results of comparing evidence for a single haplotype locus between
* two sources of evidence (typically external genotyping data vs. sequencing data.).
*
* @author <NAME>
*/
class LocusResult implements Comparable<LocusResult> {
private final Snp snp;
private final DiploidGenotype expectedGenotype;
private final DiploidGenotype mostLikelyGenotype;
private final int allele1Count;
private final int allele2Count;
private final double lodGenotype;
private final double lodExpectedSampleTumorNormal; //LOD assuming that the first sample is from a tumor and the second is from the normal
private final double lodExpectedSampleNormalTumor; //LOD assuming that the first sample is from the normal and the second is from a tumor
private final double lExpectedSample; // log probability of expected sample
private final double lRandomSample; // log probability of random sample
LocusResult(final Snp snp, final DiploidGenotype expectedGenotype, final DiploidGenotype mostLikelyGenotype,
final int allele1Count, final int allele2Count, final double lodGenotype,
final double lExpectedSample, final double lRandomSample,
final double lodGenotypeTumorNormal, final double lodGenotypeNormalTumor) {
this.snp = snp;
this.expectedGenotype = expectedGenotype;
this.mostLikelyGenotype = mostLikelyGenotype;
this.allele1Count = allele1Count;
this.allele2Count = allele2Count;
this.lodGenotype = lodGenotype;
this.lExpectedSample = lExpectedSample;
this.lRandomSample = lRandomSample;
this.lodExpectedSampleTumorNormal = lodGenotypeTumorNormal;
this.lodExpectedSampleNormalTumor = lodGenotypeNormalTumor;
}
public Snp getSnp() { return snp; }
public DiploidGenotype getExpectedGenotype() { return expectedGenotype; }
public DiploidGenotype getMostLikelyGenotype() { return mostLikelyGenotype; }
public int getAllele1Count() { return allele1Count; }
public int getAllele2Count() { return allele2Count; }
public double getLodGenotype() { return lodGenotype; }
public double getLodExpectedSampleNormalTumor() { return lodExpectedSampleNormalTumor; }
public double getLodExpectedSampleTumorNormal() { return lodExpectedSampleTumorNormal; }
public double lExpectedSample() { return lExpectedSample; }
public double lRandomSample() { return lRandomSample; }
@Override
public int compareTo(final LocusResult that) {
return this.snp.compareTo(that.snp);
}
}
| 1,170 |
370 |
{
"displayName": "<NAME>",
"email": "<EMAIL>",
"name": "projects/k8s-artifacts-prod-bak/serviceAccounts/<EMAIL>",
"oauth2ClientId": "108557486729045644821",
"projectId": "k8s-artifacts-prod-bak",
"uniqueId": "108557486729045644821"
}
| 109 |
56,632 |
/*
* jdarith.c
*
* Developed 1997-2019 by <NAME>.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains portable arithmetic entropy decoding routines for JPEG
* (implementing the ISO/IEC IS 10918-1 and CCITT Recommendation ITU-T T.81).
*
* Both sequential and progressive modes are supported in this single module.
*
* Suspension is not currently supported in this module.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
/* Expanded entropy decoder object for arithmetic decoding. */
typedef struct {
struct jpeg_entropy_decoder pub; /* public fields */
INT32 c; /* C register, base of coding interval + input bit buffer */
INT32 a; /* A register, normalized size of coding interval */
int ct; /* bit shift counter, # of bits left in bit buffer part of C */
/* init: ct = -16 */
/* run: ct = 0..7 */
/* error: ct = -1 */
int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
int dc_context[MAX_COMPS_IN_SCAN]; /* context index for DC conditioning */
unsigned int restarts_to_go; /* MCUs left in this restart interval */
/* Pointers to statistics areas (these workspaces have image lifespan) */
unsigned char * dc_stats[NUM_ARITH_TBLS];
unsigned char * ac_stats[NUM_ARITH_TBLS];
/* Statistics bin for coding with fixed probability 0.5 */
unsigned char fixed_bin[4];
} arith_entropy_decoder;
typedef arith_entropy_decoder * arith_entropy_ptr;
/* The following two definitions specify the allocation chunk size
* for the statistics area.
* According to sections F.1.4.4.1.3 and F.1.4.4.2, we need at least
* 49 statistics bins for DC, and 245 statistics bins for AC coding.
*
* We use a compact representation with 1 byte per statistics bin,
* thus the numbers directly represent byte sizes.
* This 1 byte per statistics bin contains the meaning of the MPS
* (more probable symbol) in the highest bit (mask 0x80), and the
* index into the probability estimation state machine table
* in the lower bits (mask 0x7F).
*/
#define DC_STAT_BINS 64
#define AC_STAT_BINS 256
LOCAL(int)
get_byte (j_decompress_ptr cinfo)
/* Read next input byte; we do not support suspension in this module. */
{
struct jpeg_source_mgr * src = cinfo->src;
if (src->bytes_in_buffer == 0)
if (! (*src->fill_input_buffer) (cinfo))
ERREXIT(cinfo, JERR_CANT_SUSPEND);
src->bytes_in_buffer--;
return GETJOCTET(*src->next_input_byte++);
}
/*
* The core arithmetic decoding routine (common in JPEG and JBIG).
* This needs to go as fast as possible.
* Machine-dependent optimization facilities
* are not utilized in this portable implementation.
* However, this code should be fairly efficient and
* may be a good base for further optimizations anyway.
*
* Return value is 0 or 1 (binary decision).
*
* Note: I've changed the handling of the code base & bit
* buffer register C compared to other implementations
* based on the standards layout & procedures.
* While it also contains both the actual base of the
* coding interval (16 bits) and the next-bits buffer,
* the cut-point between these two parts is floating
* (instead of fixed) with the bit shift counter CT.
* Thus, we also need only one (variable instead of
* fixed size) shift for the LPS/MPS decision, and
* we can do away with any renormalization update
* of C (except for new data insertion, of course).
*
* I've also introduced a new scheme for accessing
* the probability estimation state machine table,
* derived from <NAME>'s JBIG implementation.
*/
LOCAL(int)
arith_decode (j_decompress_ptr cinfo, unsigned char *st)
{
register arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy;
register unsigned char nl, nm;
register INT32 qe, temp;
register int sv, data;
/* Renormalization & data input per section D.2.6 */
while (e->a < 0x8000L) {
if (--e->ct < 0) {
/* Need to fetch next data byte */
if (cinfo->unread_marker)
data = 0; /* stuff zero data */
else {
data = get_byte(cinfo); /* read next input byte */
if (data == 0xFF) { /* zero stuff or marker code */
do data = get_byte(cinfo);
while (data == 0xFF); /* swallow extra 0xFF bytes */
if (data == 0)
data = 0xFF; /* discard stuffed zero byte */
else {
/* Note: Different from the Huffman decoder, hitting
* a marker while processing the compressed data
* segment is legal in arithmetic coding.
* The convention is to supply zero data
* then until decoding is complete.
*/
cinfo->unread_marker = data;
data = 0;
}
}
}
e->c = (e->c << 8) | data; /* insert data into C register */
if ((e->ct += 8) < 0) /* update bit shift counter */
/* Need more initial bytes */
if (++e->ct == 0)
/* Got 2 initial bytes -> re-init A and exit loop */
e->a = 0x8000L; /* => e->a = 0x10000L after loop exit */
}
e->a <<= 1;
}
/* Fetch values from our compact representation of Table D.3(D.2):
* Qe values and probability estimation state machine
*/
sv = *st;
qe = jpeg_aritab[sv & 0x7F]; /* => Qe_Value */
nl = qe & 0xFF; qe >>= 8; /* Next_Index_LPS + Switch_MPS */
nm = qe & 0xFF; qe >>= 8; /* Next_Index_MPS */
/* Decode & estimation procedures per sections D.2.4 & D.2.5 */
temp = e->a - qe;
e->a = temp;
temp <<= e->ct;
if (e->c >= temp) {
e->c -= temp;
/* Conditional LPS (less probable symbol) exchange */
if (e->a < qe) {
e->a = qe;
*st = (sv & 0x80) ^ nm; /* Estimate_after_MPS */
} else {
e->a = qe;
*st = (sv & 0x80) ^ nl; /* Estimate_after_LPS */
sv ^= 0x80; /* Exchange LPS/MPS */
}
} else if (e->a < 0x8000L) {
/* Conditional MPS (more probable symbol) exchange */
if (e->a < qe) {
*st = (sv & 0x80) ^ nl; /* Estimate_after_LPS */
sv ^= 0x80; /* Exchange LPS/MPS */
} else {
*st = (sv & 0x80) ^ nm; /* Estimate_after_MPS */
}
}
return sv >> 7;
}
/*
* Check for a restart marker & resynchronize decoder.
*/
LOCAL(void)
process_restart (j_decompress_ptr cinfo)
{
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
int ci;
jpeg_component_info * compptr;
/* Advance past the RSTn marker */
if (! (*cinfo->marker->read_restart_marker) (cinfo))
ERREXIT(cinfo, JERR_CANT_SUSPEND);
/* Re-initialize statistics areas */
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
compptr = cinfo->cur_comp_info[ci];
if (! cinfo->progressive_mode || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
MEMZERO(entropy->dc_stats[compptr->dc_tbl_no], DC_STAT_BINS);
/* Reset DC predictions to 0 */
entropy->last_dc_val[ci] = 0;
entropy->dc_context[ci] = 0;
}
if ((! cinfo->progressive_mode && cinfo->lim_Se) ||
(cinfo->progressive_mode && cinfo->Ss)) {
MEMZERO(entropy->ac_stats[compptr->ac_tbl_no], AC_STAT_BINS);
}
}
/* Reset arithmetic decoding variables */
entropy->c = 0;
entropy->a = 0;
entropy->ct = -16; /* force reading 2 initial bytes to fill C */
/* Reset restart counter */
entropy->restarts_to_go = cinfo->restart_interval;
}
/*
* Arithmetic MCU decoding.
* Each of these routines decodes and returns one MCU's worth of
* arithmetic-compressed coefficients.
* The coefficients are reordered from zigzag order into natural array order,
* but are not dequantized.
*
* The i'th block of the MCU is stored into the block pointed to by
* MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
*/
/*
* MCU decoding for DC initial scan (either spectral selection,
* or first pass of successive approximation).
*/
METHODDEF(boolean)
decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
JBLOCKROW block;
unsigned char *st;
int blkn, ci, tbl, sign;
int v, m;
/* Process restart marker if needed */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
process_restart(cinfo);
entropy->restarts_to_go--;
}
if (entropy->ct == -1) return TRUE; /* if error do nothing */
/* Outer loop handles each block in the MCU */
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
block = MCU_data[blkn];
ci = cinfo->MCU_membership[blkn];
tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;
/* Sections F.2.4.1 & F.1.4.4.1: Decoding of DC coefficients */
/* Table F.4: Point to statistics bin S0 for DC coefficient coding */
st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
/* Figure F.19: Decode_DC_DIFF */
if (arith_decode(cinfo, st) == 0)
entropy->dc_context[ci] = 0;
else {
/* Figure F.21: Decoding nonzero value v */
/* Figure F.22: Decoding the sign of v */
sign = arith_decode(cinfo, st + 1);
st += 2; st += sign;
/* Figure F.23: Decoding the magnitude category of v */
if ((m = arith_decode(cinfo, st)) != 0) {
st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
while (arith_decode(cinfo, st)) {
if ((m <<= 1) == (int) 0x8000U) {
WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
entropy->ct = -1; /* magnitude overflow */
return TRUE;
}
st += 1;
}
}
/* Section F.1.4.4.1.2: Establish dc_context conditioning category */
if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))
entropy->dc_context[ci] = 0; /* zero diff category */
else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))
entropy->dc_context[ci] = 12 + (sign * 4); /* large diff category */
else
entropy->dc_context[ci] = 4 + (sign * 4); /* small diff category */
v = m;
/* Figure F.24: Decoding the magnitude bit pattern of v */
st += 14;
while (m >>= 1)
if (arith_decode(cinfo, st)) v |= m;
v += 1; if (sign) v = -v;
entropy->last_dc_val[ci] += v;
}
/* Scale and output the DC coefficient (assumes jpeg_natural_order[0]=0) */
(*block)[0] = (JCOEF) (entropy->last_dc_val[ci] << cinfo->Al);
}
return TRUE;
}
/*
* MCU decoding for AC initial scan (either spectral selection,
* or first pass of successive approximation).
*/
METHODDEF(boolean)
decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
JBLOCKROW block;
unsigned char *st;
int tbl, sign, k;
int v, m;
const int * natural_order;
/* Process restart marker if needed */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
process_restart(cinfo);
entropy->restarts_to_go--;
}
if (entropy->ct == -1) return TRUE; /* if error do nothing */
natural_order = cinfo->natural_order;
/* There is always only one block per MCU */
block = MCU_data[0];
tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
/* Sections F.2.4.2 & F.1.4.4.2: Decoding of AC coefficients */
/* Figure F.20: Decode_AC_coefficients */
k = cinfo->Ss - 1;
do {
st = entropy->ac_stats[tbl] + 3 * k;
if (arith_decode(cinfo, st)) break; /* EOB flag */
for (;;) {
k++;
if (arith_decode(cinfo, st + 1)) break;
st += 3;
if (k >= cinfo->Se) {
WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
entropy->ct = -1; /* spectral overflow */
return TRUE;
}
}
/* Figure F.21: Decoding nonzero value v */
/* Figure F.22: Decoding the sign of v */
sign = arith_decode(cinfo, entropy->fixed_bin);
st += 2;
/* Figure F.23: Decoding the magnitude category of v */
if ((m = arith_decode(cinfo, st)) != 0) {
if (arith_decode(cinfo, st)) {
m <<= 1;
st = entropy->ac_stats[tbl] +
(k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
while (arith_decode(cinfo, st)) {
if ((m <<= 1) == (int) 0x8000U) {
WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
entropy->ct = -1; /* magnitude overflow */
return TRUE;
}
st += 1;
}
}
}
v = m;
/* Figure F.24: Decoding the magnitude bit pattern of v */
st += 14;
while (m >>= 1)
if (arith_decode(cinfo, st)) v |= m;
v += 1; if (sign) v = -v;
/* Scale and output coefficient in natural (dezigzagged) order */
(*block)[natural_order[k]] = (JCOEF) (v << cinfo->Al);
} while (k < cinfo->Se);
return TRUE;
}
/*
* MCU decoding for DC successive approximation refinement scan.
* Note: we assume such scans can be multi-component,
* although the spec is not very clear on the point.
*/
METHODDEF(boolean)
decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
unsigned char *st;
JCOEF p1;
int blkn;
/* Process restart marker if needed */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
process_restart(cinfo);
entropy->restarts_to_go--;
}
st = entropy->fixed_bin; /* use fixed probability estimation */
p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
/* Outer loop handles each block in the MCU */
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
/* Encoded data is simply the next bit of the two's-complement DC value */
if (arith_decode(cinfo, st))
MCU_data[blkn][0][0] |= p1;
}
return TRUE;
}
/*
* MCU decoding for AC successive approximation refinement scan.
*/
METHODDEF(boolean)
decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
JBLOCKROW block;
JCOEFPTR thiscoef;
unsigned char *st;
int tbl, k, kex;
JCOEF p1, m1;
const int * natural_order;
/* Process restart marker if needed */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
process_restart(cinfo);
entropy->restarts_to_go--;
}
if (entropy->ct == -1) return TRUE; /* if error do nothing */
natural_order = cinfo->natural_order;
/* There is always only one block per MCU */
block = MCU_data[0];
tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
m1 = -p1; /* -1 in the bit position being coded */
/* Establish EOBx (previous stage end-of-block) index */
kex = cinfo->Se;
do {
if ((*block)[natural_order[kex]]) break;
} while (--kex);
k = cinfo->Ss - 1;
do {
st = entropy->ac_stats[tbl] + 3 * k;
if (k >= kex)
if (arith_decode(cinfo, st)) break; /* EOB flag */
for (;;) {
thiscoef = *block + natural_order[++k];
if (*thiscoef) { /* previously nonzero coef */
if (arith_decode(cinfo, st + 2)) {
if (*thiscoef < 0)
*thiscoef += m1;
else
*thiscoef += p1;
}
break;
}
if (arith_decode(cinfo, st + 1)) { /* newly nonzero coef */
if (arith_decode(cinfo, entropy->fixed_bin))
*thiscoef = m1;
else
*thiscoef = p1;
break;
}
st += 3;
if (k >= cinfo->Se) {
WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
entropy->ct = -1; /* spectral overflow */
return TRUE;
}
}
} while (k < cinfo->Se);
return TRUE;
}
/*
* Decode one MCU's worth of arithmetic-compressed coefficients.
*/
METHODDEF(boolean)
decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
jpeg_component_info * compptr;
JBLOCKROW block;
unsigned char *st;
int blkn, ci, tbl, sign, k;
int v, m;
const int * natural_order;
/* Process restart marker if needed */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
process_restart(cinfo);
entropy->restarts_to_go--;
}
if (entropy->ct == -1) return TRUE; /* if error do nothing */
natural_order = cinfo->natural_order;
/* Outer loop handles each block in the MCU */
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
block = MCU_data[blkn];
ci = cinfo->MCU_membership[blkn];
compptr = cinfo->cur_comp_info[ci];
/* Sections F.2.4.1 & F.1.4.4.1: Decoding of DC coefficients */
tbl = compptr->dc_tbl_no;
/* Table F.4: Point to statistics bin S0 for DC coefficient coding */
st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
/* Figure F.19: Decode_DC_DIFF */
if (arith_decode(cinfo, st) == 0)
entropy->dc_context[ci] = 0;
else {
/* Figure F.21: Decoding nonzero value v */
/* Figure F.22: Decoding the sign of v */
sign = arith_decode(cinfo, st + 1);
st += 2; st += sign;
/* Figure F.23: Decoding the magnitude category of v */
if ((m = arith_decode(cinfo, st)) != 0) {
st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
while (arith_decode(cinfo, st)) {
if ((m <<= 1) == (int) 0x8000U) {
WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
entropy->ct = -1; /* magnitude overflow */
return TRUE;
}
st += 1;
}
}
/* Section F.1.4.4.1.2: Establish dc_context conditioning category */
if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))
entropy->dc_context[ci] = 0; /* zero diff category */
else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))
entropy->dc_context[ci] = 12 + (sign * 4); /* large diff category */
else
entropy->dc_context[ci] = 4 + (sign * 4); /* small diff category */
v = m;
/* Figure F.24: Decoding the magnitude bit pattern of v */
st += 14;
while (m >>= 1)
if (arith_decode(cinfo, st)) v |= m;
v += 1; if (sign) v = -v;
entropy->last_dc_val[ci] += v;
}
(*block)[0] = (JCOEF) entropy->last_dc_val[ci];
/* Sections F.2.4.2 & F.1.4.4.2: Decoding of AC coefficients */
if (cinfo->lim_Se == 0) continue;
tbl = compptr->ac_tbl_no;
k = 0;
/* Figure F.20: Decode_AC_coefficients */
do {
st = entropy->ac_stats[tbl] + 3 * k;
if (arith_decode(cinfo, st)) break; /* EOB flag */
for (;;) {
k++;
if (arith_decode(cinfo, st + 1)) break;
st += 3;
if (k >= cinfo->lim_Se) {
WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
entropy->ct = -1; /* spectral overflow */
return TRUE;
}
}
/* Figure F.21: Decoding nonzero value v */
/* Figure F.22: Decoding the sign of v */
sign = arith_decode(cinfo, entropy->fixed_bin);
st += 2;
/* Figure F.23: Decoding the magnitude category of v */
if ((m = arith_decode(cinfo, st)) != 0) {
if (arith_decode(cinfo, st)) {
m <<= 1;
st = entropy->ac_stats[tbl] +
(k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
while (arith_decode(cinfo, st)) {
if ((m <<= 1) == (int) 0x8000U) {
WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
entropy->ct = -1; /* magnitude overflow */
return TRUE;
}
st += 1;
}
}
}
v = m;
/* Figure F.24: Decoding the magnitude bit pattern of v */
st += 14;
while (m >>= 1)
if (arith_decode(cinfo, st)) v |= m;
v += 1; if (sign) v = -v;
(*block)[natural_order[k]] = (JCOEF) v;
} while (k < cinfo->lim_Se);
}
return TRUE;
}
/*
* Initialize for an arithmetic-compressed scan.
*/
METHODDEF(void)
start_pass (j_decompress_ptr cinfo)
{
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
int ci, tbl;
jpeg_component_info * compptr;
if (cinfo->progressive_mode) {
/* Validate progressive scan parameters */
if (cinfo->Ss == 0) {
if (cinfo->Se != 0)
goto bad;
} else {
/* need not check Ss/Se < 0 since they came from unsigned bytes */
if (cinfo->Se < cinfo->Ss || cinfo->Se > cinfo->lim_Se)
goto bad;
/* AC scans may have only one component */
if (cinfo->comps_in_scan != 1)
goto bad;
}
if (cinfo->Ah != 0) {
/* Successive approximation refinement scan: must have Al = Ah-1. */
if (cinfo->Ah-1 != cinfo->Al)
goto bad;
}
if (cinfo->Al > 13) { /* need not check for < 0 */
bad:
ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
}
/* Update progression status, and verify that scan order is legal.
* Note that inter-scan inconsistencies are treated as warnings
* not fatal errors ... not clear if this is right way to behave.
*/
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
int coefi, cindex = cinfo->cur_comp_info[ci]->component_index;
int *coef_bit_ptr = & cinfo->coef_bits[cindex][0];
if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
if (cinfo->Ah != expected)
WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
coef_bit_ptr[coefi] = cinfo->Al;
}
}
/* Select MCU decoding routine */
if (cinfo->Ah == 0) {
if (cinfo->Ss == 0)
entropy->pub.decode_mcu = decode_mcu_DC_first;
else
entropy->pub.decode_mcu = decode_mcu_AC_first;
} else {
if (cinfo->Ss == 0)
entropy->pub.decode_mcu = decode_mcu_DC_refine;
else
entropy->pub.decode_mcu = decode_mcu_AC_refine;
}
} else {
/* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
* This ought to be an error condition, but we make it a warning.
*/
if (cinfo->Ss != 0 || cinfo->Ah != 0 || cinfo->Al != 0 ||
(cinfo->Se < DCTSIZE2 && cinfo->Se != cinfo->lim_Se))
WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
/* Select MCU decoding routine */
entropy->pub.decode_mcu = decode_mcu;
}
/* Allocate & initialize requested statistics areas */
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
compptr = cinfo->cur_comp_info[ci];
if (! cinfo->progressive_mode || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
tbl = compptr->dc_tbl_no;
if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
if (entropy->dc_stats[tbl] == NULL)
entropy->dc_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo, JPOOL_IMAGE, DC_STAT_BINS);
MEMZERO(entropy->dc_stats[tbl], DC_STAT_BINS);
/* Initialize DC predictions to 0 */
entropy->last_dc_val[ci] = 0;
entropy->dc_context[ci] = 0;
}
if ((! cinfo->progressive_mode && cinfo->lim_Se) ||
(cinfo->progressive_mode && cinfo->Ss)) {
tbl = compptr->ac_tbl_no;
if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
if (entropy->ac_stats[tbl] == NULL)
entropy->ac_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo, JPOOL_IMAGE, AC_STAT_BINS);
MEMZERO(entropy->ac_stats[tbl], AC_STAT_BINS);
}
}
/* Initialize arithmetic decoding variables */
entropy->c = 0;
entropy->a = 0;
entropy->ct = -16; /* force reading 2 initial bytes to fill C */
/* Initialize restart counter */
entropy->restarts_to_go = cinfo->restart_interval;
}
/*
* Finish up at the end of an arithmetic-compressed scan.
*/
METHODDEF(void)
finish_pass (j_decompress_ptr cinfo)
{
/* no work necessary here */
}
/*
* Module initialization routine for arithmetic entropy decoding.
*/
GLOBAL(void)
jinit_arith_decoder (j_decompress_ptr cinfo)
{
arith_entropy_ptr entropy;
int i;
entropy = (arith_entropy_ptr) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(arith_entropy_decoder));
cinfo->entropy = &entropy->pub;
entropy->pub.start_pass = start_pass;
entropy->pub.finish_pass = finish_pass;
/* Mark tables unallocated */
for (i = 0; i < NUM_ARITH_TBLS; i++) {
entropy->dc_stats[i] = NULL;
entropy->ac_stats[i] = NULL;
}
/* Initialize index for fixed probability estimation */
entropy->fixed_bin[0] = 113;
if (cinfo->progressive_mode) {
/* Create progression status table */
int *coef_bit_ptr, ci;
cinfo->coef_bits = (int (*)[DCTSIZE2]) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo, JPOOL_IMAGE,
cinfo->num_components * DCTSIZE2 * SIZEOF(int));
coef_bit_ptr = & cinfo->coef_bits[0][0];
for (ci = 0; ci < cinfo->num_components; ci++)
for (i = 0; i < DCTSIZE2; i++)
*coef_bit_ptr++ = -1;
}
}
| 10,042 |
679 |
<reponame>Grosskopf/openoffice
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*************************************************************/
#ifndef _FMTCLDS_HXX
#define _FMTCLDS_HXX
#include <tools/color.hxx>
#include <svl/poolitem.hxx>
#include "swdllapi.h"
#include <hintids.hxx>
#include <format.hxx>
//Der ColumnDescriptor --------------------------
class SwColumn
{
sal_uInt16 nWish; //Wunschbreite incl. Raender.
//Verhaelt sich proportional zum Verhaeltniss:
//Wunschbreite der Umgebung / aktuelle Breite der Spalte
sal_uInt16 nUpper; //Oberer Rand
sal_uInt16 nLower; //Unterer Rand
sal_uInt16 nLeft; //Linker Rand
sal_uInt16 nRight; //Rechter Rand
public:
SwColumn();
sal_Bool operator==( const SwColumn & );
void SetWishWidth( sal_uInt16 nNew ) { nWish = nNew; }
void SetUpper( sal_uInt16 nNew ) { nUpper = nNew; }
void SetLower( sal_uInt16 nNew ) { nLower = nNew; }
void SetLeft ( sal_uInt16 nNew ) { nLeft = nNew; }
void SetRight( sal_uInt16 nNew ) { nRight = nNew; }
sal_uInt16 GetWishWidth() const { return nWish; }
sal_uInt16 GetUpper() const { return nUpper; }
sal_uInt16 GetLower() const { return nLower; }
sal_uInt16 GetLeft () const { return nLeft; }
sal_uInt16 GetRight() const { return nRight; }
};
typedef SwColumn* SwColumnPtr;
SV_DECL_PTRARR_DEL( SwColumns, SwColumnPtr, 0, 2 )
enum SwColLineAdj
{
COLADJ_NONE,
COLADJ_TOP,
COLADJ_CENTER,
COLADJ_BOTTOM
};
class SW_DLLPUBLIC SwFmtCol : public SfxPoolItem
{
// Pen aPen; //Pen fuer die Linine zwischen den Spalten
sal_uLong nLineWidth; //width of the separator line
Color aLineColor; //color of the separator line
sal_uInt8 nLineHeight; //Prozentuale Hoehe der Linien
//(Relativ zu der Hoehe der Spalten incl. UL).
SwColLineAdj eAdj; //Linie wird oben, mittig oder unten ausgerichtet.
SwColumns aColumns; //Informationen fuer die einzelnen Spalten.
sal_uInt16 nWidth; //Gesamtwunschbreite aller Spalten.
sal_Int16 aWidthAdjustValue;
sal_Bool bOrtho; //Nur wenn dieses Flag gesetzt ist wird beim setzen
//der GutterWidth eine 'optische Verteilung'
//vorgenommen.
//Es muss zurueckgesetzt werden wenn an den
//Spaltenbreiten bzw. den Raendern gedreht wird.
//Wenn es wieder gesetzt wird wird automatisch neu
//gemischt (optisch verteilt).
//Das Flag ist initial gesetzt.
SW_DLLPRIVATE void Calc( sal_uInt16 nGutterWidth, sal_uInt16 nAct );
public:
SwFmtCol();
SwFmtCol( const SwFmtCol& );
~SwFmtCol();
//i120133
sal_Int16 GetAdjustValue() const { return aWidthAdjustValue; }
void SetAdjustValue( const sal_Int16& n ) { aWidthAdjustValue = n; }
SwFmtCol& operator=( const SwFmtCol& );
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const;
virtual sal_Bool PutValue( const com::sun::star::uno::Any& rVal, sal_uInt8 nMemberId = 0 );
const SwColumns &GetColumns() const { return aColumns; }
SwColumns &GetColumns() { return aColumns; }
sal_uInt16 GetNumCols() const { return aColumns.Count(); }
// const Pen& GetLinePen() const { return aPen; }
sal_uLong GetLineWidth() const { return nLineWidth;}
const Color& GetLineColor() const { return aLineColor;}
SwColLineAdj GetLineAdj() const { return eAdj; }
sal_Bool IsOrtho() const { return bOrtho; }
sal_uInt16 GetWishWidth() const { return nWidth; }
sal_uInt8 GetLineHeight()const { return nLineHeight; }
//Return USHRT_MAX wenn uneindeutig.
//Return die kleinste Breite wenn bMin True ist.
sal_uInt16 GetGutterWidth( sal_Bool bMin = sal_False ) const;
// void SetLinePen( const Pen& rNew ) { aPen = rNew; }
void SetLineWidth(sal_uLong nLWidth) { nLineWidth = nLWidth;}
void SetLineColor(const Color& rCol ) { aLineColor = rCol;}
void SetLineHeight( sal_uInt8 nNew ) { nLineHeight = nNew; }
void SetLineAdj( SwColLineAdj eNew ){ eAdj = eNew; }
void SetWishWidth( sal_uInt16 nNew ) { nWidth = nNew; }
//Mit dieser Funktion koennen die Spalten (immer wieder) initialisert
//werden. Das Ortho Flag wird automatisch gesetzt.
void Init( sal_uInt16 nNumCols, sal_uInt16 nGutterWidth, sal_uInt16 nAct );
//Stellt die Raender fuer die Spalten in aColumns ein.
//Wenn das Flag bOrtho gesetzt ist, werden die Spalten neu optisch
//verteilt. Ist das Flag nicht gesetzt werden die Spaltenbreiten nicht
//veraendert und die Raender werden einfach eingestellt.
void SetGutterWidth( sal_uInt16 nNew, sal_uInt16 nAct );
//Verteilt ebenfalls automatisch neu wenn das Flag gesetzt wird;
//nur dann wird auch der zweite Param. benoetigt und beachtet.
void SetOrtho( sal_Bool bNew, sal_uInt16 nGutterWidth, sal_uInt16 nAct );
//Fuer den Reader
void _SetOrtho( sal_Bool bNew ) { bOrtho = bNew; }
//Berechnet die aktuelle Breite der Spalte nCol.
//Das Verhaeltniss von Wunschbreite der Spalte zum Returnwert ist
//proportional zum Verhaeltniss des Gesamtwunschwertes zu nAct.
sal_uInt16 CalcColWidth( sal_uInt16 nCol, sal_uInt16 nAct ) const;
//Wie oben, aber es wir die Breite der PrtArea - also das was fuer
//den Anwender die Spalte ist - geliefert.
sal_uInt16 CalcPrtColWidth( sal_uInt16 nCol, sal_uInt16 nAct ) const;
};
inline const SwFmtCol &SwAttrSet::GetCol(sal_Bool bInP) const
{ return (const SwFmtCol&)Get( RES_COL,bInP); }
inline const SwFmtCol &SwFmt::GetCol(sal_Bool bInP) const
{ return aSet.GetCol(bInP); }
#endif
| 2,654 |
456 |
<filename>src/test/java/com/swingfrog/summer/test/repository/task/TestLogTask.java
package com.swingfrog.summer.test.repository.task;
import com.swingfrog.summer.annotation.Autowired;
import com.swingfrog.summer.annotation.IntervalTask;
import com.swingfrog.summer.annotation.Task;
import com.swingfrog.summer.test.repository.dao.TestLogDao;
import com.swingfrog.summer.test.repository.model.TestLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;
@Task
public class TestLogTask {
private static final Logger log = LoggerFactory.getLogger(TestLogTask.class);
@Autowired
private TestLogDao testLogDao;
@IntervalTask(value = 1000, delay = 1000)
public void onTick() {
log.debug("tick");
TestLog testLog = new TestLog();
testLog.setValue(ThreadLocalRandom.current().nextInt());
testLog.setTime(new Date());
testLogDao.add(testLog);
}
}
| 374 |
575 |
<filename>components/arc/timer/arc_timer_mojom_traits.cc
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/arc/timer/arc_timer_mojom_traits.h"
#include <utility>
namespace mojo {
// static
arc::mojom::ClockId EnumTraits<arc::mojom::ClockId, clockid_t>::ToMojom(
clockid_t clock_id) {
switch (clock_id) {
case CLOCK_REALTIME_ALARM:
return arc::mojom::ClockId::REALTIME_ALARM;
case CLOCK_BOOTTIME_ALARM:
return arc::mojom::ClockId::BOOTTIME_ALARM;
}
NOTREACHED();
return arc::mojom::ClockId::BOOTTIME_ALARM;
}
// static
bool EnumTraits<arc::mojom::ClockId, clockid_t>::FromMojom(
arc::mojom::ClockId input,
clockid_t* output) {
switch (input) {
case arc::mojom::ClockId::REALTIME_ALARM:
*output = CLOCK_REALTIME_ALARM;
return true;
case arc::mojom::ClockId::BOOTTIME_ALARM:
*output = CLOCK_BOOTTIME_ALARM;
return true;
}
NOTREACHED();
return false;
}
} // namespace mojo
| 458 |
3,651 |
package com.orientechnologies.orient.server.network;
import com.orientechnologies.orient.core.config.OContextConfiguration;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinary;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/** Created by tglman on 10/05/17. */
public class MockPipeChannel extends OChannelBinary {
public MockPipeChannel(InputStream in, OutputStream out) throws IOException {
super(new Socket(), new OContextConfiguration());
this.in = new DataInputStream(in);
this.out = new DataOutputStream(out);
}
}
| 211 |
410 |
#include "private.h"
static void _declare_lookup_dumper(otl_LookupType llt, const char *lt, json_value *(*dumper)(const otl_Subtable *st),
otl_Lookup *lookup, json_value *dump) {
if (lookup->type == llt) {
json_object_push(dump, "type", json_string_new(lt));
json_object_push(dump, "flags", otfcc_dump_flags(lookup->flags, lookupFlagsLabels));
if (lookup->flags >> 8) { json_object_push(dump, "markAttachmentType", json_integer_new(lookup->flags >> 8)); }
json_value *subtables = json_array_new(lookup->subtables.length);
for (tableid_t j = 0; j < lookup->subtables.length; j++)
if (lookup->subtables.items[j]) { json_array_push(subtables, dumper(lookup->subtables.items[j])); }
json_object_push(dump, "subtables", subtables);
}
}
#define LOOKUP_DUMPER(llt, fn) _declare_lookup_dumper(llt, tableNames[llt], fn, lookup, dump);
static void _dump_lookup(otl_Lookup *lookup, json_value *dump) {
LOOKUP_DUMPER(otl_type_gsub_single, otl_gsub_dump_single);
LOOKUP_DUMPER(otl_type_gsub_multiple, otl_gsub_dump_multi);
LOOKUP_DUMPER(otl_type_gsub_alternate, otl_gsub_dump_multi);
LOOKUP_DUMPER(otl_type_gsub_ligature, otl_gsub_dump_ligature);
LOOKUP_DUMPER(otl_type_gsub_chaining, otl_dump_chaining);
LOOKUP_DUMPER(otl_type_gsub_reverse, otl_gsub_dump_reverse);
LOOKUP_DUMPER(otl_type_gpos_chaining, otl_dump_chaining);
LOOKUP_DUMPER(otl_type_gpos_single, otl_gpos_dump_single);
LOOKUP_DUMPER(otl_type_gpos_pair, otl_gpos_dump_pair);
LOOKUP_DUMPER(otl_type_gpos_cursive, otl_gpos_dump_cursive);
LOOKUP_DUMPER(otl_type_gpos_markToBase, otl_gpos_dump_markToSingle);
LOOKUP_DUMPER(otl_type_gpos_markToMark, otl_gpos_dump_markToSingle);
LOOKUP_DUMPER(otl_type_gpos_markToLigature, otl_gpos_dump_markToLigature);
}
void otfcc_dumpOtl(const table_OTL *table, json_value *root, const otfcc_Options *options, const char *tag) {
if (!table || !table->languages.length || !table->lookups.length || !table->features.length) return;
loggedStep("%s", tag) {
json_value *otl = json_object_new(3);
loggedStep("Languages") {
// dump script list
json_value *languages = json_object_new(table->languages.length);
for (tableid_t j = 0; j < table->languages.length; j++) {
json_value *_lang = json_object_new(5);
otl_LanguageSystem *lang = table->languages.items[j];
if (lang->requiredFeature) {
json_object_push(_lang, "requiredFeature", json_string_new(lang->requiredFeature->name));
}
json_value *features = json_array_new(lang->features.length);
for (tableid_t k = 0; k < lang->features.length; k++)
if (lang->features.items[k]) {
json_array_push(features, json_string_new(lang->features.items[k]->name));
}
json_object_push(_lang, "features", preserialize(features));
json_object_push(languages, lang->name, _lang);
}
json_object_push(otl, "languages", languages);
}
loggedStep("Features") {
// dump feature list
json_value *features = json_object_new(table->features.length);
for (tableid_t j = 0; j < table->features.length; j++) {
otl_Feature *feature = table->features.items[j];
json_value *_feature = json_array_new(feature->lookups.length);
for (tableid_t k = 0; k < feature->lookups.length; k++)
if (feature->lookups.items[k]) {
json_array_push(_feature, json_string_new(feature->lookups.items[k]->name));
}
json_object_push(features, feature->name, preserialize(_feature));
}
json_object_push(otl, "features", features);
}
loggedStep("Lookups") {
// dump lookups
json_value *lookups = json_object_new(table->lookups.length);
json_value *lookupOrder = json_array_new(table->lookups.length);
for (tableid_t j = 0; j < table->lookups.length; j++) {
json_value *_lookup = json_object_new(5);
otl_Lookup *lookup = table->lookups.items[j];
_dump_lookup(lookup, _lookup);
json_object_push(lookups, lookup->name, _lookup);
json_array_push(lookupOrder, json_string_new(lookup->name));
}
json_object_push(otl, "lookups", lookups);
json_object_push(otl, "lookupOrder", lookupOrder);
}
json_object_push(root, tag, otl);
}
}
| 1,765 |
512 |
<filename>tests/spot/blvt/test_blvt_info.py
import responses
from binance.spot import Spot as Client
from tests.util import mock_http_response
from tests.util import random_str
mock_item = {"key_1": "value_1", "key_2": "value_2"}
key = random_str()
secret = random_str()
@mock_http_response(responses.GET, "/sapi/v1/blvt/tokenInfo", mock_item, 200)
def test_blvt_info():
"""Tests the API endpoint to get BLVT Info"""
client = Client(key, secret)
response = client.blvt_info()
response.should.equal(mock_item)
@mock_http_response(
responses.GET, "/sapi/v1/blvt/tokenInfo\\?tokenName=LINKUP", mock_item, 200
)
def test_blvt_info_with_tokenName():
"""Tests the API endpoint to get BLVT Info with tokenName"""
client = Client(key, secret)
response = client.blvt_info("LINKUP")
response.should.equal(mock_item)
| 315 |
446 |
<gh_stars>100-1000
class PoeException(RuntimeError):
def __init__(self, msg, *args):
self.msg = msg
self.cause = args[0].args[0] if args else None
self.args = (msg, *args)
class CyclicDependencyError(PoeException):
pass
class ScriptParseError(PoeException):
pass
class ExecutionError(RuntimeError):
def __init__(self, msg, *args):
self.msg = msg
self.cause = args[0].args[0] if args else None
self.args = (msg, *args)
| 204 |
5,908 |
<reponame>rnorth/testpackage-containers
package org.testcontainers.containers;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.Container;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.wait.strategy.WaitStrategyTarget;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Class to provide a wait strategy target for services started through docker-compose
*/
@EqualsAndHashCode
class ComposeServiceWaitStrategyTarget implements WaitStrategyTarget {
private final Container container;
private final GenericContainer proxyContainer;
@NonNull
private Map<Integer, Integer> mappedPorts;
@Getter(lazy=true)
private final InspectContainerResponse containerInfo = DockerClientFactory.instance().client().inspectContainerCmd(getContainerId()).exec();
ComposeServiceWaitStrategyTarget(Container container, GenericContainer proxyContainer,
@NonNull Map<Integer, Integer> mappedPorts) {
this.container = container;
this.proxyContainer = proxyContainer;
this.mappedPorts = new HashMap<>(mappedPorts);
}
/**
* {@inheritDoc}
*/
@Override
public List<Integer> getExposedPorts() {
return new ArrayList<>(this.mappedPorts.keySet());
}
/**
* {@inheritDoc}
*/
@Override
public Integer getMappedPort(int originalPort) {
return this.proxyContainer.getMappedPort(this.mappedPorts.get(originalPort));
}
/**
* {@inheritDoc}
*/
@Override
public String getHost() {
return proxyContainer.getHost();
}
/**
* {@inheritDoc}
*/
@Override
public String getContainerId() {
return this.container.getId();
}
}
| 701 |
1,831 |
/**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "logdevice/common/protocol/GOSSIP_Message.h"
#include <memory>
#include <folly/small_vector.h>
#include "logdevice/common/Processor.h"
#include "logdevice/common/Worker.h"
#include "logdevice/common/debug.h"
#include "logdevice/common/protocol/ProtocolReader.h"
#include "logdevice/common/protocol/ProtocolWriter.h"
#include "logdevice/common/stats/ServerHistograms.h"
#include "logdevice/common/stats/Stats.h"
namespace facebook { namespace logdevice {
GOSSIP_Message::GOSSIP_Message(NodeID this_node,
node_list_t node_list,
std::chrono::milliseconds instance_id,
std::chrono::milliseconds sent_time,
boycott_list_t boycott_list,
boycott_durations_list_t boycott_durations,
GOSSIP_Message::GOSSIP_flags_t flags,
uint64_t msg_id,
GOSSIP_Message::rsmtype_list_t rsm_types,
GOSSIP_Message::versions_node_list_t versions)
: Message(MessageType::GOSSIP, TrafficClass::FAILURE_DETECTOR),
node_list_(std::move(node_list)),
gossip_node_(this_node),
flags_(flags),
instance_id_(instance_id),
sent_time_(sent_time),
num_boycotts_(boycott_list.size()),
boycott_list_(std::move(boycott_list)),
boycott_durations_list_(std::move(boycott_durations)),
msg_id_(msg_id),
rsm_types_(rsm_types),
versions_(versions) {}
Message::Disposition GOSSIP_Message::onReceived(const Address& /*from*/) {
// Receipt handler lives in server/GOSSIP_onReceived.cpp; this should
// never get called.
std::abort();
}
void GOSSIP_Message::serialize(ProtocolWriter& writer) const {
auto flags = flags_;
writer.write((uint16_t)node_list_.size());
writer.write(gossip_node_);
writer.write(flags);
writer.write(instance_id_);
writer.write(sent_time_);
writeBoycottList(writer);
writeBoycottDurations(writer);
if (writer.proto() <
Compatibility::ProtocolVersion::HEALTH_MONITOR_SUPPORT_IN_GOSSIP) {
legacy_node_list_t legacy_node_list{};
std::transform(node_list_.begin(),
node_list_.end(),
std::back_inserter(legacy_node_list),
[](GOSSIP_Node gossip_node) {
return static_cast<GOSSIP_Node_Legacy>(gossip_node);
});
writer.writeVector(legacy_node_list);
} else {
writer.writeVector(node_list_);
if (flags & HAS_IN_MEM_VERSIONS || flags & HAS_DURABLE_SNAPSHOT_VERSIONS) {
writeVersions(writer);
}
}
}
MessageReadResult GOSSIP_Message::deserialize(ProtocolReader& reader) {
std::unique_ptr<GOSSIP_Message> msg(new GOSSIP_Message());
gossip_list_t gossip_list;
gossip_ts_t gossip_ts;
failover_list_t failover_list;
std::unordered_set<node_index_t> is_starting;
uint16_t num_nodes;
reader.read(&num_nodes);
reader.read(&msg->gossip_node_);
reader.read(&msg->flags_);
reader.read(&msg->instance_id_);
reader.read(&msg->sent_time_);
msg->readBoycottList(reader);
msg->readBoycottDurations(reader);
if (reader.proto() <
Compatibility::ProtocolVersion::HEALTH_MONITOR_SUPPORT_IN_GOSSIP) {
legacy_node_list_t legacy_node_list{};
reader.readVector(&legacy_node_list, num_nodes);
std::transform(legacy_node_list.begin(),
legacy_node_list.end(),
std::back_inserter(msg->node_list_),
[](GOSSIP_Node_Legacy gossip_node) {
return GOSSIP_Node{gossip_node};
});
} else {
reader.readVector(&msg->node_list_, num_nodes);
if (msg->flags_ & HAS_IN_MEM_VERSIONS ||
msg->flags_ & HAS_DURABLE_SNAPSHOT_VERSIONS) {
// For future compatibility deserialize messages with durable flag.
// It will be discarded in this commit of the code, but will be supported
// in future iteration(once Local snapshot store is implemented)
msg->readVersions(reader, num_nodes);
}
}
return reader.resultMsg(std::move(msg));
}
void GOSSIP_Message::onSent(Status /*st*/, const Address& /*to*/) const {
// Receipt handler lives in server/GOSSIP_onSent.cpp; this should
// never get called.
std::abort();
}
PermissionParams GOSSIP_Message::getPermissionParams() const {
PermissionParams params;
params.requiresPermission = true;
params.action = ACTION::SERVER_INTERNAL;
return params;
}
void GOSSIP_Message::writeBoycottList(ProtocolWriter& writer) const {
ld_check(boycott_list_.size() == num_boycotts_);
writer.write(num_boycotts_);
for (auto& boycott : boycott_list_) {
writer.write(boycott.node_index);
writer.write(boycott.boycott_in_effect_time);
writer.write(boycott.boycott_duration);
writer.write(boycott.reset);
}
}
void GOSSIP_Message::readBoycottList(ProtocolReader& reader) {
reader.read(&num_boycotts_);
boycott_list_.resize(num_boycotts_);
for (auto& boycott : boycott_list_) {
reader.read(&boycott.node_index);
reader.read(&boycott.boycott_in_effect_time);
reader.read(&boycott.boycott_duration);
reader.read(&boycott.reset);
}
}
std::chrono::milliseconds GOSSIP_Message::getDefaultBoycottDuration() const {
return Worker::settings().sequencer_boycotting.node_stats_boycott_duration;
}
// flattens the boycott durations and write them
void GOSSIP_Message::writeBoycottDurations(ProtocolWriter& writer) const {
writer.write(boycott_durations_list_.size());
for (const auto& d : boycott_durations_list_) {
d.serialize(writer);
}
}
// reads the flattened boycott durations and unflatten them
void GOSSIP_Message::readBoycottDurations(ProtocolReader& reader) {
size_t list_size;
reader.read(&list_size);
boycott_durations_list_.resize(list_size);
for (auto& d : boycott_durations_list_) {
d.deserialize(reader);
}
}
void GOSSIP_Message::writeVersions(ProtocolWriter& writer) const {
if (writer.proto() <
Compatibility::ProtocolVersion::INCLUDE_VERSIONS_IN_GOSSIP) {
return;
}
ld_check(rsm_types_.size() <= UINT8_MAX);
uint8_t num_rsms_ = rsm_types_.size();
writer.write(num_rsms_);
for (const auto& rsm_type : rsm_types_) {
writer.write(rsm_type);
}
for (const auto& node : versions_) {
writer.write(node.node_id_);
ld_check(node.rsm_versions_.size() == num_rsms_);
for (const auto& rsm_ver : node.rsm_versions_) {
writer.write(rsm_ver);
}
// Write NCM information
for (size_t i = 0; i < node.ncm_versions_.size(); ++i) {
writer.write(node.ncm_versions_[i]);
}
}
}
void GOSSIP_Message::readVersions(ProtocolReader& reader, uint16_t num_nodes) {
if (reader.proto() <
Compatibility::ProtocolVersion::INCLUDE_VERSIONS_IN_GOSSIP) {
return;
}
uint8_t num_rsms_;
reader.read(&num_rsms_);
if (num_rsms_ == 0) {
return;
}
rsm_types_.resize(num_rsms_);
for (uint8_t i = 0; i < num_rsms_; ++i) {
reader.read(&rsm_types_[i]);
}
versions_.resize(num_nodes);
for (size_t i = 0; i < num_nodes; ++i) {
reader.read(&versions_[i].node_id_);
// Read RSM information
versions_[i].rsm_versions_.resize(num_rsms_);
for (uint8_t j = 0; j < num_rsms_; ++j) {
reader.read(&versions_[i].rsm_versions_[j]);
}
// Read NCM information
for (size_t k = 0; k < versions_[i].ncm_versions_.size(); ++k) {
reader.read(&versions_[i].ncm_versions_[k]);
}
}
}
}} // namespace facebook::logdevice
| 3,271 |
1,090 |
<filename>deps/winpty/src/agent/UnicodeEncodingTest.cc
// Copyright (c) 2015 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// Encode every code-point using this module and verify that it matches the
// encoding generated using Windows WideCharToMultiByte.
#include "UnicodeEncoding.h"
#include <windows.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
static void correctnessByCode()
{
char mbstr1[4];
char mbstr2[4];
wchar_t wch[2];
for (unsigned int code = 0; code < 0x110000; ++code) {
// Surrogate pair reserved region.
const bool isReserved = (code >= 0xD800 && code <= 0xDFFF);
int mblen1 = encodeUtf8(mbstr1, code);
if (isReserved ? mblen1 != 0 : mblen1 <= 0) {
printf("Error: 0x%04X: mblen1=%d\n", code, mblen1);
continue;
}
int wlen = encodeUtf16(wch, code);
if (isReserved ? wlen != 0 : wlen <= 0) {
printf("Error: 0x%04X: wlen=%d\n", code, wlen);
continue;
}
if (isReserved) {
continue;
}
if (mblen1 != utf8CharLength(mbstr1[0])) {
printf("Error: 0x%04X: mblen1=%d, utf8CharLength(mbstr1[0])=%d\n",
code, mblen1, utf8CharLength(mbstr1[0]));
continue;
}
if (code != decodeUtf8(mbstr1)) {
printf("Error: 0x%04X: decodeUtf8(mbstr1)=%u\n",
code, decodeUtf8(mbstr1));
continue;
}
int mblen2 = WideCharToMultiByte(CP_UTF8, 0, wch, wlen, mbstr2, 4, NULL, NULL);
if (mblen1 != mblen2) {
printf("Error: 0x%04X: mblen1=%d, mblen2=%d\n", code, mblen1, mblen2);
continue;
}
if (memcmp(mbstr1, mbstr2, mblen1) != 0) {
printf("Error: 0x%04x: encodings are different\n", code);
continue;
}
}
}
static const char *encodingStr(char (&output)[128], char (&buf)[4])
{
sprintf(output, "Encoding %02X %02X %02X %02X",
static_cast<uint8_t>(buf[0]),
static_cast<uint8_t>(buf[1]),
static_cast<uint8_t>(buf[2]),
static_cast<uint8_t>(buf[3]));
return output;
}
// This test can take a couple of minutes to run.
static void correctnessByUtf8Encoding()
{
for (uint64_t encoding = 0; encoding <= 0xFFFFFFFF; ++encoding) {
char mb[4];
mb[0] = encoding;
mb[1] = encoding >> 8;
mb[2] = encoding >> 16;
mb[3] = encoding >> 24;
const int mblen = utf8CharLength(mb[0]);
if (mblen == 0) {
continue;
}
// Test this module.
const uint32_t code1 = decodeUtf8(mb);
wchar_t ws1[2] = {};
const int wslen1 = encodeUtf16(ws1, code1);
// Test using Windows. We can't decode a codepoint directly; we have
// to do UTF8->UTF16, then decode the surrogate pair.
wchar_t ws2[2] = {};
const int wslen2 = MultiByteToWideChar(
CP_UTF8, MB_ERR_INVALID_CHARS, mb, mblen, ws2, 2);
const uint32_t code2 =
(wslen2 == 1 ? ws2[0] :
wslen2 == 2 ? decodeSurrogatePair(ws2[0], ws2[1]) :
static_cast<uint32_t>(-1));
// Verify that the two implementations match.
char prefix[128];
if (code1 != code2) {
printf("%s: code1=0x%04x code2=0x%04x\n",
encodingStr(prefix, mb),
code1, code2);
continue;
}
if (wslen1 != wslen2) {
printf("%s: wslen1=%d wslen2=%d\n",
encodingStr(prefix, mb),
wslen1, wslen2);
continue;
}
if (memcmp(ws1, ws2, wslen1 * sizeof(wchar_t)) != 0) {
printf("%s: ws1 != ws2\n", encodingStr(prefix, mb));
continue;
}
}
}
wchar_t g_wch_TEST[] = { 0xD840, 0xDC00 };
char g_ch_TEST[4];
wchar_t *volatile g_pwch = g_wch_TEST;
char *volatile g_pch = g_ch_TEST;
unsigned int volatile g_code = 0xA2000;
static void performance()
{
{
clock_t start = clock();
for (long long i = 0; i < 250000000LL; ++i) {
int mblen = WideCharToMultiByte(CP_UTF8, 0, g_pwch, 2, g_pch, 4, NULL, NULL);
assert(mblen == 4);
}
clock_t stop = clock();
printf("%.3fns per char\n", (double)(stop - start) / CLOCKS_PER_SEC * 4.0);
}
{
clock_t start = clock();
for (long long i = 0; i < 3000000000LL; ++i) {
int mblen = encodeUtf8(g_pch, g_code);
assert(mblen == 4);
}
clock_t stop = clock();
printf("%.3fns per char\n", (double)(stop - start) / CLOCKS_PER_SEC / 3.0);
}
}
int main()
{
printf("Testing correctnessByCode...\n");
fflush(stdout);
correctnessByCode();
printf("Testing correctnessByUtf8Encoding... (may take a couple minutes)\n");
fflush(stdout);
correctnessByUtf8Encoding();
printf("Testing performance...\n");
fflush(stdout);
performance();
return 0;
}
| 2,853 |
1,008 |
/**
* Copyright 2010 - 2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.log;
import org.jetbrains.annotations.NotNull;
public class RandomAccessLoggableImpl implements RandomAccessLoggable {
private final byte type;
private final byte headerLength;
private final int length;
@NotNull
private final ByteIterableWithAddress data;
private final int structureId;
public RandomAccessLoggableImpl(final long address,
final byte type,
@NotNull final ByteIterableWithAddress data,
final int dataLength,
final int structureId) {
this.type = type;
this.headerLength = (byte) (data.getDataAddress() - address);
this.length = dataLength + headerLength;
this.data = data;
this.structureId = structureId;
}
@Override
public long getAddress() {
return data.getDataAddress() - headerLength;
}
@Override
public byte getType() {
return type;
}
@Override
public int length() {
return length;
}
@NotNull
@Override
public ByteIterableWithAddress getData() {
return data;
}
public int getDataLength() {
return length - headerLength;
}
@Override
public int getStructureId() {
return structureId;
}
}
| 751 |
14,668 |
<reponame>chromium/chromium
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/identity/identity_get_auth_token_function.h"
#include <set>
#include <vector>
#include "base/bind.h"
#include "base/feature_list.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "base/strings/string_number_conversions.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/extensions/api/identity/identity_api.h"
#include "chrome/browser/extensions/api/identity/identity_constants.h"
#include "chrome/browser/extensions/api/identity/identity_get_auth_token_error.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/chrome_device_id_helper.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/signin/signin_ui_util.h"
#include "chrome/common/channel_info.h"
#include "chrome/common/extensions/api/identity.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/base/signin_pref_names.h"
#include "components/signin/public/base/signin_switches.h"
#include "components/signin/public/identity_manager/access_token_info.h"
#include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h"
#include "components/signin/public/identity_manager/scope_set.h"
#include "components/version_info/version_info.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/common/api/oauth2.h"
#include "extensions/common/extension_features.h"
#include "extensions/common/extension_l10n_util.h"
#include "extensions/common/manifest_handlers/oauth2_manifest_handler.h"
#include "google_apis/gaia/gaia_auth_util.h"
#include "google_apis/gaia/gaia_urls.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "chrome/browser/app_mode/app_mode_utils.h"
#include "chrome/browser/ash/login/session/user_session_manager.h"
#include "chrome/browser/ash/policy/core/browser_policy_connector_ash.h"
#include "chrome/browser/device_identity/device_oauth2_token_service.h"
#include "chrome/browser/device_identity/device_oauth2_token_service_factory.h"
#include "components/user_manager/user_manager.h"
#include "google_apis/gaia/gaia_constants.h"
#endif
namespace extensions {
namespace {
const char* const kExtensionsIdentityAPIOAuthConsumerName =
"extensions_identity_api";
bool IsBrowserSigninAllowed(Profile* profile) {
return profile->GetPrefs()->GetBoolean(prefs::kSigninAllowed);
}
std::string GetOAuth2MintTokenFlowVersion() {
return version_info::GetVersionNumber();
}
std::string GetOAuth2MintTokenFlowChannel() {
return version_info::GetChannelString(chrome::GetChannel());
}
void RecordFunctionResult(const IdentityGetAuthTokenError& error,
bool remote_consent_approved) {
base::UmaHistogramEnumeration("Signin.Extensions.GetAuthTokenResult",
error.state());
if (remote_consent_approved) {
base::UmaHistogramEnumeration(
"Signin.Extensions.GetAuthTokenResult.RemoteConsentApproved",
error.state());
}
}
} // namespace
IdentityGetAuthTokenFunction::IdentityGetAuthTokenFunction()
#if BUILDFLAG(IS_CHROMEOS_ASH)
: OAuth2AccessTokenManager::Consumer(
kExtensionsIdentityAPIOAuthConsumerName)
#endif
{
}
IdentityGetAuthTokenFunction::~IdentityGetAuthTokenFunction() {
TRACE_EVENT_NESTABLE_ASYNC_END0("identity", "IdentityGetAuthTokenFunction",
this);
}
ExtensionFunction::ResponseAction IdentityGetAuthTokenFunction::Run() {
TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("identity", "IdentityGetAuthTokenFunction",
this, "extension", extension()->id());
if (GetProfile()->IsOffTheRecord()) {
IdentityGetAuthTokenError error(
IdentityGetAuthTokenError::State::kOffTheRecord);
RecordFunctionResult(error, remote_consent_approved_);
return RespondNow(Error(error.ToString()));
}
std::unique_ptr<api::identity::GetAuthToken::Params> params(
api::identity::GetAuthToken::Params::Create(args()));
EXTENSION_FUNCTION_VALIDATE(params.get());
interactive_ = params->details.get() && params->details->interactive.get() &&
*params->details->interactive;
should_prompt_for_scopes_ = interactive_;
should_prompt_for_signin_ =
interactive_ && IsBrowserSigninAllowed(GetProfile());
enable_granular_permissions_ =
params->details.get() &&
params->details->enable_granular_permissions.get() &&
*params->details->enable_granular_permissions;
DCHECK(extension());
const auto& oauth2_info = OAuth2ManifestHandler::GetOAuth2Info(*extension());
// Check that the necessary information is present in the manifest.
oauth2_client_id_ = GetOAuth2ClientId();
if (oauth2_client_id_.empty()) {
IdentityGetAuthTokenError error(
IdentityGetAuthTokenError::State::kInvalidClientId);
RecordFunctionResult(error, remote_consent_approved_);
return RespondNow(Error(error.ToString()));
}
std::set<std::string> scopes(oauth2_info.scopes.begin(),
oauth2_info.scopes.end());
std::string gaia_id;
if (params->details.get()) {
if (params->details->account.get())
gaia_id = params->details->account->id;
if (params->details->scopes.get()) {
scopes = std::set<std::string>(params->details->scopes->begin(),
params->details->scopes->end());
}
}
if (scopes.empty()) {
IdentityGetAuthTokenError error(
IdentityGetAuthTokenError::State::kEmptyScopes);
RecordFunctionResult(error, remote_consent_approved_);
return RespondNow(Error(error.ToString()));
}
token_key_.scopes = scopes;
token_key_.extension_id = extension()->id();
if (gaia_id.empty() && !IsPrimaryAccountOnly()) {
gaia_id = IdentityAPI::GetFactoryInstance()
->Get(GetProfile())
->GetGaiaIdForExtension(token_key_.extension_id)
.value_or("");
}
selected_gaia_id_ = gaia_id;
// From here on out, results must be returned asynchronously.
StartAsyncRun();
if (gaia_id.empty() || IsPrimaryAccountOnly()) {
// Try the primary account.
// TODO(https://crbug.com/932400): collapse the asynchronicity
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(
&IdentityGetAuthTokenFunction::GetAuthTokenForPrimaryAccount,
weak_ptr_factory_.GetWeakPtr(), gaia_id));
} else {
// Get the AccountInfo for the account that the extension wishes to use.
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&IdentityGetAuthTokenFunction::FetchExtensionAccountInfo,
weak_ptr_factory_.GetWeakPtr(), gaia_id));
}
return RespondLater();
}
void IdentityGetAuthTokenFunction::GetAuthTokenForPrimaryAccount(
const std::string& extension_gaia_id) {
auto* identity_manager = IdentityManagerFactory::GetForProfile(GetProfile());
CoreAccountInfo primary_account_info =
identity_manager->GetPrimaryAccountInfo(signin::ConsentLevel::kSync);
bool primary_account_only = IsPrimaryAccountOnly();
// Detect and handle the case where the extension is using an account other
// than the primary account.
if (primary_account_only && !extension_gaia_id.empty() &&
extension_gaia_id != primary_account_info.gaia) {
CompleteFunctionWithError(IdentityGetAuthTokenError(
IdentityGetAuthTokenError::State::kUserNonPrimary));
return;
}
if (primary_account_only || !primary_account_info.gaia.empty()) {
// The extension is using the primary account.
OnReceivedExtensionAccountInfo(primary_account_info);
} else {
// No primary account, try the first account in cookies.
DCHECK_EQ(AccountListeningMode::kNotListening, account_listening_mode_);
account_listening_mode_ = AccountListeningMode::kListeningCookies;
signin::AccountsInCookieJarInfo accounts_in_cookies =
identity_manager->GetAccountsInCookieJar();
if (accounts_in_cookies.accounts_are_fresh) {
OnAccountsInCookieUpdated(accounts_in_cookies,
GoogleServiceAuthError::AuthErrorNone());
} else {
scoped_identity_manager_observation_.Observe(identity_manager);
}
}
}
void IdentityGetAuthTokenFunction::FetchExtensionAccountInfo(
const std::string& gaia_id) {
OnReceivedExtensionAccountInfo(
IdentityManagerFactory::GetForProfile(GetProfile())
->FindExtendedAccountInfoByGaiaId(gaia_id));
}
void IdentityGetAuthTokenFunction::OnReceivedExtensionAccountInfo(
const CoreAccountInfo& account_info) {
token_key_.account_info = account_info;
#if BUILDFLAG(IS_CHROMEOS_ASH)
policy::BrowserPolicyConnectorAsh* connector =
g_browser_process->platform_part()->browser_policy_connector_ash();
bool is_kiosk = user_manager::UserManager::Get()->IsLoggedInAsKioskApp() ||
user_manager::UserManager::Get()->IsLoggedInAsWebKioskApp();
bool is_public_session =
user_manager::UserManager::Get()->IsLoggedInAsPublicAccount();
if (connector->IsDeviceEnterpriseManaged() &&
(is_kiosk || is_public_session)) {
if (is_public_session) {
CompleteFunctionWithError(IdentityGetAuthTokenError(
IdentityGetAuthTokenError::State::kNotAllowlistedInPublicSession));
return;
}
StartMintTokenFlow(IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE);
return;
}
#endif
if (account_info.IsEmpty() ||
!IdentityManagerFactory::GetForProfile(GetProfile())
->HasAccountWithRefreshToken(account_info.account_id)) {
if (!ShouldStartSigninFlow()) {
IdentityGetAuthTokenError error(
IsBrowserSigninAllowed(GetProfile())
? IdentityGetAuthTokenError::State::kUserNotSignedIn
: IdentityGetAuthTokenError::State::kBrowserSigninNotAllowed);
CompleteFunctionWithError(error);
return;
}
// Display a login prompt.
StartSigninFlow();
} else {
StartMintTokenFlow(IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE);
}
}
void IdentityGetAuthTokenFunction::OnAccountsInCookieUpdated(
const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info,
const GoogleServiceAuthError& error) {
if (account_listening_mode_ != AccountListeningMode::kListeningCookies)
return;
// Stop listening cookies.
account_listening_mode_ = AccountListeningMode::kNotListening;
scoped_identity_manager_observation_.Reset();
const std::vector<gaia::ListedAccount>& accounts =
accounts_in_cookie_jar_info.signed_in_accounts;
if (!accounts.empty()) {
const gaia::ListedAccount& account = accounts[0];
// If the account is in auth error, it won't be in the identity manager.
// Save the email now to use as email hint for the login prompt.
email_for_default_web_account_ = account.email;
OnReceivedExtensionAccountInfo(
IdentityManagerFactory::GetForProfile(GetProfile())
->FindExtendedAccountInfoByGaiaId(account.gaia_id));
} else {
OnReceivedExtensionAccountInfo(CoreAccountInfo());
}
}
void IdentityGetAuthTokenFunction::StartAsyncRun() {
// Balanced in CompleteAsyncRun
AddRef();
identity_api_shutdown_subscription_ =
extensions::IdentityAPI::GetFactoryInstance()
->Get(GetProfile())
->RegisterOnShutdownCallback(base::BindOnce(
&IdentityGetAuthTokenFunction::OnIdentityAPIShutdown, this));
}
void IdentityGetAuthTokenFunction::CompleteAsyncRun(ResponseValue response) {
identity_api_shutdown_subscription_ = {};
Respond(std::move(response));
Release(); // Balanced in StartAsyncRun
}
void IdentityGetAuthTokenFunction::CompleteFunctionWithResult(
const std::string& access_token,
const std::set<std::string>& granted_scopes) {
RecordFunctionResult(IdentityGetAuthTokenError(), remote_consent_approved_);
std::unique_ptr<base::Value> granted_scopes_value =
std::make_unique<base::Value>(base::Value::Type::LIST);
for (const auto& scope : granted_scopes)
granted_scopes_value->Append(scope);
CompleteAsyncRun(TwoArguments(
base::Value(access_token),
base::Value::FromUniquePtrValue(std::move(granted_scopes_value))));
}
void IdentityGetAuthTokenFunction::CompleteFunctionWithError(
const IdentityGetAuthTokenError& error) {
TRACE_EVENT_NESTABLE_ASYNC_INSTANT1("identity", "CompleteFunctionWithError",
this, "error", error.ToString());
RecordFunctionResult(error, remote_consent_approved_);
CompleteAsyncRun(Error(error.ToString()));
}
bool IdentityGetAuthTokenFunction::ShouldStartSigninFlow() {
if (!should_prompt_for_signin_)
return false;
auto* identity_manager = IdentityManagerFactory::GetForProfile(GetProfile());
bool account_needs_reauth =
!identity_manager->HasAccountWithRefreshToken(
token_key_.account_info.account_id) ||
identity_manager->HasAccountWithRefreshTokenInPersistentErrorState(
token_key_.account_info.account_id);
return account_needs_reauth;
}
void IdentityGetAuthTokenFunction::StartSigninFlow() {
DCHECK(ShouldStartSigninFlow());
// All cached tokens are invalid because the user is not signed in.
IdentityAPI* id_api =
extensions::IdentityAPI::GetFactoryInstance()->Get(GetProfile());
id_api->token_cache()->EraseAllTokens();
// If the signin flow fails, don't display the login prompt again.
should_prompt_for_signin_ = false;
#if BUILDFLAG(IS_CHROMEOS_ASH)
// In normal mode (i.e. non-kiosk mode), the user has to log out to
// re-establish credentials. Let the global error popup handle everything.
// In kiosk mode, interactive sign-in is not supported.
SigninFailed();
#else
if (g_browser_process->IsShuttingDown()) {
// The login prompt cannot be displayed when the browser process is shutting
// down.
SigninFailed();
return;
}
DCHECK_EQ(AccountListeningMode::kNotListening, account_listening_mode_);
auto* identity_manager = IdentityManagerFactory::GetForProfile(GetProfile());
account_listening_mode_ = AccountListeningMode::kListeningTokens;
if (IsPrimaryAccountOnly()) {
if (!identity_manager->HasPrimaryAccount(signin::ConsentLevel::kSync)) {
account_listening_mode_ = AccountListeningMode::kListeningPrimaryAccount;
} else {
// Fixing an authentication error. Either there is no token, or it is in
// error.
DCHECK_EQ(
token_key_.account_info.account_id,
identity_manager->GetPrimaryAccountId(signin::ConsentLevel::kSync));
DCHECK(!identity_manager->HasAccountWithRefreshToken(
token_key_.account_info.account_id) ||
identity_manager->HasAccountWithRefreshTokenInPersistentErrorState(
token_key_.account_info.account_id));
}
}
scoped_identity_manager_observation_.Observe(identity_manager);
ShowExtensionLoginPrompt();
#endif
}
void IdentityGetAuthTokenFunction::StartMintTokenFlow(
IdentityMintRequestQueue::MintType type) {
#if !BUILDFLAG(IS_CHROMEOS_ASH)
// ChromeOS in kiosk mode may start the mint token flow without account.
DCHECK(!token_key_.account_info.IsEmpty());
DCHECK(IdentityManagerFactory::GetForProfile(GetProfile())
->HasAccountWithRefreshToken(token_key_.account_info.account_id));
#endif
TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("identity", "MintTokenFlow", this, "type",
type);
mint_token_flow_type_ = type;
// Flows are serialized to prevent excessive traffic to GAIA, and
// to consolidate UI pop-ups.
IdentityAPI* id_api =
extensions::IdentityAPI::GetFactoryInstance()->Get(GetProfile());
if (!should_prompt_for_scopes_) {
// Caller requested no interaction.
if (type == IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE) {
// GAIA told us to do a consent UI.
CompleteFunctionWithError(IdentityGetAuthTokenError(
IdentityGetAuthTokenError::State::kGaiaConsentInteractionRequired));
return;
}
if (!id_api->mint_queue()->empty(
IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE, token_key_)) {
// Another call is going through a consent UI.
CompleteFunctionWithError(
IdentityGetAuthTokenError(IdentityGetAuthTokenError::State::
kGaiaConsentInteractionAlreadyRunning));
return;
}
}
id_api->mint_queue()->RequestStart(type, token_key_, this);
}
void IdentityGetAuthTokenFunction::CompleteMintTokenFlow() {
TRACE_EVENT_NESTABLE_ASYNC_END0("identity", "MintTokenFlow", this);
IdentityMintRequestQueue::MintType type = mint_token_flow_type_;
extensions::IdentityAPI::GetFactoryInstance()
->Get(GetProfile())
->mint_queue()
->RequestComplete(type, token_key_, this);
}
void IdentityGetAuthTokenFunction::StartMintToken(
IdentityMintRequestQueue::MintType type) {
TRACE_EVENT_NESTABLE_ASYNC_INSTANT1("identity", "StartMintToken", this,
"type", type);
DCHECK(extension());
const auto& oauth2_info = OAuth2ManifestHandler::GetOAuth2Info(*extension());
IdentityAPI* id_api = IdentityAPI::GetFactoryInstance()->Get(GetProfile());
IdentityTokenCacheValue cache_entry =
id_api->token_cache()->GetToken(token_key_);
IdentityTokenCacheValue::CacheValueStatus cache_status = cache_entry.status();
if (type == IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE) {
switch (cache_status) {
case IdentityTokenCacheValue::CACHE_STATUS_NOTFOUND:
#if BUILDFLAG(IS_CHROMEOS_ASH)
// Always force minting token for ChromeOS kiosk app and public session.
if (user_manager::UserManager::Get()->IsLoggedInAsPublicAccount()) {
CompleteFunctionWithError(
IdentityGetAuthTokenError(IdentityGetAuthTokenError::State::
kNotAllowlistedInPublicSession));
return;
}
if (user_manager::UserManager::Get()->IsLoggedInAsKioskApp() ||
user_manager::UserManager::Get()->IsLoggedInAsWebKioskApp() ||
user_manager::UserManager::Get()->IsLoggedInAsPublicAccount()) {
gaia_mint_token_mode_ = OAuth2MintTokenFlow::MODE_MINT_TOKEN_FORCE;
policy::BrowserPolicyConnectorAsh* connector =
g_browser_process->platform_part()
->browser_policy_connector_ash();
if (connector->IsDeviceEnterpriseManaged()) {
StartDeviceAccessTokenRequest();
} else {
StartTokenKeyAccountAccessTokenRequest();
}
return;
}
#endif
if (oauth2_info.auto_approve && *oauth2_info.auto_approve) {
// oauth2_info.auto_approve is protected by an allowlist in
// _manifest_features.json hence only selected extensions take
// advantage of forcefully minting the token.
gaia_mint_token_mode_ = OAuth2MintTokenFlow::MODE_MINT_TOKEN_FORCE;
} else {
gaia_mint_token_mode_ = OAuth2MintTokenFlow::MODE_MINT_TOKEN_NO_FORCE;
}
StartTokenKeyAccountAccessTokenRequest();
break;
case IdentityTokenCacheValue::CACHE_STATUS_TOKEN:
CompleteMintTokenFlow();
CompleteFunctionWithResult(cache_entry.token(),
cache_entry.granted_scopes());
break;
case IdentityTokenCacheValue::CACHE_STATUS_REMOTE_CONSENT:
CompleteMintTokenFlow();
should_prompt_for_signin_ = false;
resolution_data_ = cache_entry.resolution_data();
StartMintTokenFlow(IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE);
break;
case IdentityTokenCacheValue::CACHE_STATUS_REMOTE_CONSENT_APPROVED:
consent_result_ = cache_entry.consent_result();
should_prompt_for_signin_ = false;
gaia_mint_token_mode_ = OAuth2MintTokenFlow::MODE_MINT_TOKEN_NO_FORCE;
StartTokenKeyAccountAccessTokenRequest();
break;
}
} else {
DCHECK(type == IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE);
switch (cache_status) {
case IdentityTokenCacheValue::CACHE_STATUS_TOKEN:
CompleteMintTokenFlow();
CompleteFunctionWithResult(cache_entry.token(),
cache_entry.granted_scopes());
break;
case IdentityTokenCacheValue::CACHE_STATUS_NOTFOUND:
case IdentityTokenCacheValue::CACHE_STATUS_REMOTE_CONSENT:
ShowRemoteConsentDialog(resolution_data_);
break;
case IdentityTokenCacheValue::CACHE_STATUS_REMOTE_CONSENT_APPROVED:
consent_result_ = cache_entry.consent_result();
should_prompt_for_signin_ = false;
gaia_mint_token_mode_ = OAuth2MintTokenFlow::MODE_MINT_TOKEN_NO_FORCE;
StartTokenKeyAccountAccessTokenRequest();
break;
}
}
}
void IdentityGetAuthTokenFunction::OnMintTokenSuccess(
const std::string& access_token,
const std::set<std::string>& granted_scopes,
int time_to_live) {
TRACE_EVENT_NESTABLE_ASYNC_INSTANT0("identity", "OnMintTokenSuccess", this);
IdentityTokenCacheValue token = IdentityTokenCacheValue::CreateToken(
access_token, granted_scopes, base::Seconds(time_to_live));
IdentityAPI::GetFactoryInstance()
->Get(GetProfile())
->token_cache()
->SetToken(token_key_, token);
CompleteMintTokenFlow();
CompleteFunctionWithResult(access_token, granted_scopes);
}
void IdentityGetAuthTokenFunction::OnMintTokenFailure(
const GoogleServiceAuthError& error) {
TRACE_EVENT_NESTABLE_ASYNC_INSTANT1("identity", "OnMintTokenFailure", this,
"error", error.ToString());
CompleteMintTokenFlow();
switch (error.state()) {
case GoogleServiceAuthError::SERVICE_ERROR:
if (ShouldStartSigninFlow()) {
StartSigninFlow();
return;
}
break;
case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS:
// TODO(courage): flush ticket and retry once
if (ShouldStartSigninFlow()) {
StartSigninFlow();
return;
}
break;
default:
// Return error to caller.
break;
}
CompleteFunctionWithError(
IdentityGetAuthTokenError::FromMintTokenAuthError(error.ToString()));
}
void IdentityGetAuthTokenFunction::OnRemoteConsentSuccess(
const RemoteConsentResolutionData& resolution_data) {
TRACE_EVENT_NESTABLE_ASYNC_INSTANT0("identity", "OnRemoteConsentSuccess",
this);
IdentityAPI::GetFactoryInstance()
->Get(GetProfile())
->token_cache()
->SetToken(token_key_,
IdentityTokenCacheValue::CreateRemoteConsent(resolution_data));
should_prompt_for_signin_ = false;
resolution_data_ = resolution_data;
CompleteMintTokenFlow();
StartMintTokenFlow(IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE);
}
void IdentityGetAuthTokenFunction::OnRefreshTokenUpdatedForAccount(
const CoreAccountInfo& account_info) {
if (account_listening_mode_ != AccountListeningMode::kListeningTokens)
return;
// No specific account id was requested, use the first one we find.
if (token_key_.account_info.IsEmpty())
token_key_.account_info = account_info;
if (token_key_.account_info == account_info) {
// Stop listening tokens.
account_listening_mode_ = AccountListeningMode::kNotListening;
scoped_identity_manager_observation_.Reset();
StartMintTokenFlow(IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE);
}
}
bool IdentityGetAuthTokenFunction::TryRecoverFromServiceAuthError(
const GoogleServiceAuthError& error) {
// If this is really an authentication error and not just a transient
// network error, then we show signin UI if appropriate.
if (error.state() != GoogleServiceAuthError::CONNECTION_FAILED &&
error.state() != GoogleServiceAuthError::SERVICE_UNAVAILABLE) {
if (ShouldStartSigninFlow()) {
StartSigninFlow();
return true;
}
}
return false;
}
void IdentityGetAuthTokenFunction::OnPrimaryAccountChanged(
const signin::PrimaryAccountChangeEvent& event_details) {
if (event_details.GetEventTypeFor(signin::ConsentLevel::kSync) !=
signin::PrimaryAccountChangeEvent::Type::kSet)
return;
if (account_listening_mode_ != AccountListeningMode::kListeningPrimaryAccount)
return;
TRACE_EVENT_NESTABLE_ASYNC_INSTANT0("identity",
"OnPrimaryAccountChanged (set)", this);
const CoreAccountInfo& primary_account_info =
event_details.GetCurrentState().primary_account;
DCHECK(token_key_.account_info.IsEmpty());
token_key_.account_info = primary_account_info;
// Stop listening primary account.
DCHECK(IdentityManagerFactory::GetForProfile(GetProfile())
->HasAccountWithRefreshToken(primary_account_info.account_id));
account_listening_mode_ = AccountListeningMode::kNotListening;
scoped_identity_manager_observation_.Reset();
StartMintTokenFlow(IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE);
}
void IdentityGetAuthTokenFunction::SigninFailed() {
TRACE_EVENT_NESTABLE_ASYNC_INSTANT0("identity", "SigninFailed", this);
CompleteFunctionWithError(IdentityGetAuthTokenError(
IdentityGetAuthTokenError::State::kSignInFailed));
}
void IdentityGetAuthTokenFunction::OnGaiaRemoteConsentFlowFailed(
GaiaRemoteConsentFlow::Failure failure) {
CompleteMintTokenFlow();
IdentityGetAuthTokenError error;
switch (failure) {
case GaiaRemoteConsentFlow::WINDOW_CLOSED:
error = IdentityGetAuthTokenError(
IdentityGetAuthTokenError::State::kRemoteConsentFlowRejected);
break;
case GaiaRemoteConsentFlow::SET_ACCOUNTS_IN_COOKIE_FAILED:
error = IdentityGetAuthTokenError(
IdentityGetAuthTokenError::State::kSetAccountsInCookieFailure);
break;
case GaiaRemoteConsentFlow::LOAD_FAILED:
error = IdentityGetAuthTokenError(
IdentityGetAuthTokenError::State::kRemoteConsentPageLoadFailure);
break;
case GaiaRemoteConsentFlow::INVALID_CONSENT_RESULT:
error = IdentityGetAuthTokenError(
IdentityGetAuthTokenError::State::kInvalidConsentResult);
break;
case GaiaRemoteConsentFlow::NO_GRANT:
error =
IdentityGetAuthTokenError(IdentityGetAuthTokenError::State::kNoGrant);
break;
case GaiaRemoteConsentFlow::NONE:
NOTREACHED();
break;
}
CompleteFunctionWithError(error);
}
void IdentityGetAuthTokenFunction::OnGaiaRemoteConsentFlowApproved(
const std::string& consent_result,
const std::string& gaia_id) {
TRACE_EVENT_NESTABLE_ASYNC_INSTANT1(
"identity", "OnGaiaRemoteConsentFlowApproved", this, "gaia_id", gaia_id);
DCHECK(!consent_result.empty());
remote_consent_approved_ = true;
AccountInfo account = IdentityManagerFactory::GetForProfile(GetProfile())
->FindExtendedAccountInfoByGaiaId(gaia_id);
if (account.IsEmpty()) {
CompleteMintTokenFlow();
CompleteFunctionWithError(IdentityGetAuthTokenError(
IdentityGetAuthTokenError::State::kRemoteConsentUserNotSignedIn));
return;
}
if (IsPrimaryAccountOnly()) {
CoreAccountId primary_account_id =
IdentityManagerFactory::GetForProfile(GetProfile())
->GetPrimaryAccountId(signin::ConsentLevel::kSync);
if (primary_account_id != account.account_id) {
CompleteMintTokenFlow();
CompleteFunctionWithError(IdentityGetAuthTokenError(
IdentityGetAuthTokenError::State::kRemoteConsentUserNonPrimary));
return;
}
}
IdentityAPI* id_api = IdentityAPI::GetFactoryInstance()->Get(GetProfile());
id_api->SetGaiaIdForExtension(token_key_.extension_id, gaia_id);
// It's important to update the cache before calling CompleteMintTokenFlow()
// as this call may start a new request synchronously and query the cache.
ExtensionTokenKey new_token_key(token_key_);
new_token_key.account_info = account;
id_api->token_cache()->SetToken(
new_token_key,
IdentityTokenCacheValue::CreateRemoteConsentApproved(consent_result));
CompleteMintTokenFlow();
token_key_ = new_token_key;
consent_result_ = consent_result;
should_prompt_for_signin_ = false;
StartMintTokenFlow(IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE);
}
void IdentityGetAuthTokenFunction::OnGetAccessTokenComplete(
const absl::optional<std::string>& access_token,
base::Time expiration_time,
const GoogleServiceAuthError& error) {
// By the time we get here we should no longer have an outstanding access
// token request.
DCHECK(!device_access_token_request_);
DCHECK(!token_key_account_access_token_fetcher_);
if (access_token) {
TRACE_EVENT_NESTABLE_ASYNC_END1(
"identity", "GetAccessToken", this, "account",
token_key_.account_info.account_id.ToString());
StartGaiaRequest(access_token.value());
} else {
TRACE_EVENT_NESTABLE_ASYNC_END1("identity", "GetAccessToken", this, "error",
error.ToString());
CompleteMintTokenFlow();
if (TryRecoverFromServiceAuthError(error)) {
return;
}
CompleteFunctionWithError(
IdentityGetAuthTokenError::FromGetAccessTokenAuthError(
error.ToString()));
}
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
void IdentityGetAuthTokenFunction::OnGetTokenSuccess(
const OAuth2AccessTokenManager::Request* request,
const OAuth2AccessTokenConsumer::TokenResponse& token_response) {
device_access_token_request_.reset();
OnGetAccessTokenComplete(token_response.access_token,
token_response.expiration_time,
GoogleServiceAuthError::AuthErrorNone());
}
void IdentityGetAuthTokenFunction::OnGetTokenFailure(
const OAuth2AccessTokenManager::Request* request,
const GoogleServiceAuthError& error) {
device_access_token_request_.reset();
OnGetAccessTokenComplete(absl::nullopt, base::Time(), error);
}
#endif
void IdentityGetAuthTokenFunction::OnAccessTokenFetchCompleted(
GoogleServiceAuthError error,
signin::AccessTokenInfo access_token_info) {
token_key_account_access_token_fetcher_.reset();
if (error.state() == GoogleServiceAuthError::NONE) {
OnGetAccessTokenComplete(access_token_info.token,
access_token_info.expiration_time,
GoogleServiceAuthError::AuthErrorNone());
} else {
OnGetAccessTokenComplete(absl::nullopt, base::Time(), error);
}
}
void IdentityGetAuthTokenFunction::OnIdentityAPIShutdown() {
device_access_token_request_.reset();
token_key_account_access_token_fetcher_.reset();
scoped_identity_manager_observation_.Reset();
extensions::IdentityAPI::GetFactoryInstance()
->Get(GetProfile())
->mint_queue()
->RequestCancel(token_key_, this);
CompleteFunctionWithError(
IdentityGetAuthTokenError(IdentityGetAuthTokenError::State::kCanceled));
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
// Even though the DeviceOAuth2TokenService may be available on non-ChromeOS
// platforms, its robot account is not made available because it should only be
// used for very specific policy-related things. In fact, the device account on
// desktop isn't scoped for anything other than policy invalidations.
void IdentityGetAuthTokenFunction::StartDeviceAccessTokenRequest() {
DeviceOAuth2TokenService* service = DeviceOAuth2TokenServiceFactory::Get();
// Since robot account refresh tokens are scoped down to [any-api] only,
// request access token for [any-api] instead of login.
OAuth2AccessTokenManager::ScopeSet scopes;
scopes.insert(GaiaConstants::kAnyApiOAuth2Scope);
device_access_token_request_ = service->StartAccessTokenRequest(scopes, this);
}
#endif
void IdentityGetAuthTokenFunction::StartTokenKeyAccountAccessTokenRequest() {
TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("identity", "GetAccessToken", this);
auto* identity_manager = IdentityManagerFactory::GetForProfile(GetProfile());
#if BUILDFLAG(IS_CHROMEOS_ASH)
if (chrome::IsRunningInForcedAppMode()) {
std::string app_client_id;
std::string app_client_secret;
if (ash::UserSessionManager::GetInstance()->GetAppModeChromeClientOAuthInfo(
&app_client_id, &app_client_secret)) {
token_key_account_access_token_fetcher_ =
identity_manager->CreateAccessTokenFetcherForClient(
token_key_.account_info.account_id, app_client_id,
app_client_secret, kExtensionsIdentityAPIOAuthConsumerName,
signin::ScopeSet(),
base::BindOnce(
&IdentityGetAuthTokenFunction::OnAccessTokenFetchCompleted,
base::Unretained(this)),
signin::AccessTokenFetcher::Mode::kImmediate);
return;
}
}
#endif
token_key_account_access_token_fetcher_ =
identity_manager->CreateAccessTokenFetcherForAccount(
token_key_.account_info.account_id,
kExtensionsIdentityAPIOAuthConsumerName, signin::ScopeSet(),
base::BindOnce(
&IdentityGetAuthTokenFunction::OnAccessTokenFetchCompleted,
base::Unretained(this)),
signin::AccessTokenFetcher::Mode::kImmediate);
}
void IdentityGetAuthTokenFunction::StartGaiaRequest(
const std::string& login_access_token) {
DCHECK(!login_access_token.empty());
mint_token_flow_ = CreateMintTokenFlow();
mint_token_flow_->Start(GetProfile()->GetURLLoaderFactory(),
login_access_token);
}
void IdentityGetAuthTokenFunction::ShowExtensionLoginPrompt() {
const CoreAccountInfo& account = token_key_.account_info;
std::string email_hint =
account.IsEmpty() ? email_for_default_web_account_ : account.email;
signin_ui_util::ShowExtensionSigninPrompt(GetProfile(),
IsPrimaryAccountOnly(), email_hint);
}
void IdentityGetAuthTokenFunction::ShowRemoteConsentDialog(
const RemoteConsentResolutionData& resolution_data) {
gaia_remote_consent_flow_ = std::make_unique<GaiaRemoteConsentFlow>(
this, GetProfile(), token_key_, resolution_data);
gaia_remote_consent_flow_->Start();
}
std::unique_ptr<OAuth2MintTokenFlow>
IdentityGetAuthTokenFunction::CreateMintTokenFlow() {
std::string signin_scoped_device_id =
GetSigninScopedDeviceIdForProfile(GetProfile());
auto mint_token_flow = std::make_unique<OAuth2MintTokenFlow>(
this,
OAuth2MintTokenFlow::Parameters(
extension()->id(), oauth2_client_id_,
std::vector<std::string>(token_key_.scopes.begin(),
token_key_.scopes.end()),
enable_granular_permissions_, signin_scoped_device_id,
GetSelectedUserId(), consent_result_, GetOAuth2MintTokenFlowVersion(),
GetOAuth2MintTokenFlowChannel(), gaia_mint_token_mode_));
return mint_token_flow;
}
bool IdentityGetAuthTokenFunction::HasRefreshTokenForTokenKeyAccount() const {
auto* identity_manager = IdentityManagerFactory::GetForProfile(GetProfile());
return identity_manager->HasAccountWithRefreshToken(
token_key_.account_info.account_id);
}
std::string IdentityGetAuthTokenFunction::GetOAuth2ClientId() const {
DCHECK(extension());
const auto& oauth2_info = OAuth2ManifestHandler::GetOAuth2Info(*extension());
std::string client_id;
if (oauth2_info.client_id)
client_id = *oauth2_info.client_id;
// Component apps using auto_approve may use Chrome's client ID by
// omitting the field.
if (client_id.empty() &&
extension()->location() == mojom::ManifestLocation::kComponent &&
oauth2_info.auto_approve && *oauth2_info.auto_approve) {
client_id = GaiaUrls::GetInstance()->oauth2_chrome_client_id();
}
return client_id;
}
bool IdentityGetAuthTokenFunction::IsPrimaryAccountOnly() const {
return IdentityAPI::GetFactoryInstance()
->Get(GetProfile())
->AreExtensionsRestrictedToPrimaryAccount();
}
Profile* IdentityGetAuthTokenFunction::GetProfile() const {
return Profile::FromBrowserContext(browser_context());
}
bool IdentityGetAuthTokenFunction::enable_granular_permissions() const {
return enable_granular_permissions_;
}
std::string IdentityGetAuthTokenFunction::GetSelectedUserId() const {
if (selected_gaia_id_ == token_key_.account_info.gaia)
return selected_gaia_id_;
return "";
}
} // namespace extensions
| 13,737 |
927 |
<filename>MLPP/SoftmaxNet/SoftmaxNet.cpp
//
// SoftmaxNet.cpp
//
// Created by <NAME> on 10/2/20.
//
#include "SoftmaxNet.hpp"
#include "LinAlg/LinAlg.hpp"
#include "Data/Data.hpp"
#include "Regularization/Reg.hpp"
#include "Activation/Activation.hpp"
#include "Utilities/Utilities.hpp"
#include "Cost/Cost.hpp"
#include <iostream>
#include <random>
namespace MLPP{
SoftmaxNet::SoftmaxNet(std::vector<std::vector<double>> inputSet, std::vector<std::vector<double>> outputSet, int n_hidden, std::string reg, double lambda, double alpha)
: inputSet(inputSet), outputSet(outputSet), n(inputSet.size()), k(inputSet[0].size()), n_hidden(n_hidden), n_class(outputSet[0].size()), reg(reg), lambda(lambda), alpha(alpha)
{
y_hat.resize(n);
weights1 = Utilities::weightInitialization(k, n_hidden);
weights2 = Utilities::weightInitialization(n_hidden, n_class);
bias1 = Utilities::biasInitialization(n_hidden);
bias2 = Utilities::biasInitialization(n_class);
}
std::vector<double> SoftmaxNet::modelTest(std::vector<double> x){
return Evaluate(x);
}
std::vector<std::vector<double>> SoftmaxNet::modelSetTest(std::vector<std::vector<double>> X){
return Evaluate(X);
}
void SoftmaxNet::gradientDescent(double learning_rate, int max_epoch, bool UI){
Activation avn;
LinAlg alg;
Reg regularization;
double cost_prev = 0;
int epoch = 1;
forwardPass();
while(true){
cost_prev = Cost(y_hat, outputSet);
// Calculating the errors
std::vector<std::vector<double>> error = alg.subtraction(y_hat, outputSet);
// Calculating the weight/bias gradients for layer 2
std::vector<std::vector<double>> D2_1 = alg.matmult(alg.transpose(a2), error);
// weights and bias updation for layer 2
weights2 = alg.subtraction(weights2, alg.scalarMultiply(learning_rate, D2_1));
weights2 = regularization.regWeights(weights2, lambda, alpha, reg);
bias2 = alg.subtractMatrixRows(bias2, alg.scalarMultiply(learning_rate, error));
//Calculating the weight/bias for layer 1
std::vector<std::vector<double>> D1_1 = alg.matmult(error, alg.transpose(weights2));
std::vector<std::vector<double>> D1_2 = alg.hadamard_product(D1_1, avn.sigmoid(z2, 1));
std::vector<std::vector<double>> D1_3 = alg.matmult(alg.transpose(inputSet), D1_2);
// weight an bias updation for layer 1
weights1 = alg.subtraction(weights1, alg.scalarMultiply(learning_rate, D1_3));
weights1 = regularization.regWeights(weights1, lambda, alpha, reg);
bias1 = alg.subtractMatrixRows(bias1, alg.scalarMultiply(learning_rate, D1_2));
forwardPass();
// UI PORTION
if(UI) {
Utilities::CostInfo(epoch, cost_prev, Cost(y_hat, outputSet));
std::cout << "Layer 1:" << std::endl;
Utilities::UI(weights1, bias1);
std::cout << "Layer 2:" << std::endl;
Utilities::UI(weights2, bias2);
}
epoch++;
if(epoch > max_epoch) { break; }
}
}
void SoftmaxNet::SGD(double learning_rate, int max_epoch, bool UI){
Activation avn;
LinAlg alg;
Reg regularization;
double cost_prev = 0;
int epoch = 1;
while(true){
std::random_device rd;
std::default_random_engine generator(rd());
std::uniform_int_distribution<int> distribution(0, int(n - 1));
int outputIndex = distribution(generator);
std::vector<double> y_hat = Evaluate(inputSet[outputIndex]);
auto [z2, a2] = propagate(inputSet[outputIndex]);
cost_prev = Cost({y_hat}, {outputSet[outputIndex]});
std::vector<double> error = alg.subtraction(y_hat, outputSet[outputIndex]);
// Weight updation for layer 2
std::vector<std::vector<double>> D2_1 = alg.outerProduct(error, a2);
weights2 = alg.subtraction(weights2, alg.scalarMultiply(learning_rate, alg.transpose(D2_1)));
weights2 = regularization.regWeights(weights2, lambda, alpha, reg);
// Bias updation for layer 2
bias2 = alg.subtraction(bias2, alg.scalarMultiply(learning_rate, error));
// Weight updation for layer 1
std::vector<double> D1_1 = alg.mat_vec_mult(weights2, error);
std::vector<double> D1_2 = alg.hadamard_product(D1_1, avn.sigmoid(z2, 1));
std::vector<std::vector<double>> D1_3 = alg.outerProduct(inputSet[outputIndex], D1_2);
weights1 = alg.subtraction(weights1, alg.scalarMultiply(learning_rate, D1_3));
weights1 = regularization.regWeights(weights1, lambda, alpha, reg);
// Bias updation for layer 1
bias1 = alg.subtraction(bias1, alg.scalarMultiply(learning_rate, D1_2));
y_hat = Evaluate(inputSet[outputIndex]);
if(UI) {
Utilities::CostInfo(epoch, cost_prev, Cost({y_hat}, {outputSet[outputIndex]}));
std::cout << "Layer 1:" << std::endl;
Utilities::UI(weights1, bias1);
std::cout << "Layer 2:" << std::endl;
Utilities::UI(weights2, bias2);
}
epoch++;
if(epoch > max_epoch) { break; }
}
forwardPass();
}
void SoftmaxNet::MBGD(double learning_rate, int max_epoch, int mini_batch_size, bool UI){
Activation avn;
LinAlg alg;
Reg regularization;
double cost_prev = 0;
int epoch = 1;
// Creating the mini-batches
int n_mini_batch = n/mini_batch_size;
auto [inputMiniBatches, outputMiniBatches] = Utilities::createMiniBatches(inputSet, outputSet, n_mini_batch);
// Creating the mini-batches
for(int i = 0; i < n_mini_batch; i++){
std::vector<std::vector<double>> currentInputSet;
std::vector<std::vector<double>> currentOutputSet;
for(int j = 0; j < n/n_mini_batch; j++){
currentInputSet.push_back(inputSet[n/n_mini_batch * i + j]);
currentOutputSet.push_back(outputSet[n/n_mini_batch * i + j]);
}
inputMiniBatches.push_back(currentInputSet);
outputMiniBatches.push_back(currentOutputSet);
}
if(double(n)/double(n_mini_batch) - int(n/n_mini_batch) != 0){
for(int i = 0; i < n - n/n_mini_batch * n_mini_batch; i++){
inputMiniBatches[n_mini_batch - 1].push_back(inputSet[n/n_mini_batch * n_mini_batch + i]);
outputMiniBatches[n_mini_batch - 1].push_back(outputSet[n/n_mini_batch * n_mini_batch + i]);
}
}
while(true){
for(int i = 0; i < n_mini_batch; i++){
std::vector<std::vector<double>> y_hat = Evaluate(inputMiniBatches[i]);
auto [z2, a2] = propagate(inputMiniBatches[i]);
cost_prev = Cost(y_hat, outputMiniBatches[i]);
// Calculating the errors
std::vector<std::vector<double>> error = alg.subtraction(y_hat, outputMiniBatches[i]);
// Calculating the weight/bias gradients for layer 2
std::vector<std::vector<double>> D2_1 = alg.matmult(alg.transpose(a2), error);
// weights and bias updation for layser 2
weights2 = alg.subtraction(weights2, alg.scalarMultiply(learning_rate, D2_1));
weights2 = regularization.regWeights(weights2, lambda, alpha, reg);
// Bias Updation for layer 2
bias2 = alg.subtractMatrixRows(bias2, alg.scalarMultiply(learning_rate, error));
//Calculating the weight/bias for layer 1
std::vector<std::vector<double>> D1_1 = alg.matmult(error, alg.transpose(weights2));
std::vector<std::vector<double>> D1_2 = alg.hadamard_product(D1_1, avn.sigmoid(z2, 1));
std::vector<std::vector<double>> D1_3 = alg.matmult(alg.transpose(inputMiniBatches[i]), D1_2);
// weight an bias updation for layer 1
weights1 = alg.subtraction(weights1, alg.scalarMultiply(learning_rate, D1_3));
weights1 = regularization.regWeights(weights1, lambda, alpha, reg);
bias1 = alg.subtractMatrixRows(bias1, alg.scalarMultiply(learning_rate, D1_2));
y_hat = Evaluate(inputMiniBatches[i]);
if(UI) {
Utilities::CostInfo(epoch, cost_prev, Cost(y_hat, outputMiniBatches[i]));
std::cout << "Layer 1:" << std::endl;
Utilities::UI(weights1, bias1);
std::cout << "Layer 2:" << std::endl;
Utilities::UI(weights2, bias2);
}
}
epoch++;
if(epoch > max_epoch) { break; }
}
forwardPass();
}
double SoftmaxNet::score(){
Utilities util;
return util.performance(y_hat, outputSet);
}
void SoftmaxNet::save(std::string fileName){
Utilities util;
util.saveParameters(fileName, weights1, bias1, 0, 1);
util.saveParameters(fileName, weights2, bias2, 1, 2);
LinAlg alg;
}
std::vector<std::vector<double>> SoftmaxNet::getEmbeddings(){
return weights1;
}
double SoftmaxNet::Cost(std::vector<std::vector<double>> y_hat, std::vector<std::vector<double>> y){
Reg regularization;
Data data;
class Cost cost;
return cost.CrossEntropy(y_hat, y) + regularization.regTerm(weights1, lambda, alpha, reg) + regularization.regTerm(weights2, lambda, alpha, reg);
}
std::vector<std::vector<double>> SoftmaxNet::Evaluate(std::vector<std::vector<double>> X){
LinAlg alg;
Activation avn;
std::vector<std::vector<double>> z2 = alg.mat_vec_add(alg.matmult(X, weights1), bias1);
std::vector<std::vector<double>> a2 = avn.sigmoid(z2);
return avn.adjSoftmax(alg.mat_vec_add(alg.matmult(a2, weights2), bias2));
}
std::tuple<std::vector<std::vector<double>>, std::vector<std::vector<double>>> SoftmaxNet::propagate(std::vector<std::vector<double>> X){
LinAlg alg;
Activation avn;
std::vector<std::vector<double>> z2 = alg.mat_vec_add(alg.matmult(X, weights1), bias1);
std::vector<std::vector<double>> a2 = avn.sigmoid(z2);
return {z2, a2};
}
std::vector<double> SoftmaxNet::Evaluate(std::vector<double> x){
LinAlg alg;
Activation avn;
std::vector<double> z2 = alg.addition(alg.mat_vec_mult(alg.transpose(weights1), x), bias1);
std::vector<double> a2 = avn.sigmoid(z2);
return avn.adjSoftmax(alg.addition(alg.mat_vec_mult(alg.transpose(weights2), a2), bias2));
}
std::tuple<std::vector<double>, std::vector<double>> SoftmaxNet::propagate(std::vector<double> x){
LinAlg alg;
Activation avn;
std::vector<double> z2 = alg.addition(alg.mat_vec_mult(alg.transpose(weights1), x), bias1);
std::vector<double> a2 = avn.sigmoid(z2);
return {z2, a2};
}
void SoftmaxNet::forwardPass(){
LinAlg alg;
Activation avn;
z2 = alg.mat_vec_add(alg.matmult(inputSet, weights1), bias1);
a2 = avn.sigmoid(z2);
y_hat = avn.adjSoftmax(alg.mat_vec_add(alg.matmult(a2, weights2), bias2));
}
}
| 5,694 |
1,359 |
<reponame>caugner/phpinspectionsea<filename>src/test/java/com/kalessil/phpStorm/phpInspectionsEA/controlFlow/MultipleReturnStatementsInspectorTest.java
package com.kalessil.phpStorm.phpInspectionsEA.controlFlow;
import com.kalessil.phpStorm.phpInspectionsEA.PhpCodeInsightFixtureTestCase;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.codeStyle.MultipleReturnStatementsInspector;
final public class MultipleReturnStatementsInspectorTest extends PhpCodeInsightFixtureTestCase {
public void testIfFindsAllPatterns() {
final MultipleReturnStatementsInspector inspector = new MultipleReturnStatementsInspector();
inspector.COMPLAIN_THRESHOLD = 3;
inspector.SCREAM_THRESHOLD = 5;
myFixture.enableInspections(inspector);
myFixture.configureByFile("testData/fixtures/controlFlow/multiple-returns.php");
myFixture.testHighlighting(true, false, true);
}
}
| 369 |
716 |
<reponame>abrahamtovarmob/flang<filename>runtime/libpgmath/lib/generic/math_tables/mth_aintdefs.h
/*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*/
/******************************************************************************
* *
* Background: *
* The POWERPC ABI does not provide for tail calls. Thus, the math dispatch *
* table processing incurs overhead with the saving and restoration of GPR 2 *
* that can severely affect application performance. For POWERPC, we use an *
* optimized assembly dispatch set of routines that make tail calls to all of *
* the routines defined in the math dispatch configuration files but do not *
* saveand /restore GPR 2. *
* *
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! *
* *
* If any entry (routine <FUNC>) in any of the dispatch tables is not present *
* in i.e. not satisfied by, libpgmath, in order to properly preserve/restore*
* GRP 2 when calling routine <FUNC>, the actual function must first be *
* encapsulated in a routine present in libpgmath. *
* *
* No doubt there are pathological cases that will show this engineering *
* choice to be wrong, but current performance testing shows otherwise. *
* *
*****************************************************************************/
MTHINTRIN(aint , ss , any , __mth_i_aint , __mth_i_aint , __mth_i_aint ,__math_dispatch_error)
MTHINTRIN(aint , ds , any , __mth_i_dint , __mth_i_dint , __mth_i_dint ,__math_dispatch_error)
MTHINTRIN(aint , sv4 , any , __gs_aint_4_f , __gs_aint_4_r , __gs_aint_4_p ,__math_dispatch_error)
MTHINTRIN(aint , dv2 , any , __gd_aint_2_f , __gd_aint_2_r , __gd_aint_2_p ,__math_dispatch_error)
MTHINTRIN(aint , sv4m , any , __fs_aint_4_mn , __rs_aint_4_mn , __ps_aint_4_mn ,__math_dispatch_error)
MTHINTRIN(aint , dv2m , any , __fd_aint_2_mn , __rd_aint_2_mn , __pd_aint_2_mn ,__math_dispatch_error)
| 1,397 |
430 |
#include "Function.h"
#include "FunctionLocation.h"
/**
* Free the current function location and stack pad table
*/
Function::~Function() {
if(_current != NULL) {
_current->release();
}
if(_stackPad != NULL) {
getDataHeap()->free(_stackPad);
}
}
/**
* Copy the code and relocation table for this function. Use the pre-assembled
* code/table chunk if the function has already been relocated.
*
* \arg target The destination of the copy.
*/
void Function::copyTo(void* target) {
if(_current == NULL) {
// Copy the code from the original function
memcpy(target, _code.base(), _code.size());
// Patch in the saved header, since the original has been overwritten
*(FunctionHeader*)target = _savedHeader;
// If there is a stack pad table, move it to a random location
if(_stackPad != NULL) {
uintptr_t* table = (uintptr_t*)_table.base();
for(size_t i=0; i<_table.size(); i+=sizeof(uintptr_t)) {
if(table[i] == (uintptr_t)_stackPad) {
_stackPad = (uint8_t*)getDataHeap()->malloc(1);
table[i] = (uintptr_t)_stackPad;
}
}
}
// Copy the relocation table, if needed
if(_tableAdjacent) {
uint8_t* a = (uint8_t*)target;
memcpy(&a[_code.size()], _table.base(), _table.size());
}
} else {
memcpy(target, _current->_memory.base(), getAllocationSize());
}
}
/**
* Create a new FunctionLocation for this Function.
* \arg relocation The ID for the current relocation phase.
* \returns Whether or not a new location was created
*/
FunctionLocation* Function::relocate() {
FunctionLocation* oldLocation = _current;
_current = new FunctionLocation(this);
_current->activate();
// Fill the stack pad table with random bytes
if(_stackPad != NULL) {
// Update random stack pad
*_stackPad = getRandomByte();
}
return oldLocation;
}
| 829 |
315 |
<filename>encryption/enc_basic.py<gh_stars>100-1000
# MIT License
# Copyright (c) 2018 <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys
if "enc_basic.py" in sys.argv[0]:
print("[-] Instead of poking around just try: python xfltreat.py --help")
sys.exit(-1)
import os
import base64
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.exceptions import UnsupportedAlgorithm
import common
import Generic_encryption_module
class Encryption_module(Generic_encryption_module.Generic_encryption_module):
def __init__(self):
super(Encryption_module, self).__init__()
self.cmh_struct_encryption = {
# num : [string to look for, function, server(1) or client(0), return on success, return on failure]
# return value meanings: True - module continues
# False - module thread terminates
# in case of Stateless modules, the whole module terminates if the return value is False
0 : ["XFLT>ECDHd1", self.encryption_step_1, 1, True, False, True],
1 : ["XFLT>ECDHd2", self.encryption_step_2, 0, True, False, False],
2 : ["XFLT>ECDHd3", self.encryption_step_3, 1, True, False, True],
3 : ["XFLT>ECDHd4", self.encryption_step_4, 0, True, False, False],
4 : ["XFLT>ECDHd5", self.encryption_step_5, 1, True, False, True],
}
self.client_step_count = 2
self.server_step_count = 3
self.server_public_key_file = "misc/public_key.pem"
self.server_private_key_file = "misc/private_key.pem"
self.curve = ec.SECP256K1()
return
def encrypt(self, shared_key, plaintext):
# the nonce should be 16 bytes long random data, but because of the
# small message size, we just get 4bytes and use it 4 times (extend).
# This is ugly, makes the encryption more vulnerable, but if you need
# something strong, please use the enhanced encryption module.
nonce = os.urandom(4)
extended_nonce = nonce*4
algorithm = algorithms.ChaCha20(shared_key, extended_nonce)
cipher = Cipher(algorithm, mode=None, backend=default_backend())
encryptor = cipher.encryptor()
return nonce+encryptor.update(plaintext)
def decrypt(self, shared_key, ciphertext):
# the nonce should be 16 bytes long random data, but because of the
# small message size, we just get 4bytes and use it 4 times (extend).
# This is ugly, makes the encryption more vulnerable, but if you need
# something strong, please use the enhanced encryption module.
nonce = ciphertext[0:4]
extended_nonce = nonce*4
algorithm = algorithms.ChaCha20(shared_key, extended_nonce)
cipher = Cipher(algorithm, mode=None, backend=default_backend())
decryptor = cipher.decryptor()
return decryptor.update(ciphertext[4:])
# server side.
# Sending the pre-generated public key from the file to the client for
# verification purposes + key exchange
def encryption_step_1(self, module, message, additional_data, cm):
common.internal_print("Encryption initialization started: {0}".format(module.module_name))
pbk = self.server_public_key.public_numbers().encode_point()[1:]
module.send(common.CONTROL_CHANNEL_BYTE, self.cmh_struct_encryption[1][0]+pbk, module.modify_additional_data(additional_data, 1))
return module.cmh_struct[cm][3]
# client side.
# Server public key received. Checking if it is known by the client.
# Generating a public/private key pair and sending back the public key to
# the client. Shared key derived from the public key and saved.
# Encryption is on from this point, shared key is used.
def encryption_step_2(self, module, message, additional_data, cm):
server_public_key_stream = message[len(self.cmh_struct_encryption[1][0]):]
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
digest.update(server_public_key_stream)
pubkey_hash = base64.b64encode(digest.finalize())
ip = module.config.get("Global", "remoteserverip")
fingerprint = self.check_fingerprint(ip, pubkey_hash)
if fingerprint == 2:
# text was shamelessly copied from OpenSSH
common.internal_print("The authenticity of host '{0}' can't be established.".format(ip), 1)
common.internal_print("Server's key fingerprint is SHA256: {0}".format(base64.b64encode(pubkey_hash)), 1)
answer = ""
while (answer != "yes") and (answer != "no"):
answer = raw_input("Are you sure you want to continue connecting? (yes/no) ")
if answer == "yes":
if not self.add_fingerprint(ip, pubkey_hash):
common.internal_print("Error opening known_hosts file.", -1)
return module.cmh_struct[cm][4+module.is_caller_stateless()]
else:
common.internal_print("Exiting...", -1)
return module.cmh_struct[cm][4+module.is_caller_stateless()]
if fingerprint == 1:
common.internal_print("The fingerprint has changed for the server. If you don't trust this network,\nthis can be a Man-in-The-Middle attack!", -1)
common.internal_print("Exiting...", -1)
return module.cmh_struct[cm][4+module.is_caller_stateless()]
try:
public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+server_public_key_stream)
except:
common.internal_print("Erroneous key received from the server. Are you sure you are using the same settings on both sides?", -1)
return module.cmh_struct[cm][4+module.is_caller_stateless()]
server_public_key = public_numbers.public_key(default_backend())
client_private_key = ec.generate_private_key(self.curve, default_backend())
module.encryption.set_shared_key(client_private_key.exchange(ec.ECDH(), server_public_key))
pbk = client_private_key.public_key().public_numbers().encode_point()[1:]
module.send(common.CONTROL_CHANNEL_BYTE, self.cmh_struct_encryption[2][0]+pbk, module.modify_additional_data(additional_data, 0))
module.encryption.set_encrypted(True)
return module.cmh_struct[cm][3]
# server side.
# Client's public key received, key exchanged.
# A new ephemeral key pair is generated, public key is sent to the client.
# This is to use a new, disposable key for every session
def encryption_step_3(self, module, message, additional_data, cm):
client_public_key_stream = message[len(self.cmh_struct_encryption[2][0]):]
try:
public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+client_public_key_stream)
except:
common.internal_print("Erroneous key received from the client. Are you sure you are using the same settings on both sides?", -1)
return module.cmh_struct[cm][4+module.is_caller_stateless()]
client_public_key = public_numbers.public_key(default_backend())
c = module.lookup_client_pub(additional_data)
c.get_encryption().set_shared_key(self.server_private_key.exchange(ec.ECDH(), client_public_key))
server_ephemeral_private_key = ec.generate_private_key(self.curve, default_backend())
server_ephemeral_public_key = server_ephemeral_private_key.public_key()
# no need to save, but who knows?!
c.get_encryption().set_private_key(server_ephemeral_private_key)
c.get_encryption().set_public_key(server_ephemeral_public_key)
c.get_encryption().set_encrypted(True)
pbk = server_ephemeral_public_key.public_numbers().encode_point()[1:]
module.send(common.CONTROL_CHANNEL_BYTE, self.cmh_struct_encryption[3][0]+pbk, module.modify_additional_data(additional_data, 1))
return module.cmh_struct[cm][3]
# client side.
# Server's ephemeral receveid, client generates an ephemeral keypair as
# well. Client sends its ephemeral's public key to the server.
# Since this is the last client side function called, we invoke the
# next step that is most probably the authentication, defined in the
# post_encryption_client() function.
def encryption_step_4(self, module, message, additional_data, cm):
server_ephemeral_public_key_stream = message[len(self.cmh_struct_encryption[3][0]):]
try:
public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+server_ephemeral_public_key_stream)
except:
common.internal_print("Erroneous key received from the server. Are you sure you are using the same settings on both sides?", -1)
return module.cmh_struct[cm][4+module.is_caller_stateless()]
server_ephemeral_public_key = public_numbers.public_key(default_backend())
client_ephemeral_private_key = ec.generate_private_key(self.curve, default_backend())
client_ephemeral_public_key = client_ephemeral_private_key.public_key()
module.encryption.set_private_key(client_ephemeral_private_key)
module.encryption.set_public_key(client_ephemeral_public_key)
pbk = client_ephemeral_public_key.public_numbers().encode_point()[1:]
module.send(common.CONTROL_CHANNEL_BYTE, self.cmh_struct_encryption[4][0]+pbk, module.modify_additional_data(additional_data, 0))
module.encryption.set_shared_key(client_ephemeral_private_key.exchange(ec.ECDH(), server_ephemeral_public_key))
module.post_encryption_client(message[len(self.cmh_struct_encryption[3][0]):], additional_data)
common.internal_print("Encryption key agreed with the server.", 1)
return module.cmh_struct[cm][3]
# server side.
# Client's ephemeral public key received. Key exchanged and saved.
def encryption_step_5(self, module, message, additional_data, cm):
client_ephemeral_public = message[len(self.cmh_struct_encryption[4][0]):]
c = module.lookup_client_pub(additional_data)
try:
public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+client_ephemeral_public)
except:
common.internal_print("Erroneous key received from the client. Are you sure you are using the same settings on both sides?", -1)
return module.cmh_struct[cm][4+module.is_caller_stateless()]
client_ephemeral_public_key = public_numbers.public_key(default_backend())
server_ephemeral_private_key = c.get_encryption().get_private_key()
c.get_encryption().set_shared_key(server_ephemeral_private_key.exchange(ec.ECDH(), client_ephemeral_public_key))
module.post_encryption_server(message[len(self.cmh_struct_encryption[4][0]):], additional_data)
common.internal_print("Encryption key agreed with the client.", 1)
return module.cmh_struct[cm][3]
# checking for the key file values in the config
def sanity_check(self, config):
if config.has_option("Encryption", "public_key"):
self.public_key_file = config.get("Encryption", "public_key")
if config.has_option("Encryption", "private_key"):
self.private_key_file = config.get("Encryption", "private_key")
return True
# initializing the module.
# client mode:
# - nothing to do
# server mode:
# - checking if the public and private key exists (server mode)
# - reading the files into memory
# - parsing the keys
def init(self, config, servermode):
try:
extended_nonce = os.urandom(4)*4
algorithm = algorithms.ChaCha20("0"*32, extended_nonce)
cipher = Cipher(algorithm, mode=None, backend=default_backend())
decryptor = cipher.decryptor()
except UnsupportedAlgorithm:
common.internal_print("OpenSSL library is outdated. Please update.", -1)
return False
except:
common.internal_print("Something went wrong with the cryptography engine. Most probably OpenSSL related.", -1)
return False
if servermode:
if not (os.path.exists(self.server_public_key_file) or os.path.exists(self.server_private_key_file)):
common.internal_print("Both public and private key is missing. This must be the first run. Generating keys...", 1)
private_key = ec.generate_private_key(self.curve, default_backend())
privkey_ser = private_key.private_bytes(serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
serialization.NoEncryption())
pubkey_ser = private_key.public_key().public_bytes(serialization.Encoding.PEM,
serialization.PublicFormat.SubjectPublicKeyInfo)
p = open(self.server_public_key_file, "w+")
p.write(pubkey_ser)
p.close()
oldmask = os.umask(0366)
p = open(self.server_private_key_file, "w+")
p.write(privkey_ser)
p.close()
os.umask(oldmask)
if not (os.path.exists(self.server_public_key_file) and os.path.exists(self.server_private_key_file)):
common.internal_print("Private or public key does not exist. Please make sure you have both or delete the existing one.", -1)
return False
# load keys from files
f = open(self.server_private_key_file, "r")
serialized_private = f.read()
f.close()
f = open(self.server_public_key_file, "r")
serialized_public = f.read()
f.close()
# load private and public keys from files
try:
self.server_public_key = serialization.load_pem_public_key(serialized_public, backend=default_backend())
except:
common.internal_print("Error parsing '{0}' as a public key.".format(self.server_public_key_file), -1)
return False
try:
self.server_private_key = serialization.load_pem_private_key(serialized_private, password=None, backend=default_backend())
except:
common.internal_print("Error parsing '{0}' as a private key.".format(self.server_private_key_file), -1)
return False
return True
else:
return True
return False
| 5,060 |
451 |
// File Automatically generated by eLiSe
#include "general/all.h"
#include "private/all.h"
#include "cEqResiduIm1DCBrownId.h"
cEqResiduIm1DCBrownId::cEqResiduIm1DCBrownId():
cElCompiledFonc(1)
{
AddIntRef (cIncIntervale("Intr1",0,17));
AddIntRef (cIncIntervale("Or1",17,23));
AddIntRef (cIncIntervale("Or2",23,29));
Close(false);
}
void cEqResiduIm1DCBrownId::ComputeVal()
{
double tmp0_ = mLocYL1*mLocYL1;
double tmp1_ = mLocXL1*mLocXL1;
double tmp2_ = tmp1_*tmp0_;
double tmp3_ = mCompCoord[17];
double tmp4_ = sin(tmp3_);
double tmp5_ = mCompCoord[18];
double tmp6_ = mCompCoord[19];
double tmp7_ = mLocXL1*mLocYL1;
double tmp8_ = tmp1_*mLocYL1;
double tmp9_ = mLocXL1*tmp0_;
double tmp10_ = mCompCoord[15];
double tmp11_ = mCompCoord[16];
double tmp12_ = tmp1_+tmp0_;
double tmp13_ = mCompCoord[0];
double tmp14_ = cos(tmp3_);
double tmp15_ = sin(tmp6_);
double tmp16_ = sin(tmp5_);
double tmp17_ = -(tmp16_);
double tmp18_ = tmp4_*tmp17_;
double tmp19_ = cos(tmp6_);
double tmp20_ = mCompCoord[3];
double tmp21_ = 1+tmp20_;
double tmp22_ = mCompCoord[4];
double tmp23_ = mCompCoord[5];
double tmp24_ = mCompCoord[6];
double tmp25_ = mCompCoord[7];
double tmp26_ = mCompCoord[8];
double tmp27_ = mLocYL2*mLocYL2;
double tmp28_ = mCompCoord[9];
double tmp29_ = mLocXL2*mLocXL2;
double tmp30_ = tmp29_*tmp27_;
double tmp31_ = mCompCoord[1];
double tmp32_ = mCompCoord[24];
double tmp33_ = mCompCoord[10];
double tmp34_ = mLocXL2*mLocYL2;
double tmp35_ = mCompCoord[11];
double tmp36_ = mCompCoord[12];
double tmp37_ = tmp29_*mLocYL2;
double tmp38_ = mCompCoord[13];
double tmp39_ = mLocXL2*tmp27_;
double tmp40_ = mCompCoord[14];
double tmp41_ = tmp29_+tmp27_;
double tmp42_ = mCompCoord[2];
double tmp43_ = cos(tmp32_);
double tmp44_ = mCompCoord[25];
double tmp45_ = (tmp21_)*mLocXL1;
double tmp46_ = tmp22_*mLocYL1;
double tmp47_ = tmp45_+tmp46_;
double tmp48_ = tmp23_*tmp7_;
double tmp49_ = tmp47_+tmp48_;
double tmp50_ = tmp24_*tmp0_;
double tmp51_ = tmp49_+tmp50_;
double tmp52_ = tmp25_*tmp8_;
double tmp53_ = tmp51_+tmp52_;
double tmp54_ = tmp26_*tmp9_;
double tmp55_ = tmp53_+tmp54_;
double tmp56_ = tmp28_*tmp2_;
double tmp57_ = tmp55_+tmp56_;
double tmp58_ = mLocXL1/mLocDCBrown_State_0_0;
double tmp59_ = tmp10_*(tmp58_);
double tmp60_ = tmp59_*tmp2_;
double tmp61_ = tmp57_+tmp60_;
double tmp62_ = tmp11_*mLocXL1;
double tmp63_ = tmp62_*(tmp12_);
double tmp64_ = tmp61_+tmp63_;
double tmp65_ = (tmp64_)-tmp31_;
double tmp66_ = (tmp65_)/tmp13_;
double tmp67_ = cos(tmp5_);
double tmp68_ = tmp33_*tmp7_;
double tmp69_ = mLocYL1+tmp68_;
double tmp70_ = tmp35_*tmp1_;
double tmp71_ = tmp69_+tmp70_;
double tmp72_ = tmp36_*tmp8_;
double tmp73_ = tmp71_+tmp72_;
double tmp74_ = tmp38_*tmp9_;
double tmp75_ = tmp73_+tmp74_;
double tmp76_ = tmp40_*tmp2_;
double tmp77_ = tmp75_+tmp76_;
double tmp78_ = mLocYL1/mLocDCBrown_State_0_0;
double tmp79_ = tmp10_*(tmp78_);
double tmp80_ = tmp79_*tmp2_;
double tmp81_ = tmp77_+tmp80_;
double tmp82_ = tmp11_*mLocYL1;
double tmp83_ = tmp82_*(tmp12_);
double tmp84_ = tmp81_+tmp83_;
double tmp85_ = (tmp84_)-tmp42_;
double tmp86_ = (tmp85_)/tmp13_;
double tmp87_ = (tmp21_)*mLocXL2;
double tmp88_ = tmp22_*mLocYL2;
double tmp89_ = tmp87_+tmp88_;
double tmp90_ = tmp23_*tmp34_;
double tmp91_ = tmp89_+tmp90_;
double tmp92_ = tmp24_*tmp27_;
double tmp93_ = tmp91_+tmp92_;
double tmp94_ = tmp25_*tmp37_;
double tmp95_ = tmp93_+tmp94_;
double tmp96_ = tmp26_*tmp39_;
double tmp97_ = tmp95_+tmp96_;
double tmp98_ = tmp28_*tmp30_;
double tmp99_ = tmp97_+tmp98_;
double tmp100_ = mLocXL2/mLocDCBrown_State_0_1;
double tmp101_ = tmp10_*(tmp100_);
double tmp102_ = tmp101_*tmp30_;
double tmp103_ = tmp99_+tmp102_;
double tmp104_ = tmp11_*mLocXL2;
double tmp105_ = tmp104_*(tmp41_);
double tmp106_ = tmp103_+tmp105_;
double tmp107_ = (tmp106_)-tmp31_;
double tmp108_ = (tmp107_)/tmp13_;
double tmp109_ = mCompCoord[23];
double tmp110_ = cos(tmp44_);
double tmp111_ = sin(tmp109_);
double tmp112_ = sin(tmp32_);
double tmp113_ = sin(tmp44_);
double tmp114_ = tmp33_*tmp34_;
double tmp115_ = mLocYL2+tmp114_;
double tmp116_ = tmp35_*tmp29_;
double tmp117_ = tmp115_+tmp116_;
double tmp118_ = tmp36_*tmp37_;
double tmp119_ = tmp117_+tmp118_;
double tmp120_ = tmp38_*tmp39_;
double tmp121_ = tmp119_+tmp120_;
double tmp122_ = tmp40_*tmp30_;
double tmp123_ = tmp121_+tmp122_;
double tmp124_ = mLocYL2/mLocDCBrown_State_0_1;
double tmp125_ = tmp10_*(tmp124_);
double tmp126_ = tmp125_*tmp30_;
double tmp127_ = tmp123_+tmp126_;
double tmp128_ = tmp11_*mLocYL2;
double tmp129_ = tmp128_*(tmp41_);
double tmp130_ = tmp127_+tmp129_;
double tmp131_ = (tmp130_)-tmp42_;
double tmp132_ = (tmp131_)/tmp13_;
double tmp133_ = cos(tmp109_);
double tmp134_ = -(tmp112_);
double tmp135_ = tmp111_*tmp134_;
double tmp136_ = tmp4_*tmp67_;
double tmp137_ = tmp136_*(tmp66_);
double tmp138_ = tmp14_*tmp19_;
double tmp139_ = tmp18_*tmp15_;
double tmp140_ = tmp138_+tmp139_;
double tmp141_ = (tmp140_)*(tmp86_);
double tmp142_ = tmp137_+tmp141_;
double tmp143_ = -(tmp15_);
double tmp144_ = tmp14_*tmp143_;
double tmp145_ = tmp18_*tmp19_;
double tmp146_ = tmp144_+tmp145_;
double tmp147_ = tmp142_+tmp146_;
double tmp148_ = tmp112_*(tmp108_);
double tmp149_ = tmp43_*tmp113_;
double tmp150_ = tmp149_*(tmp132_);
double tmp151_ = tmp148_+tmp150_;
double tmp152_ = tmp43_*tmp110_;
double tmp153_ = tmp151_+tmp152_;
double tmp154_ = (tmp147_)*(tmp153_);
double tmp155_ = tmp16_*(tmp66_);
double tmp156_ = tmp67_*tmp15_;
double tmp157_ = tmp156_*(tmp86_);
double tmp158_ = tmp155_+tmp157_;
double tmp159_ = tmp67_*tmp19_;
double tmp160_ = tmp158_+tmp159_;
double tmp161_ = tmp111_*tmp43_;
double tmp162_ = tmp161_*(tmp108_);
double tmp163_ = tmp133_*tmp110_;
double tmp164_ = tmp135_*tmp113_;
double tmp165_ = tmp163_+tmp164_;
double tmp166_ = (tmp165_)*(tmp132_);
double tmp167_ = tmp162_+tmp166_;
double tmp168_ = -(tmp113_);
double tmp169_ = tmp133_*tmp168_;
double tmp170_ = tmp135_*tmp110_;
double tmp171_ = tmp169_+tmp170_;
double tmp172_ = tmp167_+tmp171_;
double tmp173_ = (tmp160_)*(tmp172_);
double tmp174_ = tmp154_-tmp173_;
double tmp175_ = -(tmp111_);
double tmp176_ = tmp133_*tmp134_;
double tmp177_ = -(tmp4_);
double tmp178_ = tmp14_*tmp17_;
double tmp179_ = tmp133_*tmp43_;
double tmp180_ = tmp179_*(tmp108_);
double tmp181_ = tmp175_*tmp110_;
double tmp182_ = tmp176_*tmp113_;
double tmp183_ = tmp181_+tmp182_;
double tmp184_ = (tmp183_)*(tmp132_);
double tmp185_ = tmp180_+tmp184_;
double tmp186_ = tmp175_*tmp168_;
double tmp187_ = tmp176_*tmp110_;
double tmp188_ = tmp186_+tmp187_;
double tmp189_ = tmp185_+tmp188_;
double tmp190_ = (tmp160_)*(tmp189_);
double tmp191_ = tmp14_*tmp67_;
double tmp192_ = tmp191_*(tmp66_);
double tmp193_ = tmp177_*tmp19_;
double tmp194_ = tmp178_*tmp15_;
double tmp195_ = tmp193_+tmp194_;
double tmp196_ = (tmp195_)*(tmp86_);
double tmp197_ = tmp192_+tmp196_;
double tmp198_ = tmp177_*tmp143_;
double tmp199_ = tmp178_*tmp19_;
double tmp200_ = tmp198_+tmp199_;
double tmp201_ = tmp197_+tmp200_;
double tmp202_ = (tmp201_)*(tmp153_);
double tmp203_ = tmp190_-tmp202_;
double tmp204_ = (tmp201_)*(tmp172_);
double tmp205_ = (tmp147_)*(tmp189_);
double tmp206_ = tmp204_-tmp205_;
double tmp207_ = mCompCoord[28];
double tmp208_ = mCompCoord[22];
double tmp209_ = tmp207_-tmp208_;
double tmp210_ = mCompCoord[26];
double tmp211_ = mCompCoord[20];
double tmp212_ = tmp210_-tmp211_;
double tmp213_ = mCompCoord[27];
double tmp214_ = mCompCoord[21];
double tmp215_ = tmp213_-tmp214_;
double tmp216_ = (tmp215_)*(tmp153_);
double tmp217_ = (tmp209_)*(tmp172_);
double tmp218_ = tmp216_-tmp217_;
double tmp219_ = (tmp209_)*(tmp189_);
double tmp220_ = (tmp212_)*(tmp153_);
double tmp221_ = tmp219_-tmp220_;
double tmp222_ = (tmp212_)*(tmp172_);
double tmp223_ = (tmp215_)*(tmp189_);
double tmp224_ = tmp222_-tmp223_;
mVal[0] = (sqrt((tmp174_)*(tmp174_)+(tmp203_)*(tmp203_)+(tmp206_)*(tmp206_))/sqrt((tmp201_)*(tmp201_)+(tmp147_)*(tmp147_)+(tmp160_)*(tmp160_)))*(((tmp218_)*(tmp201_)+(tmp221_)*(tmp147_)+(tmp224_)*(tmp160_))/((tmp218_)*(tmp174_)+(tmp221_)*(tmp203_)+(tmp224_)*(tmp206_)));
}
void cEqResiduIm1DCBrownId::ComputeValDeriv()
{
double tmp0_ = mLocYL1*mLocYL1;
double tmp1_ = mLocXL1*mLocXL1;
double tmp2_ = tmp1_*tmp0_;
double tmp3_ = mCompCoord[17];
double tmp4_ = sin(tmp3_);
double tmp5_ = mCompCoord[18];
double tmp6_ = mCompCoord[19];
double tmp7_ = mLocXL1*mLocYL1;
double tmp8_ = tmp1_*mLocYL1;
double tmp9_ = mLocXL1*tmp0_;
double tmp10_ = mCompCoord[15];
double tmp11_ = mCompCoord[16];
double tmp12_ = tmp1_+tmp0_;
double tmp13_ = mCompCoord[0];
double tmp14_ = cos(tmp3_);
double tmp15_ = sin(tmp6_);
double tmp16_ = sin(tmp5_);
double tmp17_ = -(tmp16_);
double tmp18_ = tmp4_*tmp17_;
double tmp19_ = cos(tmp6_);
double tmp20_ = mCompCoord[3];
double tmp21_ = 1+tmp20_;
double tmp22_ = mCompCoord[4];
double tmp23_ = mCompCoord[5];
double tmp24_ = mCompCoord[6];
double tmp25_ = mCompCoord[7];
double tmp26_ = mCompCoord[8];
double tmp27_ = mLocYL2*mLocYL2;
double tmp28_ = mCompCoord[9];
double tmp29_ = mLocXL2*mLocXL2;
double tmp30_ = tmp29_*tmp27_;
double tmp31_ = mCompCoord[1];
double tmp32_ = mCompCoord[24];
double tmp33_ = mCompCoord[10];
double tmp34_ = mLocXL2*mLocYL2;
double tmp35_ = mCompCoord[11];
double tmp36_ = mCompCoord[12];
double tmp37_ = tmp29_*mLocYL2;
double tmp38_ = mCompCoord[13];
double tmp39_ = mLocXL2*tmp27_;
double tmp40_ = mCompCoord[14];
double tmp41_ = tmp29_+tmp27_;
double tmp42_ = mCompCoord[2];
double tmp43_ = cos(tmp32_);
double tmp44_ = mCompCoord[25];
double tmp45_ = (tmp21_)*mLocXL1;
double tmp46_ = tmp22_*mLocYL1;
double tmp47_ = tmp45_+tmp46_;
double tmp48_ = tmp23_*tmp7_;
double tmp49_ = tmp47_+tmp48_;
double tmp50_ = tmp24_*tmp0_;
double tmp51_ = tmp49_+tmp50_;
double tmp52_ = tmp25_*tmp8_;
double tmp53_ = tmp51_+tmp52_;
double tmp54_ = tmp26_*tmp9_;
double tmp55_ = tmp53_+tmp54_;
double tmp56_ = tmp28_*tmp2_;
double tmp57_ = tmp55_+tmp56_;
double tmp58_ = mLocXL1/mLocDCBrown_State_0_0;
double tmp59_ = tmp10_*(tmp58_);
double tmp60_ = tmp59_*tmp2_;
double tmp61_ = tmp57_+tmp60_;
double tmp62_ = tmp11_*mLocXL1;
double tmp63_ = tmp62_*(tmp12_);
double tmp64_ = tmp61_+tmp63_;
double tmp65_ = (tmp64_)-tmp31_;
double tmp66_ = (tmp65_)/tmp13_;
double tmp67_ = cos(tmp5_);
double tmp68_ = tmp33_*tmp7_;
double tmp69_ = mLocYL1+tmp68_;
double tmp70_ = tmp35_*tmp1_;
double tmp71_ = tmp69_+tmp70_;
double tmp72_ = tmp36_*tmp8_;
double tmp73_ = tmp71_+tmp72_;
double tmp74_ = tmp38_*tmp9_;
double tmp75_ = tmp73_+tmp74_;
double tmp76_ = tmp40_*tmp2_;
double tmp77_ = tmp75_+tmp76_;
double tmp78_ = mLocYL1/mLocDCBrown_State_0_0;
double tmp79_ = tmp10_*(tmp78_);
double tmp80_ = tmp79_*tmp2_;
double tmp81_ = tmp77_+tmp80_;
double tmp82_ = tmp11_*mLocYL1;
double tmp83_ = tmp82_*(tmp12_);
double tmp84_ = tmp81_+tmp83_;
double tmp85_ = (tmp84_)-tmp42_;
double tmp86_ = (tmp85_)/tmp13_;
double tmp87_ = (tmp21_)*mLocXL2;
double tmp88_ = tmp22_*mLocYL2;
double tmp89_ = tmp87_+tmp88_;
double tmp90_ = tmp23_*tmp34_;
double tmp91_ = tmp89_+tmp90_;
double tmp92_ = tmp24_*tmp27_;
double tmp93_ = tmp91_+tmp92_;
double tmp94_ = tmp25_*tmp37_;
double tmp95_ = tmp93_+tmp94_;
double tmp96_ = tmp26_*tmp39_;
double tmp97_ = tmp95_+tmp96_;
double tmp98_ = tmp28_*tmp30_;
double tmp99_ = tmp97_+tmp98_;
double tmp100_ = mLocXL2/mLocDCBrown_State_0_1;
double tmp101_ = tmp10_*(tmp100_);
double tmp102_ = tmp101_*tmp30_;
double tmp103_ = tmp99_+tmp102_;
double tmp104_ = tmp11_*mLocXL2;
double tmp105_ = tmp104_*(tmp41_);
double tmp106_ = tmp103_+tmp105_;
double tmp107_ = (tmp106_)-tmp31_;
double tmp108_ = (tmp107_)/tmp13_;
double tmp109_ = mCompCoord[23];
double tmp110_ = cos(tmp44_);
double tmp111_ = sin(tmp109_);
double tmp112_ = sin(tmp32_);
double tmp113_ = sin(tmp44_);
double tmp114_ = tmp33_*tmp34_;
double tmp115_ = mLocYL2+tmp114_;
double tmp116_ = tmp35_*tmp29_;
double tmp117_ = tmp115_+tmp116_;
double tmp118_ = tmp36_*tmp37_;
double tmp119_ = tmp117_+tmp118_;
double tmp120_ = tmp38_*tmp39_;
double tmp121_ = tmp119_+tmp120_;
double tmp122_ = tmp40_*tmp30_;
double tmp123_ = tmp121_+tmp122_;
double tmp124_ = mLocYL2/mLocDCBrown_State_0_1;
double tmp125_ = tmp10_*(tmp124_);
double tmp126_ = tmp125_*tmp30_;
double tmp127_ = tmp123_+tmp126_;
double tmp128_ = tmp11_*mLocYL2;
double tmp129_ = tmp128_*(tmp41_);
double tmp130_ = tmp127_+tmp129_;
double tmp131_ = (tmp130_)-tmp42_;
double tmp132_ = (tmp131_)/tmp13_;
double tmp133_ = cos(tmp109_);
double tmp134_ = -(tmp112_);
double tmp135_ = tmp111_*tmp134_;
double tmp136_ = tmp4_*tmp67_;
double tmp137_ = tmp136_*(tmp66_);
double tmp138_ = tmp14_*tmp19_;
double tmp139_ = tmp18_*tmp15_;
double tmp140_ = tmp138_+tmp139_;
double tmp141_ = (tmp140_)*(tmp86_);
double tmp142_ = tmp137_+tmp141_;
double tmp143_ = -(tmp15_);
double tmp144_ = tmp14_*tmp143_;
double tmp145_ = tmp18_*tmp19_;
double tmp146_ = tmp144_+tmp145_;
double tmp147_ = tmp142_+tmp146_;
double tmp148_ = tmp112_*(tmp108_);
double tmp149_ = tmp43_*tmp113_;
double tmp150_ = tmp149_*(tmp132_);
double tmp151_ = tmp148_+tmp150_;
double tmp152_ = tmp43_*tmp110_;
double tmp153_ = tmp151_+tmp152_;
double tmp154_ = (tmp147_)*(tmp153_);
double tmp155_ = tmp16_*(tmp66_);
double tmp156_ = tmp67_*tmp15_;
double tmp157_ = tmp156_*(tmp86_);
double tmp158_ = tmp155_+tmp157_;
double tmp159_ = tmp67_*tmp19_;
double tmp160_ = tmp158_+tmp159_;
double tmp161_ = tmp111_*tmp43_;
double tmp162_ = tmp161_*(tmp108_);
double tmp163_ = tmp133_*tmp110_;
double tmp164_ = tmp135_*tmp113_;
double tmp165_ = tmp163_+tmp164_;
double tmp166_ = (tmp165_)*(tmp132_);
double tmp167_ = tmp162_+tmp166_;
double tmp168_ = -(tmp113_);
double tmp169_ = tmp133_*tmp168_;
double tmp170_ = tmp135_*tmp110_;
double tmp171_ = tmp169_+tmp170_;
double tmp172_ = tmp167_+tmp171_;
double tmp173_ = (tmp160_)*(tmp172_);
double tmp174_ = tmp154_-tmp173_;
double tmp175_ = -(tmp111_);
double tmp176_ = tmp133_*tmp134_;
double tmp177_ = -(tmp4_);
double tmp178_ = tmp14_*tmp17_;
double tmp179_ = tmp133_*tmp43_;
double tmp180_ = tmp179_*(tmp108_);
double tmp181_ = tmp175_*tmp110_;
double tmp182_ = tmp176_*tmp113_;
double tmp183_ = tmp181_+tmp182_;
double tmp184_ = (tmp183_)*(tmp132_);
double tmp185_ = tmp180_+tmp184_;
double tmp186_ = tmp175_*tmp168_;
double tmp187_ = tmp176_*tmp110_;
double tmp188_ = tmp186_+tmp187_;
double tmp189_ = tmp185_+tmp188_;
double tmp190_ = (tmp160_)*(tmp189_);
double tmp191_ = tmp14_*tmp67_;
double tmp192_ = tmp191_*(tmp66_);
double tmp193_ = tmp177_*tmp19_;
double tmp194_ = tmp178_*tmp15_;
double tmp195_ = tmp193_+tmp194_;
double tmp196_ = (tmp195_)*(tmp86_);
double tmp197_ = tmp192_+tmp196_;
double tmp198_ = tmp177_*tmp143_;
double tmp199_ = tmp178_*tmp19_;
double tmp200_ = tmp198_+tmp199_;
double tmp201_ = tmp197_+tmp200_;
double tmp202_ = (tmp201_)*(tmp153_);
double tmp203_ = tmp190_-tmp202_;
double tmp204_ = (tmp201_)*(tmp172_);
double tmp205_ = (tmp147_)*(tmp189_);
double tmp206_ = tmp204_-tmp205_;
double tmp207_ = mCompCoord[28];
double tmp208_ = mCompCoord[22];
double tmp209_ = tmp207_-tmp208_;
double tmp210_ = mCompCoord[26];
double tmp211_ = mCompCoord[20];
double tmp212_ = tmp210_-tmp211_;
double tmp213_ = mCompCoord[27];
double tmp214_ = mCompCoord[21];
double tmp215_ = tmp213_-tmp214_;
double tmp216_ = (tmp215_)*(tmp153_);
double tmp217_ = (tmp209_)*(tmp172_);
double tmp218_ = tmp216_-tmp217_;
double tmp219_ = (tmp209_)*(tmp189_);
double tmp220_ = (tmp212_)*(tmp153_);
double tmp221_ = tmp219_-tmp220_;
double tmp222_ = (tmp212_)*(tmp172_);
double tmp223_ = (tmp215_)*(tmp189_);
double tmp224_ = tmp222_-tmp223_;
double tmp225_ = ElSquare(tmp13_);
double tmp226_ = -(tmp65_);
double tmp227_ = tmp226_/tmp225_;
double tmp228_ = -(tmp85_);
double tmp229_ = tmp228_/tmp225_;
double tmp230_ = -(tmp107_);
double tmp231_ = tmp230_/tmp225_;
double tmp232_ = -(tmp131_);
double tmp233_ = tmp232_/tmp225_;
double tmp234_ = (tmp227_)*tmp136_;
double tmp235_ = (tmp229_)*(tmp140_);
double tmp236_ = tmp234_+tmp235_;
double tmp237_ = (tmp236_)*(tmp153_);
double tmp238_ = (tmp231_)*tmp112_;
double tmp239_ = (tmp233_)*tmp149_;
double tmp240_ = tmp238_+tmp239_;
double tmp241_ = (tmp240_)*(tmp147_);
double tmp242_ = tmp237_+tmp241_;
double tmp243_ = (tmp227_)*tmp16_;
double tmp244_ = (tmp229_)*tmp156_;
double tmp245_ = tmp243_+tmp244_;
double tmp246_ = (tmp245_)*(tmp172_);
double tmp247_ = (tmp231_)*tmp161_;
double tmp248_ = (tmp233_)*(tmp165_);
double tmp249_ = tmp247_+tmp248_;
double tmp250_ = (tmp249_)*(tmp160_);
double tmp251_ = tmp246_+tmp250_;
double tmp252_ = (tmp242_)-(tmp251_);
double tmp253_ = (tmp252_)*(tmp174_);
double tmp254_ = (tmp245_)*(tmp189_);
double tmp255_ = (tmp231_)*tmp179_;
double tmp256_ = (tmp233_)*(tmp183_);
double tmp257_ = tmp255_+tmp256_;
double tmp258_ = (tmp257_)*(tmp160_);
double tmp259_ = tmp254_+tmp258_;
double tmp260_ = (tmp227_)*tmp191_;
double tmp261_ = (tmp229_)*(tmp195_);
double tmp262_ = tmp260_+tmp261_;
double tmp263_ = (tmp262_)*(tmp153_);
double tmp264_ = (tmp240_)*(tmp201_);
double tmp265_ = tmp263_+tmp264_;
double tmp266_ = (tmp259_)-(tmp265_);
double tmp267_ = (tmp266_)*(tmp203_);
double tmp268_ = (tmp262_)*(tmp172_);
double tmp269_ = (tmp249_)*(tmp201_);
double tmp270_ = tmp268_+tmp269_;
double tmp271_ = (tmp236_)*(tmp189_);
double tmp272_ = (tmp257_)*(tmp147_);
double tmp273_ = tmp271_+tmp272_;
double tmp274_ = (tmp270_)-(tmp273_);
double tmp275_ = (tmp274_)*(tmp206_);
double tmp276_ = (tmp174_)*(tmp174_);
double tmp277_ = (tmp203_)*(tmp203_);
double tmp278_ = tmp276_+tmp277_;
double tmp279_ = (tmp206_)*(tmp206_);
double tmp280_ = tmp278_+tmp279_;
double tmp281_ = sqrt(tmp280_);
double tmp282_ = (tmp201_)*(tmp201_);
double tmp283_ = (tmp147_)*(tmp147_);
double tmp284_ = tmp282_+tmp283_;
double tmp285_ = (tmp160_)*(tmp160_);
double tmp286_ = tmp284_+tmp285_;
double tmp287_ = sqrt(tmp286_);
double tmp288_ = (tmp262_)*(tmp201_);
double tmp289_ = (tmp236_)*(tmp147_);
double tmp290_ = (tmp245_)*(tmp160_);
double tmp291_ = (tmp218_)*(tmp201_);
double tmp292_ = (tmp221_)*(tmp147_);
double tmp293_ = tmp291_+tmp292_;
double tmp294_ = (tmp224_)*(tmp160_);
double tmp295_ = tmp293_+tmp294_;
double tmp296_ = (tmp218_)*(tmp174_);
double tmp297_ = (tmp221_)*(tmp203_);
double tmp298_ = tmp296_+tmp297_;
double tmp299_ = (tmp224_)*(tmp206_);
double tmp300_ = tmp298_+tmp299_;
double tmp301_ = (tmp295_)/(tmp300_);
double tmp302_ = (tmp240_)*(tmp215_);
double tmp303_ = (tmp249_)*(tmp209_);
double tmp304_ = tmp302_-tmp303_;
double tmp305_ = (tmp257_)*(tmp209_);
double tmp306_ = (tmp240_)*(tmp212_);
double tmp307_ = tmp305_-tmp306_;
double tmp308_ = (tmp249_)*(tmp212_);
double tmp309_ = (tmp257_)*(tmp215_);
double tmp310_ = tmp308_-tmp309_;
double tmp311_ = tmp281_/tmp287_;
double tmp312_ = -(1);
double tmp313_ = tmp312_*tmp13_;
double tmp314_ = (tmp313_)/tmp225_;
double tmp315_ = (tmp314_)*tmp136_;
double tmp316_ = tmp315_*(tmp153_);
double tmp317_ = (tmp314_)*tmp112_;
double tmp318_ = tmp317_*(tmp147_);
double tmp319_ = tmp316_+tmp318_;
double tmp320_ = (tmp314_)*tmp16_;
double tmp321_ = tmp320_*(tmp172_);
double tmp322_ = (tmp314_)*tmp161_;
double tmp323_ = tmp322_*(tmp160_);
double tmp324_ = tmp321_+tmp323_;
double tmp325_ = (tmp319_)-(tmp324_);
double tmp326_ = (tmp325_)*(tmp174_);
double tmp327_ = tmp320_*(tmp189_);
double tmp328_ = (tmp314_)*tmp179_;
double tmp329_ = tmp328_*(tmp160_);
double tmp330_ = tmp327_+tmp329_;
double tmp331_ = (tmp314_)*tmp191_;
double tmp332_ = tmp331_*(tmp153_);
double tmp333_ = tmp317_*(tmp201_);
double tmp334_ = tmp332_+tmp333_;
double tmp335_ = (tmp330_)-(tmp334_);
double tmp336_ = (tmp335_)*(tmp203_);
double tmp337_ = tmp331_*(tmp172_);
double tmp338_ = tmp322_*(tmp201_);
double tmp339_ = tmp337_+tmp338_;
double tmp340_ = tmp315_*(tmp189_);
double tmp341_ = tmp328_*(tmp147_);
double tmp342_ = tmp340_+tmp341_;
double tmp343_ = (tmp339_)-(tmp342_);
double tmp344_ = (tmp343_)*(tmp206_);
double tmp345_ = tmp331_*(tmp201_);
double tmp346_ = tmp315_*(tmp147_);
double tmp347_ = tmp320_*(tmp160_);
double tmp348_ = ElSquare(tmp287_);
double tmp349_ = tmp317_*(tmp215_);
double tmp350_ = tmp322_*(tmp209_);
double tmp351_ = tmp349_-tmp350_;
double tmp352_ = tmp328_*(tmp209_);
double tmp353_ = tmp317_*(tmp212_);
double tmp354_ = tmp352_-tmp353_;
double tmp355_ = tmp322_*(tmp212_);
double tmp356_ = tmp328_*(tmp215_);
double tmp357_ = tmp355_-tmp356_;
double tmp358_ = ElSquare(tmp300_);
double tmp359_ = (tmp314_)*(tmp140_);
double tmp360_ = tmp359_*(tmp153_);
double tmp361_ = (tmp314_)*tmp149_;
double tmp362_ = tmp361_*(tmp147_);
double tmp363_ = tmp360_+tmp362_;
double tmp364_ = (tmp314_)*tmp156_;
double tmp365_ = tmp364_*(tmp172_);
double tmp366_ = (tmp314_)*(tmp165_);
double tmp367_ = tmp366_*(tmp160_);
double tmp368_ = tmp365_+tmp367_;
double tmp369_ = (tmp363_)-(tmp368_);
double tmp370_ = (tmp369_)*(tmp174_);
double tmp371_ = tmp364_*(tmp189_);
double tmp372_ = (tmp314_)*(tmp183_);
double tmp373_ = tmp372_*(tmp160_);
double tmp374_ = tmp371_+tmp373_;
double tmp375_ = (tmp314_)*(tmp195_);
double tmp376_ = tmp375_*(tmp153_);
double tmp377_ = tmp361_*(tmp201_);
double tmp378_ = tmp376_+tmp377_;
double tmp379_ = (tmp374_)-(tmp378_);
double tmp380_ = (tmp379_)*(tmp203_);
double tmp381_ = tmp375_*(tmp172_);
double tmp382_ = tmp366_*(tmp201_);
double tmp383_ = tmp381_+tmp382_;
double tmp384_ = tmp359_*(tmp189_);
double tmp385_ = tmp372_*(tmp147_);
double tmp386_ = tmp384_+tmp385_;
double tmp387_ = (tmp383_)-(tmp386_);
double tmp388_ = (tmp387_)*(tmp206_);
double tmp389_ = tmp375_*(tmp201_);
double tmp390_ = tmp359_*(tmp147_);
double tmp391_ = tmp364_*(tmp160_);
double tmp392_ = tmp361_*(tmp215_);
double tmp393_ = tmp366_*(tmp209_);
double tmp394_ = tmp392_-tmp393_;
double tmp395_ = tmp372_*(tmp209_);
double tmp396_ = tmp361_*(tmp212_);
double tmp397_ = tmp395_-tmp396_;
double tmp398_ = tmp366_*(tmp212_);
double tmp399_ = tmp372_*(tmp215_);
double tmp400_ = tmp398_-tmp399_;
double tmp401_ = mLocXL1*tmp13_;
double tmp402_ = (tmp401_)/tmp225_;
double tmp403_ = mLocXL2*tmp13_;
double tmp404_ = (tmp403_)/tmp225_;
double tmp405_ = (tmp402_)*tmp136_;
double tmp406_ = tmp405_*(tmp153_);
double tmp407_ = (tmp404_)*tmp112_;
double tmp408_ = tmp407_*(tmp147_);
double tmp409_ = tmp406_+tmp408_;
double tmp410_ = (tmp402_)*tmp16_;
double tmp411_ = tmp410_*(tmp172_);
double tmp412_ = (tmp404_)*tmp161_;
double tmp413_ = tmp412_*(tmp160_);
double tmp414_ = tmp411_+tmp413_;
double tmp415_ = (tmp409_)-(tmp414_);
double tmp416_ = (tmp415_)*(tmp174_);
double tmp417_ = tmp410_*(tmp189_);
double tmp418_ = (tmp404_)*tmp179_;
double tmp419_ = tmp418_*(tmp160_);
double tmp420_ = tmp417_+tmp419_;
double tmp421_ = (tmp402_)*tmp191_;
double tmp422_ = tmp421_*(tmp153_);
double tmp423_ = tmp407_*(tmp201_);
double tmp424_ = tmp422_+tmp423_;
double tmp425_ = (tmp420_)-(tmp424_);
double tmp426_ = (tmp425_)*(tmp203_);
double tmp427_ = tmp421_*(tmp172_);
double tmp428_ = tmp412_*(tmp201_);
double tmp429_ = tmp427_+tmp428_;
double tmp430_ = tmp405_*(tmp189_);
double tmp431_ = tmp418_*(tmp147_);
double tmp432_ = tmp430_+tmp431_;
double tmp433_ = (tmp429_)-(tmp432_);
double tmp434_ = (tmp433_)*(tmp206_);
double tmp435_ = tmp421_*(tmp201_);
double tmp436_ = tmp405_*(tmp147_);
double tmp437_ = tmp410_*(tmp160_);
double tmp438_ = tmp407_*(tmp215_);
double tmp439_ = tmp412_*(tmp209_);
double tmp440_ = tmp438_-tmp439_;
double tmp441_ = tmp418_*(tmp209_);
double tmp442_ = tmp407_*(tmp212_);
double tmp443_ = tmp441_-tmp442_;
double tmp444_ = tmp412_*(tmp212_);
double tmp445_ = tmp418_*(tmp215_);
double tmp446_ = tmp444_-tmp445_;
double tmp447_ = mLocYL1*tmp13_;
double tmp448_ = (tmp447_)/tmp225_;
double tmp449_ = mLocYL2*tmp13_;
double tmp450_ = (tmp449_)/tmp225_;
double tmp451_ = (tmp448_)*tmp136_;
double tmp452_ = tmp451_*(tmp153_);
double tmp453_ = (tmp450_)*tmp112_;
double tmp454_ = tmp453_*(tmp147_);
double tmp455_ = tmp452_+tmp454_;
double tmp456_ = (tmp448_)*tmp16_;
double tmp457_ = tmp456_*(tmp172_);
double tmp458_ = (tmp450_)*tmp161_;
double tmp459_ = tmp458_*(tmp160_);
double tmp460_ = tmp457_+tmp459_;
double tmp461_ = (tmp455_)-(tmp460_);
double tmp462_ = (tmp461_)*(tmp174_);
double tmp463_ = tmp456_*(tmp189_);
double tmp464_ = (tmp450_)*tmp179_;
double tmp465_ = tmp464_*(tmp160_);
double tmp466_ = tmp463_+tmp465_;
double tmp467_ = (tmp448_)*tmp191_;
double tmp468_ = tmp467_*(tmp153_);
double tmp469_ = tmp453_*(tmp201_);
double tmp470_ = tmp468_+tmp469_;
double tmp471_ = (tmp466_)-(tmp470_);
double tmp472_ = (tmp471_)*(tmp203_);
double tmp473_ = tmp467_*(tmp172_);
double tmp474_ = tmp458_*(tmp201_);
double tmp475_ = tmp473_+tmp474_;
double tmp476_ = tmp451_*(tmp189_);
double tmp477_ = tmp464_*(tmp147_);
double tmp478_ = tmp476_+tmp477_;
double tmp479_ = (tmp475_)-(tmp478_);
double tmp480_ = (tmp479_)*(tmp206_);
double tmp481_ = tmp467_*(tmp201_);
double tmp482_ = tmp451_*(tmp147_);
double tmp483_ = tmp456_*(tmp160_);
double tmp484_ = tmp453_*(tmp215_);
double tmp485_ = tmp458_*(tmp209_);
double tmp486_ = tmp484_-tmp485_;
double tmp487_ = tmp464_*(tmp209_);
double tmp488_ = tmp453_*(tmp212_);
double tmp489_ = tmp487_-tmp488_;
double tmp490_ = tmp458_*(tmp212_);
double tmp491_ = tmp464_*(tmp215_);
double tmp492_ = tmp490_-tmp491_;
double tmp493_ = tmp7_*tmp13_;
double tmp494_ = (tmp493_)/tmp225_;
double tmp495_ = tmp34_*tmp13_;
double tmp496_ = (tmp495_)/tmp225_;
double tmp497_ = (tmp494_)*tmp136_;
double tmp498_ = tmp497_*(tmp153_);
double tmp499_ = (tmp496_)*tmp112_;
double tmp500_ = tmp499_*(tmp147_);
double tmp501_ = tmp498_+tmp500_;
double tmp502_ = (tmp494_)*tmp16_;
double tmp503_ = tmp502_*(tmp172_);
double tmp504_ = (tmp496_)*tmp161_;
double tmp505_ = tmp504_*(tmp160_);
double tmp506_ = tmp503_+tmp505_;
double tmp507_ = (tmp501_)-(tmp506_);
double tmp508_ = (tmp507_)*(tmp174_);
double tmp509_ = tmp502_*(tmp189_);
double tmp510_ = (tmp496_)*tmp179_;
double tmp511_ = tmp510_*(tmp160_);
double tmp512_ = tmp509_+tmp511_;
double tmp513_ = (tmp494_)*tmp191_;
double tmp514_ = tmp513_*(tmp153_);
double tmp515_ = tmp499_*(tmp201_);
double tmp516_ = tmp514_+tmp515_;
double tmp517_ = (tmp512_)-(tmp516_);
double tmp518_ = (tmp517_)*(tmp203_);
double tmp519_ = tmp513_*(tmp172_);
double tmp520_ = tmp504_*(tmp201_);
double tmp521_ = tmp519_+tmp520_;
double tmp522_ = tmp497_*(tmp189_);
double tmp523_ = tmp510_*(tmp147_);
double tmp524_ = tmp522_+tmp523_;
double tmp525_ = (tmp521_)-(tmp524_);
double tmp526_ = (tmp525_)*(tmp206_);
double tmp527_ = tmp513_*(tmp201_);
double tmp528_ = tmp497_*(tmp147_);
double tmp529_ = tmp502_*(tmp160_);
double tmp530_ = tmp499_*(tmp215_);
double tmp531_ = tmp504_*(tmp209_);
double tmp532_ = tmp530_-tmp531_;
double tmp533_ = tmp510_*(tmp209_);
double tmp534_ = tmp499_*(tmp212_);
double tmp535_ = tmp533_-tmp534_;
double tmp536_ = tmp504_*(tmp212_);
double tmp537_ = tmp510_*(tmp215_);
double tmp538_ = tmp536_-tmp537_;
double tmp539_ = tmp0_*tmp13_;
double tmp540_ = (tmp539_)/tmp225_;
double tmp541_ = tmp27_*tmp13_;
double tmp542_ = (tmp541_)/tmp225_;
double tmp543_ = (tmp540_)*tmp136_;
double tmp544_ = tmp543_*(tmp153_);
double tmp545_ = (tmp542_)*tmp112_;
double tmp546_ = tmp545_*(tmp147_);
double tmp547_ = tmp544_+tmp546_;
double tmp548_ = (tmp540_)*tmp16_;
double tmp549_ = tmp548_*(tmp172_);
double tmp550_ = (tmp542_)*tmp161_;
double tmp551_ = tmp550_*(tmp160_);
double tmp552_ = tmp549_+tmp551_;
double tmp553_ = (tmp547_)-(tmp552_);
double tmp554_ = (tmp553_)*(tmp174_);
double tmp555_ = tmp548_*(tmp189_);
double tmp556_ = (tmp542_)*tmp179_;
double tmp557_ = tmp556_*(tmp160_);
double tmp558_ = tmp555_+tmp557_;
double tmp559_ = (tmp540_)*tmp191_;
double tmp560_ = tmp559_*(tmp153_);
double tmp561_ = tmp545_*(tmp201_);
double tmp562_ = tmp560_+tmp561_;
double tmp563_ = (tmp558_)-(tmp562_);
double tmp564_ = (tmp563_)*(tmp203_);
double tmp565_ = tmp559_*(tmp172_);
double tmp566_ = tmp550_*(tmp201_);
double tmp567_ = tmp565_+tmp566_;
double tmp568_ = tmp543_*(tmp189_);
double tmp569_ = tmp556_*(tmp147_);
double tmp570_ = tmp568_+tmp569_;
double tmp571_ = (tmp567_)-(tmp570_);
double tmp572_ = (tmp571_)*(tmp206_);
double tmp573_ = tmp559_*(tmp201_);
double tmp574_ = tmp543_*(tmp147_);
double tmp575_ = tmp548_*(tmp160_);
double tmp576_ = tmp545_*(tmp215_);
double tmp577_ = tmp550_*(tmp209_);
double tmp578_ = tmp576_-tmp577_;
double tmp579_ = tmp556_*(tmp209_);
double tmp580_ = tmp545_*(tmp212_);
double tmp581_ = tmp579_-tmp580_;
double tmp582_ = tmp550_*(tmp212_);
double tmp583_ = tmp556_*(tmp215_);
double tmp584_ = tmp582_-tmp583_;
double tmp585_ = tmp8_*tmp13_;
double tmp586_ = (tmp585_)/tmp225_;
double tmp587_ = tmp37_*tmp13_;
double tmp588_ = (tmp587_)/tmp225_;
double tmp589_ = (tmp586_)*tmp136_;
double tmp590_ = tmp589_*(tmp153_);
double tmp591_ = (tmp588_)*tmp112_;
double tmp592_ = tmp591_*(tmp147_);
double tmp593_ = tmp590_+tmp592_;
double tmp594_ = (tmp586_)*tmp16_;
double tmp595_ = tmp594_*(tmp172_);
double tmp596_ = (tmp588_)*tmp161_;
double tmp597_ = tmp596_*(tmp160_);
double tmp598_ = tmp595_+tmp597_;
double tmp599_ = (tmp593_)-(tmp598_);
double tmp600_ = (tmp599_)*(tmp174_);
double tmp601_ = tmp594_*(tmp189_);
double tmp602_ = (tmp588_)*tmp179_;
double tmp603_ = tmp602_*(tmp160_);
double tmp604_ = tmp601_+tmp603_;
double tmp605_ = (tmp586_)*tmp191_;
double tmp606_ = tmp605_*(tmp153_);
double tmp607_ = tmp591_*(tmp201_);
double tmp608_ = tmp606_+tmp607_;
double tmp609_ = (tmp604_)-(tmp608_);
double tmp610_ = (tmp609_)*(tmp203_);
double tmp611_ = tmp605_*(tmp172_);
double tmp612_ = tmp596_*(tmp201_);
double tmp613_ = tmp611_+tmp612_;
double tmp614_ = tmp589_*(tmp189_);
double tmp615_ = tmp602_*(tmp147_);
double tmp616_ = tmp614_+tmp615_;
double tmp617_ = (tmp613_)-(tmp616_);
double tmp618_ = (tmp617_)*(tmp206_);
double tmp619_ = tmp605_*(tmp201_);
double tmp620_ = tmp589_*(tmp147_);
double tmp621_ = tmp594_*(tmp160_);
double tmp622_ = tmp591_*(tmp215_);
double tmp623_ = tmp596_*(tmp209_);
double tmp624_ = tmp622_-tmp623_;
double tmp625_ = tmp602_*(tmp209_);
double tmp626_ = tmp591_*(tmp212_);
double tmp627_ = tmp625_-tmp626_;
double tmp628_ = tmp596_*(tmp212_);
double tmp629_ = tmp602_*(tmp215_);
double tmp630_ = tmp628_-tmp629_;
double tmp631_ = tmp9_*tmp13_;
double tmp632_ = (tmp631_)/tmp225_;
double tmp633_ = tmp39_*tmp13_;
double tmp634_ = (tmp633_)/tmp225_;
double tmp635_ = (tmp632_)*tmp136_;
double tmp636_ = tmp635_*(tmp153_);
double tmp637_ = (tmp634_)*tmp112_;
double tmp638_ = tmp637_*(tmp147_);
double tmp639_ = tmp636_+tmp638_;
double tmp640_ = (tmp632_)*tmp16_;
double tmp641_ = tmp640_*(tmp172_);
double tmp642_ = (tmp634_)*tmp161_;
double tmp643_ = tmp642_*(tmp160_);
double tmp644_ = tmp641_+tmp643_;
double tmp645_ = (tmp639_)-(tmp644_);
double tmp646_ = (tmp645_)*(tmp174_);
double tmp647_ = tmp640_*(tmp189_);
double tmp648_ = (tmp634_)*tmp179_;
double tmp649_ = tmp648_*(tmp160_);
double tmp650_ = tmp647_+tmp649_;
double tmp651_ = (tmp632_)*tmp191_;
double tmp652_ = tmp651_*(tmp153_);
double tmp653_ = tmp637_*(tmp201_);
double tmp654_ = tmp652_+tmp653_;
double tmp655_ = (tmp650_)-(tmp654_);
double tmp656_ = (tmp655_)*(tmp203_);
double tmp657_ = tmp651_*(tmp172_);
double tmp658_ = tmp642_*(tmp201_);
double tmp659_ = tmp657_+tmp658_;
double tmp660_ = tmp635_*(tmp189_);
double tmp661_ = tmp648_*(tmp147_);
double tmp662_ = tmp660_+tmp661_;
double tmp663_ = (tmp659_)-(tmp662_);
double tmp664_ = (tmp663_)*(tmp206_);
double tmp665_ = tmp651_*(tmp201_);
double tmp666_ = tmp635_*(tmp147_);
double tmp667_ = tmp640_*(tmp160_);
double tmp668_ = tmp637_*(tmp215_);
double tmp669_ = tmp642_*(tmp209_);
double tmp670_ = tmp668_-tmp669_;
double tmp671_ = tmp648_*(tmp209_);
double tmp672_ = tmp637_*(tmp212_);
double tmp673_ = tmp671_-tmp672_;
double tmp674_ = tmp642_*(tmp212_);
double tmp675_ = tmp648_*(tmp215_);
double tmp676_ = tmp674_-tmp675_;
double tmp677_ = tmp2_*tmp13_;
double tmp678_ = (tmp677_)/tmp225_;
double tmp679_ = tmp30_*tmp13_;
double tmp680_ = (tmp679_)/tmp225_;
double tmp681_ = (tmp678_)*tmp136_;
double tmp682_ = tmp681_*(tmp153_);
double tmp683_ = (tmp680_)*tmp112_;
double tmp684_ = tmp683_*(tmp147_);
double tmp685_ = tmp682_+tmp684_;
double tmp686_ = (tmp678_)*tmp16_;
double tmp687_ = tmp686_*(tmp172_);
double tmp688_ = (tmp680_)*tmp161_;
double tmp689_ = tmp688_*(tmp160_);
double tmp690_ = tmp687_+tmp689_;
double tmp691_ = (tmp685_)-(tmp690_);
double tmp692_ = (tmp691_)*(tmp174_);
double tmp693_ = tmp686_*(tmp189_);
double tmp694_ = (tmp680_)*tmp179_;
double tmp695_ = tmp694_*(tmp160_);
double tmp696_ = tmp693_+tmp695_;
double tmp697_ = (tmp678_)*tmp191_;
double tmp698_ = tmp697_*(tmp153_);
double tmp699_ = tmp683_*(tmp201_);
double tmp700_ = tmp698_+tmp699_;
double tmp701_ = (tmp696_)-(tmp700_);
double tmp702_ = (tmp701_)*(tmp203_);
double tmp703_ = tmp697_*(tmp172_);
double tmp704_ = tmp688_*(tmp201_);
double tmp705_ = tmp703_+tmp704_;
double tmp706_ = tmp681_*(tmp189_);
double tmp707_ = tmp694_*(tmp147_);
double tmp708_ = tmp706_+tmp707_;
double tmp709_ = (tmp705_)-(tmp708_);
double tmp710_ = (tmp709_)*(tmp206_);
double tmp711_ = tmp697_*(tmp201_);
double tmp712_ = tmp681_*(tmp147_);
double tmp713_ = tmp686_*(tmp160_);
double tmp714_ = tmp683_*(tmp215_);
double tmp715_ = tmp688_*(tmp209_);
double tmp716_ = tmp714_-tmp715_;
double tmp717_ = tmp694_*(tmp209_);
double tmp718_ = tmp683_*(tmp212_);
double tmp719_ = tmp717_-tmp718_;
double tmp720_ = tmp688_*(tmp212_);
double tmp721_ = tmp694_*(tmp215_);
double tmp722_ = tmp720_-tmp721_;
double tmp723_ = (tmp494_)*(tmp140_);
double tmp724_ = tmp723_*(tmp153_);
double tmp725_ = (tmp496_)*tmp149_;
double tmp726_ = tmp725_*(tmp147_);
double tmp727_ = tmp724_+tmp726_;
double tmp728_ = (tmp494_)*tmp156_;
double tmp729_ = tmp728_*(tmp172_);
double tmp730_ = (tmp496_)*(tmp165_);
double tmp731_ = tmp730_*(tmp160_);
double tmp732_ = tmp729_+tmp731_;
double tmp733_ = (tmp727_)-(tmp732_);
double tmp734_ = (tmp733_)*(tmp174_);
double tmp735_ = tmp728_*(tmp189_);
double tmp736_ = (tmp496_)*(tmp183_);
double tmp737_ = tmp736_*(tmp160_);
double tmp738_ = tmp735_+tmp737_;
double tmp739_ = (tmp494_)*(tmp195_);
double tmp740_ = tmp739_*(tmp153_);
double tmp741_ = tmp725_*(tmp201_);
double tmp742_ = tmp740_+tmp741_;
double tmp743_ = (tmp738_)-(tmp742_);
double tmp744_ = (tmp743_)*(tmp203_);
double tmp745_ = tmp739_*(tmp172_);
double tmp746_ = tmp730_*(tmp201_);
double tmp747_ = tmp745_+tmp746_;
double tmp748_ = tmp723_*(tmp189_);
double tmp749_ = tmp736_*(tmp147_);
double tmp750_ = tmp748_+tmp749_;
double tmp751_ = (tmp747_)-(tmp750_);
double tmp752_ = (tmp751_)*(tmp206_);
double tmp753_ = tmp739_*(tmp201_);
double tmp754_ = tmp723_*(tmp147_);
double tmp755_ = tmp728_*(tmp160_);
double tmp756_ = tmp725_*(tmp215_);
double tmp757_ = tmp730_*(tmp209_);
double tmp758_ = tmp756_-tmp757_;
double tmp759_ = tmp736_*(tmp209_);
double tmp760_ = tmp725_*(tmp212_);
double tmp761_ = tmp759_-tmp760_;
double tmp762_ = tmp730_*(tmp212_);
double tmp763_ = tmp736_*(tmp215_);
double tmp764_ = tmp762_-tmp763_;
double tmp765_ = tmp1_*tmp13_;
double tmp766_ = (tmp765_)/tmp225_;
double tmp767_ = tmp29_*tmp13_;
double tmp768_ = (tmp767_)/tmp225_;
double tmp769_ = (tmp766_)*(tmp140_);
double tmp770_ = tmp769_*(tmp153_);
double tmp771_ = (tmp768_)*tmp149_;
double tmp772_ = tmp771_*(tmp147_);
double tmp773_ = tmp770_+tmp772_;
double tmp774_ = (tmp766_)*tmp156_;
double tmp775_ = tmp774_*(tmp172_);
double tmp776_ = (tmp768_)*(tmp165_);
double tmp777_ = tmp776_*(tmp160_);
double tmp778_ = tmp775_+tmp777_;
double tmp779_ = (tmp773_)-(tmp778_);
double tmp780_ = (tmp779_)*(tmp174_);
double tmp781_ = tmp774_*(tmp189_);
double tmp782_ = (tmp768_)*(tmp183_);
double tmp783_ = tmp782_*(tmp160_);
double tmp784_ = tmp781_+tmp783_;
double tmp785_ = (tmp766_)*(tmp195_);
double tmp786_ = tmp785_*(tmp153_);
double tmp787_ = tmp771_*(tmp201_);
double tmp788_ = tmp786_+tmp787_;
double tmp789_ = (tmp784_)-(tmp788_);
double tmp790_ = (tmp789_)*(tmp203_);
double tmp791_ = tmp785_*(tmp172_);
double tmp792_ = tmp776_*(tmp201_);
double tmp793_ = tmp791_+tmp792_;
double tmp794_ = tmp769_*(tmp189_);
double tmp795_ = tmp782_*(tmp147_);
double tmp796_ = tmp794_+tmp795_;
double tmp797_ = (tmp793_)-(tmp796_);
double tmp798_ = (tmp797_)*(tmp206_);
double tmp799_ = tmp785_*(tmp201_);
double tmp800_ = tmp769_*(tmp147_);
double tmp801_ = tmp774_*(tmp160_);
double tmp802_ = tmp771_*(tmp215_);
double tmp803_ = tmp776_*(tmp209_);
double tmp804_ = tmp802_-tmp803_;
double tmp805_ = tmp782_*(tmp209_);
double tmp806_ = tmp771_*(tmp212_);
double tmp807_ = tmp805_-tmp806_;
double tmp808_ = tmp776_*(tmp212_);
double tmp809_ = tmp782_*(tmp215_);
double tmp810_ = tmp808_-tmp809_;
double tmp811_ = (tmp586_)*(tmp140_);
double tmp812_ = tmp811_*(tmp153_);
double tmp813_ = (tmp588_)*tmp149_;
double tmp814_ = tmp813_*(tmp147_);
double tmp815_ = tmp812_+tmp814_;
double tmp816_ = (tmp586_)*tmp156_;
double tmp817_ = tmp816_*(tmp172_);
double tmp818_ = (tmp588_)*(tmp165_);
double tmp819_ = tmp818_*(tmp160_);
double tmp820_ = tmp817_+tmp819_;
double tmp821_ = (tmp815_)-(tmp820_);
double tmp822_ = (tmp821_)*(tmp174_);
double tmp823_ = tmp816_*(tmp189_);
double tmp824_ = (tmp588_)*(tmp183_);
double tmp825_ = tmp824_*(tmp160_);
double tmp826_ = tmp823_+tmp825_;
double tmp827_ = (tmp586_)*(tmp195_);
double tmp828_ = tmp827_*(tmp153_);
double tmp829_ = tmp813_*(tmp201_);
double tmp830_ = tmp828_+tmp829_;
double tmp831_ = (tmp826_)-(tmp830_);
double tmp832_ = (tmp831_)*(tmp203_);
double tmp833_ = tmp827_*(tmp172_);
double tmp834_ = tmp818_*(tmp201_);
double tmp835_ = tmp833_+tmp834_;
double tmp836_ = tmp811_*(tmp189_);
double tmp837_ = tmp824_*(tmp147_);
double tmp838_ = tmp836_+tmp837_;
double tmp839_ = (tmp835_)-(tmp838_);
double tmp840_ = (tmp839_)*(tmp206_);
double tmp841_ = tmp827_*(tmp201_);
double tmp842_ = tmp811_*(tmp147_);
double tmp843_ = tmp816_*(tmp160_);
double tmp844_ = tmp813_*(tmp215_);
double tmp845_ = tmp818_*(tmp209_);
double tmp846_ = tmp844_-tmp845_;
double tmp847_ = tmp824_*(tmp209_);
double tmp848_ = tmp813_*(tmp212_);
double tmp849_ = tmp847_-tmp848_;
double tmp850_ = tmp818_*(tmp212_);
double tmp851_ = tmp824_*(tmp215_);
double tmp852_ = tmp850_-tmp851_;
double tmp853_ = (tmp632_)*(tmp140_);
double tmp854_ = tmp853_*(tmp153_);
double tmp855_ = (tmp634_)*tmp149_;
double tmp856_ = tmp855_*(tmp147_);
double tmp857_ = tmp854_+tmp856_;
double tmp858_ = (tmp632_)*tmp156_;
double tmp859_ = tmp858_*(tmp172_);
double tmp860_ = (tmp634_)*(tmp165_);
double tmp861_ = tmp860_*(tmp160_);
double tmp862_ = tmp859_+tmp861_;
double tmp863_ = (tmp857_)-(tmp862_);
double tmp864_ = (tmp863_)*(tmp174_);
double tmp865_ = tmp858_*(tmp189_);
double tmp866_ = (tmp634_)*(tmp183_);
double tmp867_ = tmp866_*(tmp160_);
double tmp868_ = tmp865_+tmp867_;
double tmp869_ = (tmp632_)*(tmp195_);
double tmp870_ = tmp869_*(tmp153_);
double tmp871_ = tmp855_*(tmp201_);
double tmp872_ = tmp870_+tmp871_;
double tmp873_ = (tmp868_)-(tmp872_);
double tmp874_ = (tmp873_)*(tmp203_);
double tmp875_ = tmp869_*(tmp172_);
double tmp876_ = tmp860_*(tmp201_);
double tmp877_ = tmp875_+tmp876_;
double tmp878_ = tmp853_*(tmp189_);
double tmp879_ = tmp866_*(tmp147_);
double tmp880_ = tmp878_+tmp879_;
double tmp881_ = (tmp877_)-(tmp880_);
double tmp882_ = (tmp881_)*(tmp206_);
double tmp883_ = tmp869_*(tmp201_);
double tmp884_ = tmp853_*(tmp147_);
double tmp885_ = tmp858_*(tmp160_);
double tmp886_ = tmp855_*(tmp215_);
double tmp887_ = tmp860_*(tmp209_);
double tmp888_ = tmp886_-tmp887_;
double tmp889_ = tmp866_*(tmp209_);
double tmp890_ = tmp855_*(tmp212_);
double tmp891_ = tmp889_-tmp890_;
double tmp892_ = tmp860_*(tmp212_);
double tmp893_ = tmp866_*(tmp215_);
double tmp894_ = tmp892_-tmp893_;
double tmp895_ = (tmp678_)*(tmp140_);
double tmp896_ = tmp895_*(tmp153_);
double tmp897_ = (tmp680_)*tmp149_;
double tmp898_ = tmp897_*(tmp147_);
double tmp899_ = tmp896_+tmp898_;
double tmp900_ = (tmp678_)*tmp156_;
double tmp901_ = tmp900_*(tmp172_);
double tmp902_ = (tmp680_)*(tmp165_);
double tmp903_ = tmp902_*(tmp160_);
double tmp904_ = tmp901_+tmp903_;
double tmp905_ = (tmp899_)-(tmp904_);
double tmp906_ = (tmp905_)*(tmp174_);
double tmp907_ = tmp900_*(tmp189_);
double tmp908_ = (tmp680_)*(tmp183_);
double tmp909_ = tmp908_*(tmp160_);
double tmp910_ = tmp907_+tmp909_;
double tmp911_ = (tmp678_)*(tmp195_);
double tmp912_ = tmp911_*(tmp153_);
double tmp913_ = tmp897_*(tmp201_);
double tmp914_ = tmp912_+tmp913_;
double tmp915_ = (tmp910_)-(tmp914_);
double tmp916_ = (tmp915_)*(tmp203_);
double tmp917_ = tmp911_*(tmp172_);
double tmp918_ = tmp902_*(tmp201_);
double tmp919_ = tmp917_+tmp918_;
double tmp920_ = tmp895_*(tmp189_);
double tmp921_ = tmp908_*(tmp147_);
double tmp922_ = tmp920_+tmp921_;
double tmp923_ = (tmp919_)-(tmp922_);
double tmp924_ = (tmp923_)*(tmp206_);
double tmp925_ = tmp911_*(tmp201_);
double tmp926_ = tmp895_*(tmp147_);
double tmp927_ = tmp900_*(tmp160_);
double tmp928_ = tmp897_*(tmp215_);
double tmp929_ = tmp902_*(tmp209_);
double tmp930_ = tmp928_-tmp929_;
double tmp931_ = tmp908_*(tmp209_);
double tmp932_ = tmp897_*(tmp212_);
double tmp933_ = tmp931_-tmp932_;
double tmp934_ = tmp902_*(tmp212_);
double tmp935_ = tmp908_*(tmp215_);
double tmp936_ = tmp934_-tmp935_;
double tmp937_ = (tmp58_)*tmp2_;
double tmp938_ = tmp937_*tmp13_;
double tmp939_ = (tmp938_)/tmp225_;
double tmp940_ = (tmp78_)*tmp2_;
double tmp941_ = tmp940_*tmp13_;
double tmp942_ = (tmp941_)/tmp225_;
double tmp943_ = (tmp100_)*tmp30_;
double tmp944_ = tmp943_*tmp13_;
double tmp945_ = (tmp944_)/tmp225_;
double tmp946_ = (tmp124_)*tmp30_;
double tmp947_ = tmp946_*tmp13_;
double tmp948_ = (tmp947_)/tmp225_;
double tmp949_ = (tmp939_)*tmp136_;
double tmp950_ = (tmp942_)*(tmp140_);
double tmp951_ = tmp949_+tmp950_;
double tmp952_ = (tmp951_)*(tmp153_);
double tmp953_ = (tmp945_)*tmp112_;
double tmp954_ = (tmp948_)*tmp149_;
double tmp955_ = tmp953_+tmp954_;
double tmp956_ = (tmp955_)*(tmp147_);
double tmp957_ = tmp952_+tmp956_;
double tmp958_ = (tmp939_)*tmp16_;
double tmp959_ = (tmp942_)*tmp156_;
double tmp960_ = tmp958_+tmp959_;
double tmp961_ = (tmp960_)*(tmp172_);
double tmp962_ = (tmp945_)*tmp161_;
double tmp963_ = (tmp948_)*(tmp165_);
double tmp964_ = tmp962_+tmp963_;
double tmp965_ = (tmp964_)*(tmp160_);
double tmp966_ = tmp961_+tmp965_;
double tmp967_ = (tmp957_)-(tmp966_);
double tmp968_ = (tmp967_)*(tmp174_);
double tmp969_ = (tmp960_)*(tmp189_);
double tmp970_ = (tmp945_)*tmp179_;
double tmp971_ = (tmp948_)*(tmp183_);
double tmp972_ = tmp970_+tmp971_;
double tmp973_ = (tmp972_)*(tmp160_);
double tmp974_ = tmp969_+tmp973_;
double tmp975_ = (tmp939_)*tmp191_;
double tmp976_ = (tmp942_)*(tmp195_);
double tmp977_ = tmp975_+tmp976_;
double tmp978_ = (tmp977_)*(tmp153_);
double tmp979_ = (tmp955_)*(tmp201_);
double tmp980_ = tmp978_+tmp979_;
double tmp981_ = (tmp974_)-(tmp980_);
double tmp982_ = (tmp981_)*(tmp203_);
double tmp983_ = (tmp977_)*(tmp172_);
double tmp984_ = (tmp964_)*(tmp201_);
double tmp985_ = tmp983_+tmp984_;
double tmp986_ = (tmp951_)*(tmp189_);
double tmp987_ = (tmp972_)*(tmp147_);
double tmp988_ = tmp986_+tmp987_;
double tmp989_ = (tmp985_)-(tmp988_);
double tmp990_ = (tmp989_)*(tmp206_);
double tmp991_ = (tmp977_)*(tmp201_);
double tmp992_ = (tmp951_)*(tmp147_);
double tmp993_ = (tmp960_)*(tmp160_);
double tmp994_ = (tmp955_)*(tmp215_);
double tmp995_ = (tmp964_)*(tmp209_);
double tmp996_ = tmp994_-tmp995_;
double tmp997_ = (tmp972_)*(tmp209_);
double tmp998_ = (tmp955_)*(tmp212_);
double tmp999_ = tmp997_-tmp998_;
double tmp1000_ = (tmp964_)*(tmp212_);
double tmp1001_ = (tmp972_)*(tmp215_);
double tmp1002_ = tmp1000_-tmp1001_;
double tmp1003_ = mLocXL1*(tmp12_);
double tmp1004_ = tmp1003_*tmp13_;
double tmp1005_ = (tmp1004_)/tmp225_;
double tmp1006_ = mLocYL1*(tmp12_);
double tmp1007_ = tmp1006_*tmp13_;
double tmp1008_ = (tmp1007_)/tmp225_;
double tmp1009_ = mLocXL2*(tmp41_);
double tmp1010_ = tmp1009_*tmp13_;
double tmp1011_ = (tmp1010_)/tmp225_;
double tmp1012_ = mLocYL2*(tmp41_);
double tmp1013_ = tmp1012_*tmp13_;
double tmp1014_ = (tmp1013_)/tmp225_;
double tmp1015_ = (tmp1005_)*tmp136_;
double tmp1016_ = (tmp1008_)*(tmp140_);
double tmp1017_ = tmp1015_+tmp1016_;
double tmp1018_ = (tmp1017_)*(tmp153_);
double tmp1019_ = (tmp1011_)*tmp112_;
double tmp1020_ = (tmp1014_)*tmp149_;
double tmp1021_ = tmp1019_+tmp1020_;
double tmp1022_ = (tmp1021_)*(tmp147_);
double tmp1023_ = tmp1018_+tmp1022_;
double tmp1024_ = (tmp1005_)*tmp16_;
double tmp1025_ = (tmp1008_)*tmp156_;
double tmp1026_ = tmp1024_+tmp1025_;
double tmp1027_ = (tmp1026_)*(tmp172_);
double tmp1028_ = (tmp1011_)*tmp161_;
double tmp1029_ = (tmp1014_)*(tmp165_);
double tmp1030_ = tmp1028_+tmp1029_;
double tmp1031_ = (tmp1030_)*(tmp160_);
double tmp1032_ = tmp1027_+tmp1031_;
double tmp1033_ = (tmp1023_)-(tmp1032_);
double tmp1034_ = (tmp1033_)*(tmp174_);
double tmp1035_ = (tmp1026_)*(tmp189_);
double tmp1036_ = (tmp1011_)*tmp179_;
double tmp1037_ = (tmp1014_)*(tmp183_);
double tmp1038_ = tmp1036_+tmp1037_;
double tmp1039_ = (tmp1038_)*(tmp160_);
double tmp1040_ = tmp1035_+tmp1039_;
double tmp1041_ = (tmp1005_)*tmp191_;
double tmp1042_ = (tmp1008_)*(tmp195_);
double tmp1043_ = tmp1041_+tmp1042_;
double tmp1044_ = (tmp1043_)*(tmp153_);
double tmp1045_ = (tmp1021_)*(tmp201_);
double tmp1046_ = tmp1044_+tmp1045_;
double tmp1047_ = (tmp1040_)-(tmp1046_);
double tmp1048_ = (tmp1047_)*(tmp203_);
double tmp1049_ = (tmp1043_)*(tmp172_);
double tmp1050_ = (tmp1030_)*(tmp201_);
double tmp1051_ = tmp1049_+tmp1050_;
double tmp1052_ = (tmp1017_)*(tmp189_);
double tmp1053_ = (tmp1038_)*(tmp147_);
double tmp1054_ = tmp1052_+tmp1053_;
double tmp1055_ = (tmp1051_)-(tmp1054_);
double tmp1056_ = (tmp1055_)*(tmp206_);
double tmp1057_ = (tmp1043_)*(tmp201_);
double tmp1058_ = (tmp1017_)*(tmp147_);
double tmp1059_ = (tmp1026_)*(tmp160_);
double tmp1060_ = (tmp1021_)*(tmp215_);
double tmp1061_ = (tmp1030_)*(tmp209_);
double tmp1062_ = tmp1060_-tmp1061_;
double tmp1063_ = (tmp1038_)*(tmp209_);
double tmp1064_ = (tmp1021_)*(tmp212_);
double tmp1065_ = tmp1063_-tmp1064_;
double tmp1066_ = (tmp1030_)*(tmp212_);
double tmp1067_ = (tmp1038_)*(tmp215_);
double tmp1068_ = tmp1066_-tmp1067_;
double tmp1069_ = tmp312_*tmp4_;
double tmp1070_ = tmp1069_*tmp19_;
double tmp1071_ = tmp1070_+tmp194_;
double tmp1072_ = (tmp1071_)*(tmp86_);
double tmp1073_ = tmp192_+tmp1072_;
double tmp1074_ = tmp1069_*tmp143_;
double tmp1075_ = tmp1074_+tmp199_;
double tmp1076_ = tmp1073_+tmp1075_;
double tmp1077_ = (tmp1076_)*(tmp153_);
double tmp1078_ = tmp1077_*(tmp174_);
double tmp1079_ = -(tmp14_);
double tmp1080_ = tmp1069_*tmp17_;
double tmp1081_ = tmp1069_*tmp67_;
double tmp1082_ = tmp1081_*(tmp66_);
double tmp1083_ = tmp1079_*tmp19_;
double tmp1084_ = tmp1080_*tmp15_;
double tmp1085_ = tmp1083_+tmp1084_;
double tmp1086_ = (tmp1085_)*(tmp86_);
double tmp1087_ = tmp1082_+tmp1086_;
double tmp1088_ = tmp1079_*tmp143_;
double tmp1089_ = tmp1080_*tmp19_;
double tmp1090_ = tmp1088_+tmp1089_;
double tmp1091_ = tmp1087_+tmp1090_;
double tmp1092_ = (tmp1091_)*(tmp153_);
double tmp1093_ = -(tmp1092_);
double tmp1094_ = tmp1093_*(tmp203_);
double tmp1095_ = (tmp1091_)*(tmp172_);
double tmp1096_ = (tmp1076_)*(tmp189_);
double tmp1097_ = tmp1095_-tmp1096_;
double tmp1098_ = (tmp1097_)*(tmp206_);
double tmp1099_ = (tmp1091_)*(tmp201_);
double tmp1100_ = (tmp1076_)*(tmp147_);
double tmp1101_ = -(tmp67_);
double tmp1102_ = tmp1101_*tmp4_;
double tmp1103_ = tmp312_*tmp16_;
double tmp1104_ = tmp1103_*tmp4_;
double tmp1105_ = tmp1104_*(tmp66_);
double tmp1106_ = tmp1102_*tmp15_;
double tmp1107_ = tmp1106_*(tmp86_);
double tmp1108_ = tmp1105_+tmp1107_;
double tmp1109_ = tmp1102_*tmp19_;
double tmp1110_ = tmp1108_+tmp1109_;
double tmp1111_ = (tmp1110_)*(tmp153_);
double tmp1112_ = tmp67_*(tmp66_);
double tmp1113_ = tmp1103_*tmp15_;
double tmp1114_ = tmp1113_*(tmp86_);
double tmp1115_ = tmp1112_+tmp1114_;
double tmp1116_ = tmp1103_*tmp19_;
double tmp1117_ = tmp1115_+tmp1116_;
double tmp1118_ = (tmp1117_)*(tmp172_);
double tmp1119_ = tmp1111_-tmp1118_;
double tmp1120_ = (tmp1119_)*(tmp174_);
double tmp1121_ = tmp1101_*tmp14_;
double tmp1122_ = (tmp1117_)*(tmp189_);
double tmp1123_ = tmp1103_*tmp14_;
double tmp1124_ = tmp1123_*(tmp66_);
double tmp1125_ = tmp1121_*tmp15_;
double tmp1126_ = tmp1125_*(tmp86_);
double tmp1127_ = tmp1124_+tmp1126_;
double tmp1128_ = tmp1121_*tmp19_;
double tmp1129_ = tmp1127_+tmp1128_;
double tmp1130_ = (tmp1129_)*(tmp153_);
double tmp1131_ = tmp1122_-tmp1130_;
double tmp1132_ = (tmp1131_)*(tmp203_);
double tmp1133_ = (tmp1129_)*(tmp172_);
double tmp1134_ = (tmp1110_)*(tmp189_);
double tmp1135_ = tmp1133_-tmp1134_;
double tmp1136_ = (tmp1135_)*(tmp206_);
double tmp1137_ = (tmp1129_)*(tmp201_);
double tmp1138_ = (tmp1110_)*(tmp147_);
double tmp1139_ = (tmp1117_)*(tmp160_);
double tmp1140_ = tmp312_*tmp15_;
double tmp1141_ = tmp1140_*tmp14_;
double tmp1142_ = tmp19_*tmp18_;
double tmp1143_ = tmp1141_+tmp1142_;
double tmp1144_ = (tmp1143_)*(tmp86_);
double tmp1145_ = -(tmp19_);
double tmp1146_ = tmp1145_*tmp14_;
double tmp1147_ = tmp1140_*tmp18_;
double tmp1148_ = tmp1146_+tmp1147_;
double tmp1149_ = tmp1144_+tmp1148_;
double tmp1150_ = (tmp1149_)*(tmp153_);
double tmp1151_ = tmp19_*tmp67_;
double tmp1152_ = tmp1151_*(tmp86_);
double tmp1153_ = tmp1140_*tmp67_;
double tmp1154_ = tmp1152_+tmp1153_;
double tmp1155_ = (tmp1154_)*(tmp172_);
double tmp1156_ = tmp1150_-tmp1155_;
double tmp1157_ = (tmp1156_)*(tmp174_);
double tmp1158_ = (tmp1154_)*(tmp189_);
double tmp1159_ = tmp1140_*tmp177_;
double tmp1160_ = tmp19_*tmp178_;
double tmp1161_ = tmp1159_+tmp1160_;
double tmp1162_ = (tmp1161_)*(tmp86_);
double tmp1163_ = tmp1145_*tmp177_;
double tmp1164_ = tmp1140_*tmp178_;
double tmp1165_ = tmp1163_+tmp1164_;
double tmp1166_ = tmp1162_+tmp1165_;
double tmp1167_ = (tmp1166_)*(tmp153_);
double tmp1168_ = tmp1158_-tmp1167_;
double tmp1169_ = (tmp1168_)*(tmp203_);
double tmp1170_ = (tmp1166_)*(tmp172_);
double tmp1171_ = (tmp1149_)*(tmp189_);
double tmp1172_ = tmp1170_-tmp1171_;
double tmp1173_ = (tmp1172_)*(tmp206_);
double tmp1174_ = (tmp1166_)*(tmp201_);
double tmp1175_ = (tmp1149_)*(tmp147_);
double tmp1176_ = (tmp1154_)*(tmp160_);
double tmp1177_ = tmp312_*(tmp153_);
double tmp1178_ = -(tmp1177_);
double tmp1179_ = tmp312_*(tmp172_);
double tmp1180_ = tmp312_*(tmp189_);
double tmp1181_ = -(tmp1180_);
double tmp1182_ = -(tmp1179_);
double tmp1183_ = tmp312_*tmp111_;
double tmp1184_ = tmp1183_*tmp110_;
double tmp1185_ = tmp1184_+tmp182_;
double tmp1186_ = (tmp1185_)*(tmp132_);
double tmp1187_ = tmp180_+tmp1186_;
double tmp1188_ = tmp1183_*tmp168_;
double tmp1189_ = tmp1188_+tmp187_;
double tmp1190_ = tmp1187_+tmp1189_;
double tmp1191_ = (tmp1190_)*(tmp160_);
double tmp1192_ = -(tmp1191_);
double tmp1193_ = tmp1192_*(tmp174_);
double tmp1194_ = -(tmp133_);
double tmp1195_ = tmp1183_*tmp134_;
double tmp1196_ = tmp1183_*tmp43_;
double tmp1197_ = tmp1196_*(tmp108_);
double tmp1198_ = tmp1194_*tmp110_;
double tmp1199_ = tmp1195_*tmp113_;
double tmp1200_ = tmp1198_+tmp1199_;
double tmp1201_ = (tmp1200_)*(tmp132_);
double tmp1202_ = tmp1197_+tmp1201_;
double tmp1203_ = tmp1194_*tmp168_;
double tmp1204_ = tmp1195_*tmp110_;
double tmp1205_ = tmp1203_+tmp1204_;
double tmp1206_ = tmp1202_+tmp1205_;
double tmp1207_ = (tmp1206_)*(tmp160_);
double tmp1208_ = tmp1207_*(tmp203_);
double tmp1209_ = (tmp1190_)*(tmp201_);
double tmp1210_ = (tmp1206_)*(tmp147_);
double tmp1211_ = tmp1209_-tmp1210_;
double tmp1212_ = (tmp1211_)*(tmp206_);
double tmp1213_ = (tmp1190_)*(tmp209_);
double tmp1214_ = -(tmp1213_);
double tmp1215_ = (tmp1206_)*(tmp209_);
double tmp1216_ = (tmp1190_)*(tmp212_);
double tmp1217_ = (tmp1206_)*(tmp215_);
double tmp1218_ = tmp1216_-tmp1217_;
double tmp1219_ = tmp312_*tmp112_;
double tmp1220_ = -(tmp43_);
double tmp1221_ = tmp1220_*tmp111_;
double tmp1222_ = tmp43_*(tmp108_);
double tmp1223_ = tmp1219_*tmp113_;
double tmp1224_ = tmp1223_*(tmp132_);
double tmp1225_ = tmp1222_+tmp1224_;
double tmp1226_ = tmp1219_*tmp110_;
double tmp1227_ = tmp1225_+tmp1226_;
double tmp1228_ = (tmp1227_)*(tmp147_);
double tmp1229_ = tmp1219_*tmp111_;
double tmp1230_ = tmp1229_*(tmp108_);
double tmp1231_ = tmp1221_*tmp113_;
double tmp1232_ = tmp1231_*(tmp132_);
double tmp1233_ = tmp1230_+tmp1232_;
double tmp1234_ = tmp1221_*tmp110_;
double tmp1235_ = tmp1233_+tmp1234_;
double tmp1236_ = (tmp1235_)*(tmp160_);
double tmp1237_ = tmp1228_-tmp1236_;
double tmp1238_ = (tmp1237_)*(tmp174_);
double tmp1239_ = tmp1220_*tmp133_;
double tmp1240_ = tmp1219_*tmp133_;
double tmp1241_ = tmp1240_*(tmp108_);
double tmp1242_ = tmp1239_*tmp113_;
double tmp1243_ = tmp1242_*(tmp132_);
double tmp1244_ = tmp1241_+tmp1243_;
double tmp1245_ = tmp1239_*tmp110_;
double tmp1246_ = tmp1244_+tmp1245_;
double tmp1247_ = (tmp1246_)*(tmp160_);
double tmp1248_ = (tmp1227_)*(tmp201_);
double tmp1249_ = tmp1247_-tmp1248_;
double tmp1250_ = (tmp1249_)*(tmp203_);
double tmp1251_ = (tmp1235_)*(tmp201_);
double tmp1252_ = (tmp1246_)*(tmp147_);
double tmp1253_ = tmp1251_-tmp1252_;
double tmp1254_ = (tmp1253_)*(tmp206_);
double tmp1255_ = (tmp1227_)*(tmp215_);
double tmp1256_ = (tmp1235_)*(tmp209_);
double tmp1257_ = tmp1255_-tmp1256_;
double tmp1258_ = (tmp1246_)*(tmp209_);
double tmp1259_ = (tmp1227_)*(tmp212_);
double tmp1260_ = tmp1258_-tmp1259_;
double tmp1261_ = (tmp1235_)*(tmp212_);
double tmp1262_ = (tmp1246_)*(tmp215_);
double tmp1263_ = tmp1261_-tmp1262_;
double tmp1264_ = tmp312_*tmp113_;
double tmp1265_ = tmp110_*tmp43_;
double tmp1266_ = tmp1265_*(tmp132_);
double tmp1267_ = tmp1264_*tmp43_;
double tmp1268_ = tmp1266_+tmp1267_;
double tmp1269_ = (tmp1268_)*(tmp147_);
double tmp1270_ = tmp1264_*tmp133_;
double tmp1271_ = tmp110_*tmp135_;
double tmp1272_ = tmp1270_+tmp1271_;
double tmp1273_ = (tmp1272_)*(tmp132_);
double tmp1274_ = -(tmp110_);
double tmp1275_ = tmp1274_*tmp133_;
double tmp1276_ = tmp1264_*tmp135_;
double tmp1277_ = tmp1275_+tmp1276_;
double tmp1278_ = tmp1273_+tmp1277_;
double tmp1279_ = (tmp1278_)*(tmp160_);
double tmp1280_ = tmp1269_-tmp1279_;
double tmp1281_ = (tmp1280_)*(tmp174_);
double tmp1282_ = tmp1264_*tmp175_;
double tmp1283_ = tmp110_*tmp176_;
double tmp1284_ = tmp1282_+tmp1283_;
double tmp1285_ = (tmp1284_)*(tmp132_);
double tmp1286_ = tmp1274_*tmp175_;
double tmp1287_ = tmp1264_*tmp176_;
double tmp1288_ = tmp1286_+tmp1287_;
double tmp1289_ = tmp1285_+tmp1288_;
double tmp1290_ = (tmp1289_)*(tmp160_);
double tmp1291_ = (tmp1268_)*(tmp201_);
double tmp1292_ = tmp1290_-tmp1291_;
double tmp1293_ = (tmp1292_)*(tmp203_);
double tmp1294_ = (tmp1278_)*(tmp201_);
double tmp1295_ = (tmp1289_)*(tmp147_);
double tmp1296_ = tmp1294_-tmp1295_;
double tmp1297_ = (tmp1296_)*(tmp206_);
double tmp1298_ = (tmp1268_)*(tmp215_);
double tmp1299_ = (tmp1278_)*(tmp209_);
double tmp1300_ = tmp1298_-tmp1299_;
double tmp1301_ = (tmp1289_)*(tmp209_);
double tmp1302_ = (tmp1268_)*(tmp212_);
double tmp1303_ = tmp1301_-tmp1302_;
double tmp1304_ = (tmp1278_)*(tmp212_);
double tmp1305_ = (tmp1289_)*(tmp215_);
double tmp1306_ = tmp1304_-tmp1305_;
double tmp1307_ = -(tmp153_);
double tmp1308_ = -(tmp189_);
double tmp1309_ = -(tmp172_);
mVal[0] = (tmp311_)*(tmp301_);
mCompDer[0][0] = ((((0.500000*(tmp253_+tmp253_+tmp267_+tmp267_+tmp275_+tmp275_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp288_+tmp288_+tmp289_+tmp289_+tmp290_+tmp290_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp304_)*(tmp201_)+(tmp262_)*(tmp218_)+(tmp307_)*(tmp147_)+(tmp236_)*(tmp221_)+(tmp310_)*(tmp160_)+(tmp245_)*(tmp224_))*(tmp300_)-(tmp295_)*((tmp304_)*(tmp174_)+(tmp252_)*(tmp218_)+(tmp307_)*(tmp203_)+(tmp266_)*(tmp221_)+(tmp310_)*(tmp206_)+(tmp274_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][1] = ((((0.500000*(tmp326_+tmp326_+tmp336_+tmp336_+tmp344_+tmp344_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp345_+tmp345_+tmp346_+tmp346_+tmp347_+tmp347_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp351_)*(tmp201_)+tmp331_*(tmp218_)+(tmp354_)*(tmp147_)+tmp315_*(tmp221_)+(tmp357_)*(tmp160_)+tmp320_*(tmp224_))*(tmp300_)-(tmp295_)*((tmp351_)*(tmp174_)+(tmp325_)*(tmp218_)+(tmp354_)*(tmp203_)+(tmp335_)*(tmp221_)+(tmp357_)*(tmp206_)+(tmp343_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][2] = ((((0.500000*(tmp370_+tmp370_+tmp380_+tmp380_+tmp388_+tmp388_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp389_+tmp389_+tmp390_+tmp390_+tmp391_+tmp391_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp394_)*(tmp201_)+tmp375_*(tmp218_)+(tmp397_)*(tmp147_)+tmp359_*(tmp221_)+(tmp400_)*(tmp160_)+tmp364_*(tmp224_))*(tmp300_)-(tmp295_)*((tmp394_)*(tmp174_)+(tmp369_)*(tmp218_)+(tmp397_)*(tmp203_)+(tmp379_)*(tmp221_)+(tmp400_)*(tmp206_)+(tmp387_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][3] = ((((0.500000*(tmp416_+tmp416_+tmp426_+tmp426_+tmp434_+tmp434_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp435_+tmp435_+tmp436_+tmp436_+tmp437_+tmp437_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp440_)*(tmp201_)+tmp421_*(tmp218_)+(tmp443_)*(tmp147_)+tmp405_*(tmp221_)+(tmp446_)*(tmp160_)+tmp410_*(tmp224_))*(tmp300_)-(tmp295_)*((tmp440_)*(tmp174_)+(tmp415_)*(tmp218_)+(tmp443_)*(tmp203_)+(tmp425_)*(tmp221_)+(tmp446_)*(tmp206_)+(tmp433_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][4] = ((((0.500000*(tmp462_+tmp462_+tmp472_+tmp472_+tmp480_+tmp480_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp481_+tmp481_+tmp482_+tmp482_+tmp483_+tmp483_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp486_)*(tmp201_)+tmp467_*(tmp218_)+(tmp489_)*(tmp147_)+tmp451_*(tmp221_)+(tmp492_)*(tmp160_)+tmp456_*(tmp224_))*(tmp300_)-(tmp295_)*((tmp486_)*(tmp174_)+(tmp461_)*(tmp218_)+(tmp489_)*(tmp203_)+(tmp471_)*(tmp221_)+(tmp492_)*(tmp206_)+(tmp479_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][5] = ((((0.500000*(tmp508_+tmp508_+tmp518_+tmp518_+tmp526_+tmp526_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp527_+tmp527_+tmp528_+tmp528_+tmp529_+tmp529_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp532_)*(tmp201_)+tmp513_*(tmp218_)+(tmp535_)*(tmp147_)+tmp497_*(tmp221_)+(tmp538_)*(tmp160_)+tmp502_*(tmp224_))*(tmp300_)-(tmp295_)*((tmp532_)*(tmp174_)+(tmp507_)*(tmp218_)+(tmp535_)*(tmp203_)+(tmp517_)*(tmp221_)+(tmp538_)*(tmp206_)+(tmp525_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][6] = ((((0.500000*(tmp554_+tmp554_+tmp564_+tmp564_+tmp572_+tmp572_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp573_+tmp573_+tmp574_+tmp574_+tmp575_+tmp575_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp578_)*(tmp201_)+tmp559_*(tmp218_)+(tmp581_)*(tmp147_)+tmp543_*(tmp221_)+(tmp584_)*(tmp160_)+tmp548_*(tmp224_))*(tmp300_)-(tmp295_)*((tmp578_)*(tmp174_)+(tmp553_)*(tmp218_)+(tmp581_)*(tmp203_)+(tmp563_)*(tmp221_)+(tmp584_)*(tmp206_)+(tmp571_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][7] = ((((0.500000*(tmp600_+tmp600_+tmp610_+tmp610_+tmp618_+tmp618_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp619_+tmp619_+tmp620_+tmp620_+tmp621_+tmp621_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp624_)*(tmp201_)+tmp605_*(tmp218_)+(tmp627_)*(tmp147_)+tmp589_*(tmp221_)+(tmp630_)*(tmp160_)+tmp594_*(tmp224_))*(tmp300_)-(tmp295_)*((tmp624_)*(tmp174_)+(tmp599_)*(tmp218_)+(tmp627_)*(tmp203_)+(tmp609_)*(tmp221_)+(tmp630_)*(tmp206_)+(tmp617_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][8] = ((((0.500000*(tmp646_+tmp646_+tmp656_+tmp656_+tmp664_+tmp664_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp665_+tmp665_+tmp666_+tmp666_+tmp667_+tmp667_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp670_)*(tmp201_)+tmp651_*(tmp218_)+(tmp673_)*(tmp147_)+tmp635_*(tmp221_)+(tmp676_)*(tmp160_)+tmp640_*(tmp224_))*(tmp300_)-(tmp295_)*((tmp670_)*(tmp174_)+(tmp645_)*(tmp218_)+(tmp673_)*(tmp203_)+(tmp655_)*(tmp221_)+(tmp676_)*(tmp206_)+(tmp663_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][9] = ((((0.500000*(tmp692_+tmp692_+tmp702_+tmp702_+tmp710_+tmp710_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp711_+tmp711_+tmp712_+tmp712_+tmp713_+tmp713_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp716_)*(tmp201_)+tmp697_*(tmp218_)+(tmp719_)*(tmp147_)+tmp681_*(tmp221_)+(tmp722_)*(tmp160_)+tmp686_*(tmp224_))*(tmp300_)-(tmp295_)*((tmp716_)*(tmp174_)+(tmp691_)*(tmp218_)+(tmp719_)*(tmp203_)+(tmp701_)*(tmp221_)+(tmp722_)*(tmp206_)+(tmp709_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][10] = ((((0.500000*(tmp734_+tmp734_+tmp744_+tmp744_+tmp752_+tmp752_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp753_+tmp753_+tmp754_+tmp754_+tmp755_+tmp755_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp758_)*(tmp201_)+tmp739_*(tmp218_)+(tmp761_)*(tmp147_)+tmp723_*(tmp221_)+(tmp764_)*(tmp160_)+tmp728_*(tmp224_))*(tmp300_)-(tmp295_)*((tmp758_)*(tmp174_)+(tmp733_)*(tmp218_)+(tmp761_)*(tmp203_)+(tmp743_)*(tmp221_)+(tmp764_)*(tmp206_)+(tmp751_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][11] = ((((0.500000*(tmp780_+tmp780_+tmp790_+tmp790_+tmp798_+tmp798_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp799_+tmp799_+tmp800_+tmp800_+tmp801_+tmp801_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp804_)*(tmp201_)+tmp785_*(tmp218_)+(tmp807_)*(tmp147_)+tmp769_*(tmp221_)+(tmp810_)*(tmp160_)+tmp774_*(tmp224_))*(tmp300_)-(tmp295_)*((tmp804_)*(tmp174_)+(tmp779_)*(tmp218_)+(tmp807_)*(tmp203_)+(tmp789_)*(tmp221_)+(tmp810_)*(tmp206_)+(tmp797_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][12] = ((((0.500000*(tmp822_+tmp822_+tmp832_+tmp832_+tmp840_+tmp840_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp841_+tmp841_+tmp842_+tmp842_+tmp843_+tmp843_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp846_)*(tmp201_)+tmp827_*(tmp218_)+(tmp849_)*(tmp147_)+tmp811_*(tmp221_)+(tmp852_)*(tmp160_)+tmp816_*(tmp224_))*(tmp300_)-(tmp295_)*((tmp846_)*(tmp174_)+(tmp821_)*(tmp218_)+(tmp849_)*(tmp203_)+(tmp831_)*(tmp221_)+(tmp852_)*(tmp206_)+(tmp839_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][13] = ((((0.500000*(tmp864_+tmp864_+tmp874_+tmp874_+tmp882_+tmp882_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp883_+tmp883_+tmp884_+tmp884_+tmp885_+tmp885_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp888_)*(tmp201_)+tmp869_*(tmp218_)+(tmp891_)*(tmp147_)+tmp853_*(tmp221_)+(tmp894_)*(tmp160_)+tmp858_*(tmp224_))*(tmp300_)-(tmp295_)*((tmp888_)*(tmp174_)+(tmp863_)*(tmp218_)+(tmp891_)*(tmp203_)+(tmp873_)*(tmp221_)+(tmp894_)*(tmp206_)+(tmp881_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][14] = ((((0.500000*(tmp906_+tmp906_+tmp916_+tmp916_+tmp924_+tmp924_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp925_+tmp925_+tmp926_+tmp926_+tmp927_+tmp927_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp930_)*(tmp201_)+tmp911_*(tmp218_)+(tmp933_)*(tmp147_)+tmp895_*(tmp221_)+(tmp936_)*(tmp160_)+tmp900_*(tmp224_))*(tmp300_)-(tmp295_)*((tmp930_)*(tmp174_)+(tmp905_)*(tmp218_)+(tmp933_)*(tmp203_)+(tmp915_)*(tmp221_)+(tmp936_)*(tmp206_)+(tmp923_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][15] = ((((0.500000*(tmp968_+tmp968_+tmp982_+tmp982_+tmp990_+tmp990_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp991_+tmp991_+tmp992_+tmp992_+tmp993_+tmp993_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp996_)*(tmp201_)+(tmp977_)*(tmp218_)+(tmp999_)*(tmp147_)+(tmp951_)*(tmp221_)+(tmp1002_)*(tmp160_)+(tmp960_)*(tmp224_))*(tmp300_)-(tmp295_)*((tmp996_)*(tmp174_)+(tmp967_)*(tmp218_)+(tmp999_)*(tmp203_)+(tmp981_)*(tmp221_)+(tmp1002_)*(tmp206_)+(tmp989_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][16] = ((((0.500000*(tmp1034_+tmp1034_+tmp1048_+tmp1048_+tmp1056_+tmp1056_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp1057_+tmp1057_+tmp1058_+tmp1058_+tmp1059_+tmp1059_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp1062_)*(tmp201_)+(tmp1043_)*(tmp218_)+(tmp1065_)*(tmp147_)+(tmp1017_)*(tmp221_)+(tmp1068_)*(tmp160_)+(tmp1026_)*(tmp224_))*(tmp300_)-(tmp295_)*((tmp1062_)*(tmp174_)+(tmp1033_)*(tmp218_)+(tmp1065_)*(tmp203_)+(tmp1047_)*(tmp221_)+(tmp1068_)*(tmp206_)+(tmp1055_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][17] = ((((0.500000*(tmp1078_+tmp1078_+tmp1094_+tmp1094_+tmp1098_+tmp1098_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp1099_+tmp1099_+tmp1100_+tmp1100_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp1091_)*(tmp218_)+(tmp1076_)*(tmp221_))*(tmp300_)-(tmp295_)*(tmp1077_*(tmp218_)+tmp1093_*(tmp221_)+(tmp1097_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][18] = ((((0.500000*(tmp1120_+tmp1120_+tmp1132_+tmp1132_+tmp1136_+tmp1136_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp1137_+tmp1137_+tmp1138_+tmp1138_+tmp1139_+tmp1139_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp1129_)*(tmp218_)+(tmp1110_)*(tmp221_)+(tmp1117_)*(tmp224_))*(tmp300_)-(tmp295_)*((tmp1119_)*(tmp218_)+(tmp1131_)*(tmp221_)+(tmp1135_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][19] = ((((0.500000*(tmp1157_+tmp1157_+tmp1169_+tmp1169_+tmp1173_+tmp1173_))/tmp281_)*tmp287_-tmp281_*((0.500000*(tmp1174_+tmp1174_+tmp1175_+tmp1175_+tmp1176_+tmp1176_))/tmp287_))/tmp348_)*(tmp301_)+((((tmp1166_)*(tmp218_)+(tmp1149_)*(tmp221_)+(tmp1154_)*(tmp224_))*(tmp300_)-(tmp295_)*((tmp1156_)*(tmp218_)+(tmp1168_)*(tmp221_)+(tmp1172_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][20] = (((tmp1178_*(tmp147_)+tmp1179_*(tmp160_))*(tmp300_)-(tmp295_)*(tmp1178_*(tmp203_)+tmp1179_*(tmp206_)))/tmp358_)*(tmp311_);
mCompDer[0][21] = (((tmp1177_*(tmp201_)+tmp1181_*(tmp160_))*(tmp300_)-(tmp295_)*(tmp1177_*(tmp174_)+tmp1181_*(tmp206_)))/tmp358_)*(tmp311_);
mCompDer[0][22] = (((tmp1182_*(tmp201_)+tmp1180_*(tmp147_))*(tmp300_)-(tmp295_)*(tmp1182_*(tmp174_)+tmp1180_*(tmp203_)))/tmp358_)*(tmp311_);
mCompDer[0][23] = ((((0.500000*(tmp1193_+tmp1193_+tmp1208_+tmp1208_+tmp1212_+tmp1212_))/tmp281_)*tmp287_)/tmp348_)*(tmp301_)+(((tmp1214_*(tmp201_)+tmp1215_*(tmp147_)+(tmp1218_)*(tmp160_))*(tmp300_)-(tmp295_)*(tmp1214_*(tmp174_)+tmp1192_*(tmp218_)+tmp1215_*(tmp203_)+tmp1207_*(tmp221_)+(tmp1218_)*(tmp206_)+(tmp1211_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][24] = ((((0.500000*(tmp1238_+tmp1238_+tmp1250_+tmp1250_+tmp1254_+tmp1254_))/tmp281_)*tmp287_)/tmp348_)*(tmp301_)+((((tmp1257_)*(tmp201_)+(tmp1260_)*(tmp147_)+(tmp1263_)*(tmp160_))*(tmp300_)-(tmp295_)*((tmp1257_)*(tmp174_)+(tmp1237_)*(tmp218_)+(tmp1260_)*(tmp203_)+(tmp1249_)*(tmp221_)+(tmp1263_)*(tmp206_)+(tmp1253_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][25] = ((((0.500000*(tmp1281_+tmp1281_+tmp1293_+tmp1293_+tmp1297_+tmp1297_))/tmp281_)*tmp287_)/tmp348_)*(tmp301_)+((((tmp1300_)*(tmp201_)+(tmp1303_)*(tmp147_)+(tmp1306_)*(tmp160_))*(tmp300_)-(tmp295_)*((tmp1300_)*(tmp174_)+(tmp1280_)*(tmp218_)+(tmp1303_)*(tmp203_)+(tmp1292_)*(tmp221_)+(tmp1306_)*(tmp206_)+(tmp1296_)*(tmp224_)))/tmp358_)*(tmp311_);
mCompDer[0][26] = (((tmp1307_*(tmp147_)+(tmp172_)*(tmp160_))*(tmp300_)-(tmp295_)*(tmp1307_*(tmp203_)+(tmp172_)*(tmp206_)))/tmp358_)*(tmp311_);
mCompDer[0][27] = ((((tmp153_)*(tmp201_)+tmp1308_*(tmp160_))*(tmp300_)-(tmp295_)*((tmp153_)*(tmp174_)+tmp1308_*(tmp206_)))/tmp358_)*(tmp311_);
mCompDer[0][28] = (((tmp1309_*(tmp201_)+(tmp189_)*(tmp147_))*(tmp300_)-(tmp295_)*(tmp1309_*(tmp174_)+(tmp189_)*(tmp203_)))/tmp358_)*(tmp311_);
}
void cEqResiduIm1DCBrownId::ComputeValDerivHessian()
{
ELISE_ASSERT(false,"Foncteur cEqResiduIm1DCBrownId Has no Der Sec");
}
void cEqResiduIm1DCBrownId::SetDCBrown_State_0_0(double aVal){ mLocDCBrown_State_0_0 = aVal;}
void cEqResiduIm1DCBrownId::SetDCBrown_State_0_1(double aVal){ mLocDCBrown_State_0_1 = aVal;}
void cEqResiduIm1DCBrownId::SetXL1(double aVal){ mLocXL1 = aVal;}
void cEqResiduIm1DCBrownId::SetXL2(double aVal){ mLocXL2 = aVal;}
void cEqResiduIm1DCBrownId::SetYL1(double aVal){ mLocYL1 = aVal;}
void cEqResiduIm1DCBrownId::SetYL2(double aVal){ mLocYL2 = aVal;}
double * cEqResiduIm1DCBrownId::AdrVarLocFromString(const std::string & aName)
{
if (aName == "DCBrown_State_0_0") return & mLocDCBrown_State_0_0;
if (aName == "DCBrown_State_0_1") return & mLocDCBrown_State_0_1;
if (aName == "XL1") return & mLocXL1;
if (aName == "XL2") return & mLocXL2;
if (aName == "YL1") return & mLocYL1;
if (aName == "YL2") return & mLocYL2;
return 0;
}
cElCompiledFonc::cAutoAddEntry cEqResiduIm1DCBrownId::mTheAuto("cEqResiduIm1DCBrownId",cEqResiduIm1DCBrownId::Alloc);
cElCompiledFonc * cEqResiduIm1DCBrownId::Alloc()
{ return new cEqResiduIm1DCBrownId();
}
| 33,297 |
2,542 |
//+---------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
//----------------------------------------------------------------------------
#pragma once
namespace Management
{
namespace LocalSecretService
{
class LocalSecretServiceInstance :
public IFabricStatelessServiceInstance,
private ComUnknownBase
{
DENY_COPY(LocalSecretServiceInstance)
BEGIN_COM_INTERFACE_LIST(LocalSecretServiceInstance)
COM_INTERFACE_ITEM(IID_IUnknown, IFabricStatelessServiceInstance)
COM_INTERFACE_ITEM(IID_IFabricStatelessServiceInstance, IFabricStatelessServiceInstance)
END_COM_INTERFACE_LIST()
public:
LocalSecretServiceInstance();
~LocalSecretServiceInstance();
// IFabricStatelessServiceInstance Impl.
virtual HRESULT BeginOpen(
__in IFabricStatelessServicePartition* partition,
__in IFabricAsyncOperationCallback* callback,
__out IFabricAsyncOperationContext** context
) override;
virtual HRESULT EndOpen(
__in IFabricAsyncOperationContext* context,
__out IFabricStringResult** serviceAddress
) override;
virtual HRESULT BeginClose(
__in IFabricAsyncOperationCallback* callback,
__out IFabricAsyncOperationContext** context
) override;
virtual HRESULT EndClose(
__in IFabricAsyncOperationContext* context
) override;
virtual void Abort(void) override;
};
}
}
| 714 |
1,603 |
<filename>metadata-io/src/test/java/com/linkedin/metadata/search/elasticsearch/query/request/AutocompleteRequestHandlerTest.java
package com.linkedin.metadata.search.elasticsearch.query.request;
import com.linkedin.metadata.TestEntitySpecBuilder;
import java.util.List;
import java.util.Map;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class AutocompleteRequestHandlerTest {
private AutocompleteRequestHandler handler = AutocompleteRequestHandler.getBuilder(TestEntitySpecBuilder.getSpec());
@Test
public void testDefaultAutocompleteRequest() {
// When field is null
SearchRequest autocompleteRequest = handler.getSearchRequest("input", null, null, 10);
SearchSourceBuilder sourceBuilder = autocompleteRequest.source();
assertEquals(sourceBuilder.size(), 10);
BoolQueryBuilder query = (BoolQueryBuilder) sourceBuilder.query();
assertEquals(query.must().size(), 1);
QueryStringQueryBuilder autocompleteQuery = (QueryStringQueryBuilder) query.must().get(0);
Map<String, Float> queryFields = autocompleteQuery.fields();
assertTrue(queryFields.containsKey("keyPart1"));
assertTrue(queryFields.containsKey("keyPart1.ngram"));
assertEquals(autocompleteQuery.analyzer(), "word_delimited");
assertEquals(autocompleteQuery.defaultOperator(), Operator.AND);
assertEquals(query.mustNot().size(), 1);
MatchQueryBuilder removedFilter = (MatchQueryBuilder) query.mustNot().get(0);
assertEquals(removedFilter.fieldName(), "removed");
assertEquals(removedFilter.value(), true);
HighlightBuilder highlightBuilder = sourceBuilder.highlighter();
List<HighlightBuilder.Field> highlightedFields = highlightBuilder.fields();
assertEquals(highlightedFields.size(), 2);
assertEquals(highlightedFields.get(0).name(), "keyPart1");
assertEquals(highlightedFields.get(1).name(), "keyPart1.*");
}
@Test
public void testAutocompleteRequestWithField() {
// When field is null
SearchRequest autocompleteRequest = handler.getSearchRequest("input", "field", null, 10);
SearchSourceBuilder sourceBuilder = autocompleteRequest.source();
assertEquals(sourceBuilder.size(), 10);
BoolQueryBuilder query = (BoolQueryBuilder) sourceBuilder.query();
assertEquals(query.must().size(), 1);
QueryStringQueryBuilder autocompleteQuery = (QueryStringQueryBuilder) query.must().get(0);
Map<String, Float> queryFields = autocompleteQuery.fields();
assertTrue(queryFields.containsKey("field"));
assertTrue(queryFields.containsKey("field.ngram"));
assertEquals(autocompleteQuery.analyzer(), "word_delimited");
assertEquals(autocompleteQuery.defaultOperator(), Operator.AND);
MatchQueryBuilder removedFilter = (MatchQueryBuilder) query.mustNot().get(0);
assertEquals(removedFilter.fieldName(), "removed");
assertEquals(removedFilter.value(), true);
HighlightBuilder highlightBuilder = sourceBuilder.highlighter();
List<HighlightBuilder.Field> highlightedFields = highlightBuilder.fields();
assertEquals(highlightedFields.size(), 2);
assertEquals(highlightedFields.get(0).name(), "field");
assertEquals(highlightedFields.get(1).name(), "field.*");
}
}
| 1,147 |
496 |
<reponame>huangjd/simit-staging<gh_stars>100-1000
#ifndef REWRITE_SYSTEM_ASSIGN_H
#define REWRITE_SYSTEM_ASSIGN_H
#include "ir.h"
namespace simit {
namespace ir {
Func rewriteSystemAssigns(Func func);
}} // namespace simit::ir
#endif
| 103 |
5,023 |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from clusterfuzz._internal.protos import heartbeat_pb2 as clusterfuzz_dot___internal_dot_protos_dot_heartbeat__pb2
class HeartbeatStub(object):
"""Service for receiving hearbeats.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.Beat = channel.unary_unary(
'/Heartbeat/Beat',
request_serializer=clusterfuzz_dot___internal_dot_protos_dot_heartbeat__pb2.HeartbeatRequest.SerializeToString,
response_deserializer=clusterfuzz_dot___internal_dot_protos_dot_heartbeat__pb2.HeartbeatResponse.FromString,
)
class HeartbeatServicer(object):
"""Service for receiving hearbeats.
"""
def Beat(self, request, context):
"""Send a beat.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_HeartbeatServicer_to_server(servicer, server):
rpc_method_handlers = {
'Beat': grpc.unary_unary_rpc_method_handler(
servicer.Beat,
request_deserializer=clusterfuzz_dot___internal_dot_protos_dot_heartbeat__pb2.HeartbeatRequest.FromString,
response_serializer=clusterfuzz_dot___internal_dot_protos_dot_heartbeat__pb2.HeartbeatResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'Heartbeat', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class Heartbeat(object):
"""Service for receiving hearbeats.
"""
@staticmethod
def Beat(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/Heartbeat/Beat',
clusterfuzz_dot___internal_dot_protos_dot_heartbeat__pb2.HeartbeatRequest.SerializeToString,
clusterfuzz_dot___internal_dot_protos_dot_heartbeat__pb2.HeartbeatResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
| 1,262 |
446 |
"""
README
======
This file contains Python codes.
======
"""
import numpy as np
import scipy.stats as stats
import pythoncom
class BlackScholes:
_public_methods_ = ["call_pricer", "put_pricer"]
_reg_progid_ = "BlackScholes.Pricer"
_reg_clsid_ = pythoncom.CreateGuid()
def d1(self, S0, K, r, T, sigma, div):
return (np.log(S0/K) + ((r-div) + sigma**2 / 2) * T)/ \
(sigma * np.sqrt(T))
def d2(self, S0, K, r, T, sigma, div):
return (np.log(S0 / K) + ((r-div) - sigma**2 / 2) * T) / \
(sigma * np.sqrt(T))
def call_pricer(self, S0, K, r, T, sigma, div):
d1 = self.d1(S0, K, r, T, sigma, div)
d2 = self.d2(S0, K, r, T, sigma, div)
return S0 * np.exp(-div * T) * stats.norm.cdf(d1) \
- K * np.exp(-r * T) * stats.norm.cdf(d2)
def put_pricer(self, S0, K, r, T, sigma, div):
d1 = self.d1(S0, K, r, T, sigma, div)
d2 = self.d2(S0, K, r, T, sigma, div)
return K * np.exp(-r * T) * stats.norm.cdf(-d2) \
- S0 * np.exp(-div * T) *stats.norm.cdf(-d1)
if __name__ == "__main__":
# Run "python binomial_tree_am.py"
# to register the COM server.
# Run "python binomial_tree_am.py --unregister"
# to unregister it.
print "Registering COM server..."
import win32com.server.register
win32com.server.register.UseCommandLine(BlackScholes)
| 758 |
640 |
<gh_stars>100-1000
"""
"""
# Created on 2015.07.09
#
# Author: <NAME>
#
# Copyright 2015 - 2020 <NAME>
#
# This file is part of ldap3.
#
# ldap3 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ldap3 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with ldap3 in the COPYING and COPYING.LESSER files.
# If not, see <http://www.gnu.org/licenses/>.
from binascii import hexlify
from .. import STRING_TYPES
try:
from sys import stdout
repr_encoding = stdout.encoding # get the encoding of the stdout for printing (repr)
if not repr_encoding:
repr_encoding = 'ascii' # default
except Exception:
repr_encoding = 'ascii' # default
def to_stdout_encoding(value):
if not isinstance(value, STRING_TYPES):
value = str(value)
if str is bytes: # Python 2
try:
return value.encode(repr_encoding, 'backslashreplace')
except UnicodeDecodeError: # Python 2.6
return hexlify(value)
else: # Python 3
try:
return value.encode(repr_encoding, errors='backslashreplace').decode(repr_encoding, errors='backslashreplace')
except UnicodeDecodeError:
return hexlify(value)
| 650 |
372 |
<reponame>mjhopkins/google-api-java-client-services
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.appengine.v1.model;
/**
* Target scaling by disk usage. Only applicable in the App Engine flexible environment.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the App Engine Admin API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class DiskUtilization extends com.google.api.client.json.GenericJson {
/**
* Target bytes read per second.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer targetReadBytesPerSecond;
/**
* Target ops read per seconds.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer targetReadOpsPerSecond;
/**
* Target bytes written per second.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer targetWriteBytesPerSecond;
/**
* Target ops written per second.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer targetWriteOpsPerSecond;
/**
* Target bytes read per second.
* @return value or {@code null} for none
*/
public java.lang.Integer getTargetReadBytesPerSecond() {
return targetReadBytesPerSecond;
}
/**
* Target bytes read per second.
* @param targetReadBytesPerSecond targetReadBytesPerSecond or {@code null} for none
*/
public DiskUtilization setTargetReadBytesPerSecond(java.lang.Integer targetReadBytesPerSecond) {
this.targetReadBytesPerSecond = targetReadBytesPerSecond;
return this;
}
/**
* Target ops read per seconds.
* @return value or {@code null} for none
*/
public java.lang.Integer getTargetReadOpsPerSecond() {
return targetReadOpsPerSecond;
}
/**
* Target ops read per seconds.
* @param targetReadOpsPerSecond targetReadOpsPerSecond or {@code null} for none
*/
public DiskUtilization setTargetReadOpsPerSecond(java.lang.Integer targetReadOpsPerSecond) {
this.targetReadOpsPerSecond = targetReadOpsPerSecond;
return this;
}
/**
* Target bytes written per second.
* @return value or {@code null} for none
*/
public java.lang.Integer getTargetWriteBytesPerSecond() {
return targetWriteBytesPerSecond;
}
/**
* Target bytes written per second.
* @param targetWriteBytesPerSecond targetWriteBytesPerSecond or {@code null} for none
*/
public DiskUtilization setTargetWriteBytesPerSecond(java.lang.Integer targetWriteBytesPerSecond) {
this.targetWriteBytesPerSecond = targetWriteBytesPerSecond;
return this;
}
/**
* Target ops written per second.
* @return value or {@code null} for none
*/
public java.lang.Integer getTargetWriteOpsPerSecond() {
return targetWriteOpsPerSecond;
}
/**
* Target ops written per second.
* @param targetWriteOpsPerSecond targetWriteOpsPerSecond or {@code null} for none
*/
public DiskUtilization setTargetWriteOpsPerSecond(java.lang.Integer targetWriteOpsPerSecond) {
this.targetWriteOpsPerSecond = targetWriteOpsPerSecond;
return this;
}
@Override
public DiskUtilization set(String fieldName, Object value) {
return (DiskUtilization) super.set(fieldName, value);
}
@Override
public DiskUtilization clone() {
return (DiskUtilization) super.clone();
}
}
| 1,336 |
623 |
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2017 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.extension.replacer;
import java.awt.Window;
import org.parosproxy.paros.Constant;
public class ReplaceRuleModifyDialog extends ReplaceRuleAddDialog {
private static final long serialVersionUID = 1L;
private String originalDesc;
public ReplaceRuleModifyDialog(
Window owner,
String title,
ReplacerParam replacerParam,
OptionsReplacerTableModel replacerModel) {
super(owner, title, replacerParam, replacerModel);
}
@Override
public void setRule(ReplacerParamRule rule) {
super.setRule(rule);
if (originalDesc == null) {
originalDesc = rule.getDescription();
}
}
@Override
public void cancelPressed() {
super.cancelPressed();
originalDesc = null;
}
@Override
public void save() {
super.save();
originalDesc = null;
}
@Override
protected String checkIfUnique() {
String newDesc = this.getStringValue(DESC_FIELD);
if (!newDesc.equals(originalDesc)) {
// Its been changed, check the new one is unique
if (this.getReplacerModel().containsRule(newDesc)) {
return Constant.messages.getString("replacer.add.warning.existdesc");
}
}
return null;
}
}
| 749 |
2,151 |
<reponame>Scopetta197/chromium
#ifndef UTIL_RINGBUFFER_H
#define UTIL_RINGBUFFER_H
#include "pipe/p_compiler.h"
#include "pipe/p_defines.h" /* only for pipe_error! */
/* Generic header
*/
struct util_packet {
unsigned dwords:8;
unsigned data24:24;
};
struct util_ringbuffer;
struct util_ringbuffer *util_ringbuffer_create( unsigned dwords );
void util_ringbuffer_destroy( struct util_ringbuffer *ring );
void util_ringbuffer_enqueue( struct util_ringbuffer *ring,
const struct util_packet *packet );
enum pipe_error util_ringbuffer_dequeue( struct util_ringbuffer *ring,
struct util_packet *packet,
unsigned max_dwords,
boolean wait );
#endif
| 386 |
574 |
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazon.opendistroforelasticsearch.sql.legacy.query.planner.core;
import com.amazon.opendistroforelasticsearch.sql.legacy.executor.format.Schema;
import com.amazon.opendistroforelasticsearch.sql.legacy.expression.core.Expression;
import com.google.common.base.Strings;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* The definition of column node.
*/
@Builder
@Setter
@Getter
@ToString
public class ColumnNode {
private String name;
private String alias;
private Schema.Type type;
private Expression expr;
public String columnName() {
return Strings.isNullOrEmpty(alias) ? name : alias;
}
}
| 416 |
12,278 |
<filename>3rdParty/boost/1.71.0/libs/mpi/test/cartesian_topology_init_test.cpp
// Copyright <NAME> 2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Authors: <NAME>
#include <vector>
#include <list>
#include <iostream>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <functional>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi/collectives.hpp>
#include <boost/array.hpp>
#include <boost/mpi/environment.hpp>
#include <boost/mpi/cartesian_communicator.hpp>
#define BOOST_TEST_MODULE mpi_cartesian_topology_init
#include <boost/test/included/unit_test.hpp>
namespace mpi = boost::mpi;
BOOST_AUTO_TEST_CASE(cartesian_dimension_init)
{
// Curly brace initialization syntax not supported on (very) old gnu
// This typedef keeps things shorter
typedef mpi::cartesian_dimension cd;
{
// Check the basic ctor
mpi::cartesian_dimension def;
mpi::cartesian_topology t1(10);
BOOST_CHECK(t1.stl() == std::vector<mpi::cartesian_dimension>(10, def));
}
#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
{
// Intializer list ctor vs range based
int dims[] = {2,3,4};
bool per[] = {true, false, true};
mpi::cartesian_topology t1(dims, per);
mpi::cartesian_topology t2({{2,true},{3, false},{4, true}});
BOOST_CHECK(t1.size() == 3);
BOOST_CHECK(t1 == t2);
}
#endif
// Container based ctor only available as a replacement for initializer list ctor
{
// seq ctor vs C array ctor
mpi::cartesian_dimension d[] = {cd(2,true),cd(3, false),cd(4, true)};
std::list<mpi::cartesian_dimension> seq;
std::copy(d, d+3, std::back_inserter(seq));
mpi::cartesian_topology t1(seq);
mpi::cartesian_topology t2(d);
BOOST_CHECK(t1 == t2);
}
{
// Check range based with array based ctor.
boost::array<mpi::cartesian_dimension, 3> d = {{cd(2,true),cd(3, false),cd(4, true)}};
int dims[] = {2,3,4};
bool per[] = {true, false, true};
mpi::cartesian_topology t1(dims, per);
mpi::cartesian_topology t2(d);
BOOST_CHECK(t1.size() == 3);
BOOST_CHECK(t1 == t2);
}
{
// Iterator based ctor vs C array based ctor
mpi::cartesian_dimension d[] = {cd(2,true),cd(3, false),cd(4, true)};
std::vector<mpi::cartesian_dimension> vdims(d, d+3);
mpi::cartesian_topology t1(vdims);
mpi::cartesian_topology t2(d);
BOOST_CHECK(t1.size() == 3);
BOOST_CHECK(t1 == t2);
BOOST_CHECK(!(t1 != t2));
t1[1].periodic = true;
BOOST_CHECK(t1 != t2);
t1[2].periodic = false;
t1[2].size = 0;
vdims.push_back(mpi::cartesian_dimension(3, false));
mpi::cartesian_topology t3(vdims);
BOOST_CHECK(t1 != t3);
}
}
| 1,219 |
471 |
<reponame>andyasne/commcare-hq
import uuid
from django.test import Client, TestCase
from django.urls import reverse
from corehq.apps.data_dictionary.models import CaseProperty, CaseType
from corehq.apps.domain.shortcuts import create_domain
from corehq.apps.users.models import WebUser
from corehq.util.test_utils import flag_enabled
@flag_enabled('DATA_DICTIONARY')
class UpdateCasePropertyViewTest(TestCase):
domain_name = uuid.uuid4().hex
@classmethod
def setUpClass(cls):
super(UpdateCasePropertyViewTest, cls).setUpClass()
cls.domain = create_domain(cls.domain_name)
cls.couch_user = WebUser.create(None, "test", "foobar", None, None)
cls.couch_user.add_domain_membership(cls.domain_name, is_admin=True)
cls.couch_user.save()
cls.case_type_obj = CaseType(name='caseType', domain=cls.domain_name)
cls.case_type_obj.save()
CaseProperty(case_type=cls.case_type_obj, name='property').save()
@classmethod
def tearDownClass(cls):
cls.case_type_obj.delete()
cls.couch_user.delete(cls.domain_name, deleted_by=None)
cls.domain.delete()
super(UpdateCasePropertyViewTest, cls).tearDownClass()
def setUp(self):
self.url = reverse('update_case_property', args=[self.domain_name])
self.client = Client()
self.client.login(username='test', password='<PASSWORD>')
def _get_property(self):
return CaseProperty.objects.filter(
case_type=self.case_type_obj,
name='property'
).first()
def _assert_type(self, value=''):
prop = self._get_property()
self.assertEqual(prop.data_type, value)
def _get_case_property(self, name, case_type):
return CaseProperty.objects.filter(
case_type__name=case_type,
name=name
).first()
def test_new_case_type(self):
self._assert_type()
post_data = {"properties": '[{"caseType": "somethingelse", "name": "property", "data_type": "date"}]'}
response = self.client.post(self.url, post_data)
self.assertEqual(response.status_code, 200)
prop = self._get_case_property(name="property", case_type="somethingelse")
self.assertEqual(prop.data_type, 'date')
def test_new_case_property(self):
self._assert_type()
post_data = {"properties": '[{"caseType": "caseType", "name": "otherproperty", "data_type": "date"}]'}
response = self.client.post(self.url, post_data)
self.assertEqual(response.status_code, 200)
prop = self._get_case_property(name="otherproperty", case_type="caseType")
self.assertEqual(prop.data_type, 'date')
def test_update_with_incorrect_data_type(self):
self._assert_type()
post_data = {"properties": '[{"caseType": "caseType", "name": "property", "data_type": "blah"}]'}
response = self.client.post(self.url, post_data)
self.assertEqual(response.status_code, 400)
self._assert_type()
def test_update_no_name(self):
self._assert_type()
post_data = {"properties": '[{"caseType": "caseType", "name": "", "data_type": "date"}]'}
response = self.client.post(self.url, post_data)
self.assertEqual(response.status_code, 400)
self._assert_type()
def test_update_of_correct_data_type(self):
self._assert_type()
post_data = {"properties": '[{"caseType": "caseType", "name": "property", "data_type": "date"}]'}
response = self.client.post(self.url, post_data)
self.assertEqual(response.status_code, 200)
self._assert_type('date')
def test_update_description(self):
prop = self._get_property()
self.assertEqual(prop.description, '')
post_data = {"properties": '[{"caseType": "caseType", "name": "property", "description": "description"}]'}
response = self.client.post(self.url, post_data)
self.assertEqual(response.status_code, 200)
prop = self._get_property()
self.assertEqual(prop.description, 'description')
| 1,691 |
1,648 |
static inline int computeSignal (context frame)
{
return 0;
}
static inline void clear_thread_stepping(thread t)
{
}
static inline void set_thread_stepping(thread t)
{
}
static inline int get_register(u64 num, void *buf, context c)
{
return -1;
}
static boolean set_thread_register(thread t, int regno, u64 val)
{
return false;
}
static inline void set_thread_pc(thread t, u64 addr)
{
}
static inline void read_registers(buffer b, thread t)
{
}
static inline void write_registers(buffer b, thread t)
{
}
static inline void set_write_protect(boolean enable)
{
}
boolean breakpoint_insert(heap h, u64 a, u8 type, u8 log_length, thunk completion)
{
return false;
}
boolean breakpoint_remove(heap h, u32 a, thunk completion)
{
return false;
}
| 280 |
328 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#pragma once
#include "stdafx.h"
using namespace std;
typedef NTSTATUS(__stdcall *_NtCreateFile)(
PHANDLE FileHandle,
ACCESS_MASK DesiredAccess,
POBJECT_ATTRIBUTES ObjectAttributes,
PIO_STATUS_BLOCK IoStatusBlock,
PLARGE_INTEGER AllocationSize,
ULONG FileAttributes,
ULONG ShareAccess,
ULONG CreateDisposition,
ULONG CreateOptions,
PVOID EaBuffer,
ULONG EaLength);
typedef NTSTATUS(__stdcall *_NtClose)(HANDLE FileHandle);
typedef VOID(__stdcall *_RtlInitUnicodeString)(
PUNICODE_STRING DestinationString,
PCWSTR SourceString);
#define InitializeObjectAttributes( i, o, a, r, s ) { \
(i)->Length = sizeof( OBJECT_ATTRIBUTES ); \
(i)->RootDirectory = r; \
(i)->Attributes = a; \
(i)->ObjectName = o; \
(i)->SecurityDescriptor = s; \
(i)->SecurityQualityOfService = NULL; \
}
typedef enum _FILE_INFORMATION_CLASS_EXTRA {
FileFullDirectoryInformation = 2,
FileBothDirectoryInformation,
FileBasicInformation,
FileStandardInformation,
FileInternalInformation,
FileEaInformation,
FileAccessInformation,
FileNameInformation,
FileRenameInformation,
FileLinkInformation,
FileNamesInformation,
FileDispositionInformation,
FilePositionInformation,
FileFullEaInformation,
FileModeInformation,
FileAlignmentInformation,
FileAllInformation,
FileAllocationInformation,
FileEndOfFileInformation,
FileAlternateNameInformation,
FileStreamInformation,
FilePipeInformation,
FilePipeLocalInformation,
FilePipeRemoteInformation,
FileMailslotQueryInformation,
FileMailslotSetInformation,
FileCompressionInformation,
FileObjectIdInformation,
FileCompletionInformation,
FileMoveClusterInformation,
FileQuotaInformation,
FileReparsePointInformation,
FileNetworkOpenInformation,
FileAttributeTagInformation,
FileTrackingInformation,
FileIdBothDirectoryInformation,
FileIdFullDirectoryInformation,
FileValidDataLengthInformation,
FileShortNameInformation,
FileIoCompletionNotificationInformation,
FileIoStatusBlockRangeInformation,
FileIoPriorityHintInformation,
FileSfioReserveInformation,
FileSfioVolumeInformation,
FileHardLinkInformation,
FileProcessIdsUsingFileInformation,
FileNormalizedNameInformation,
FileNetworkPhysicalNameInformation,
FileIdGlobalTxDirectoryInformation,
FileIsRemoteDeviceInformation,
FileUnusedInformation,
FileNumaNodeInformation,
FileStandardLinkInformation,
FileRemoteProtocolInformation,
FileRenameInformationBypassAccessCheck,
FileLinkInformationBypassAccessCheck,
FileVolumeNameInformation,
FileIdInformation,
FileIdExtdDirectoryInformation,
FileReplaceCompletionInformation,
FileHardLinkFullIdInformation,
FileIdExtdBothDirectoryInformation,
FileDispositionInformationEx,
FileRenameInformationEx,
FileRenameInformationExBypassAccessCheck,
FileDesiredStorageClassInformation,
FileStatInformation,
FileMemoryPartitionInformation,
FileStatLxInformation,
FileCaseSensitiveInformation,
FileLinkInformationEx,
FileLinkInformationExBypassAccessCheck,
FileStorageReserveIdInformation,
FileCaseSensitiveInformationForceAccessCheck,
FileMaximumInformation
} FILE_INFORMATION_CLASS_EXTRA, * PFILE_INFORMATION_CLASS_EXTRA;
typedef struct _FILE_LINK_INFORMATION {
BOOLEAN ReplaceIfExists;
HANDLE RootDirectory;
ULONG FileNameLength;
WCHAR FileName[1];
} FILE_LINK_INFORMATION, * PFILE_LINK_INFORMATION;
typedef struct _FILE_LINK_INFORMATION_EX {
union {
BOOLEAN ReplaceIfExists;
ULONG Flags;
};
HANDLE RootDirectory;
ULONG FileNameLength;
WCHAR FileName[1];
} FILE_LINK_INFORMATION_EX, * PFILE_LINK_INFORMATION_EX;
extern "C" {
NTSTATUS NTAPI ZwSetInformationFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ PVOID FileInformation,
_In_ ULONG Length,
_In_ FILE_INFORMATION_CLASS FileInformationClass);
NTSTATUS NTAPI ZwCreateFile(
_Out_ PHANDLE FileHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_opt_ PLARGE_INTEGER AllocationSize,
_In_ ULONG FileAttributes,
_In_ ULONG ShareAccess,
_In_ ULONG CreateDisposition,
_In_ ULONG CreateOptions,
_In_opt_ PVOID EaBuffer,
_In_ ULONG EaLength);
NTSTATUS NTAPI ZwOpenFile(
_Out_ PHANDLE FileHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG ShareAccess,
_In_ ULONG OpenOptions);
NTSTATUS NTAPI ZwClose(_In_ HANDLE FileHandle);
}
BOOL SetRenameFileByHandle(HANDLE hFile, const wstring& target);
NTSTATUS ZwSetRenameFileByHandle(HANDLE hFile, LPCWSTR targetName, FILE_INFORMATION_CLASS_EXTRA fileInfoClass);
BOOL SetFileDispositionByHandle(HANDLE hFile, FILE_INFO_BY_HANDLE_CLASS fileInfoClass);
NTSTATUS ZwSetFileDispositionByHandle(HANDLE hFile, FILE_INFORMATION_CLASS_EXTRA fileInfoClass);
_NtCreateFile GetNtCreateFile();
_NtClose GetNtClose();
_RtlInitUnicodeString GetRtlInitUnicodeString();
bool TryGetFullPath(_In_ LPCWSTR path, _Out_ wstring& fullPath);
bool TryGetNtFullPath(_In_ LPCWSTR path, _Out_ wstring& fullPath);
bool TryGetNtEscapedFullPath(_In_ LPCWSTR path, _Out_ wstring& fullPath);
BOOLEAN TestCreateSymbolicLinkW(_In_ LPCWSTR lpSymlinkFileName, _In_ LPCWSTR lpTargetFileName, _In_ DWORD dwFlags);
BOOLEAN TestCreateSymbolicLinkA(_In_ LPCSTR lpSymlinkFileName, _In_ LPCSTR lpTargetFileName, _In_ DWORD dwFlags);
| 2,775 |
1,144 |
<gh_stars>1000+
from typing import Dict, Tuple, Optional, Sequence
from random import choice
def split_hostport(hostport: str) -> Tuple[str, Optional[int]]:
split_host = hostport.split(":")
if len(split_host) == 1:
split_host.append(None)
else:
# Convert port to int
split_host[1] = int(split_host[1])
return split_host
def merge_hostport(hostport: Tuple[str, Optional[int]]) -> str:
host, port = hostport
if port is None:
return host
return f"{host}:{port}"
def get_parsed_variables(
s: str, separator: str = ";", equal: str = "="
) -> Dict[str, str]:
result = {}
if len(s):
variables = s.split(separator)
for variable in variables:
key, value = variable.split(equal)
result[key] = value
return result
def random_choice(choices: Sequence, default=None):
if len(choices) == 0:
return default
return choice(choices)
| 396 |
1,275 |
<gh_stars>1000+
/*
* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. A copy of the
* License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
#include <utils/sh_dpi_tasks.h>
void host_memory_putc(uint64_t addr, uint8_t data)
{
*(uint8_t *)addr = data;
}
//void host_memory_getc(uint64_t addr, uint8_t *data)
uint8_t host_memory_getc(uint64_t addr)
{
return *(uint8_t *)addr;
}
void cosim_printf(const char *format, ...)
{
static char sv_msg_buffer[256];
va_list args;
va_start(args, format);
vsprintf(sv_msg_buffer, format, args);
#ifdef SV_TEST
sv_printf(sv_msg_buffer);
#else
printf(sv_msg_buffer);
#endif
va_end(args);
}
void int_handler(uint32_t int_num)
{
// Vivado does not support svGetScopeFromName
#ifdef SV_TEST
#ifndef VIVADO_SIM
svScope scope;
scope = svGetScopeFromName("tb");
svSetScope(scope);
#endif
#endif
cosim_printf("Received interrupt %2d", int_num);
#ifdef SV_TEST
sv_int_ack(int_num);
#endif
}
| 652 |
335 |
<gh_stars>100-1000
{
"word": "Consolation",
"definitions": [
"The comfort received by a person after a loss or disappointment.",
"A person or thing providing consolation.",
"(in sport) a goal scored at a point when it is no longer possible for the scoring team to win."
],
"parts-of-speech": "Noun"
}
| 120 |
2,542 |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
namespace Naming
{
using namespace std;
using namespace Common;
using namespace Reliability;
using namespace ServiceModel;
INITIALIZE_SIZE_ESTIMATION(ResolvedServicePartition)
ResolvedServicePartition::ResolvedServicePartition()
: isServiceGroup_(false)
, locations_(ConsistencyUnitId::Zero, L"", ServiceReplicaSet())
, partitionData_(FABRIC_PARTITION_SCHEME::FABRIC_PARTITION_SCHEME_SINGLETON)
, storeVersion_(ServiceModel::Constants::UninitializedVersion)
, generation_()
, psd_()
{
}
ResolvedServicePartition::ResolvedServicePartition(
bool isServiceGroup,
ServiceTableEntry const & locations,
PartitionInfo const & partitionData,
GenerationNumber const & generation,
__int64 storeVersion,
PartitionedServiceDescriptorSPtr const & psd)
: isServiceGroup_(isServiceGroup)
, locations_(locations)
, partitionData_(partitionData)
, storeVersion_(storeVersion)
, generation_(generation)
, psd_(psd)
{
}
ResolvedServicePartition::ResolvedServicePartition(
ResolvedServicePartition const & other,
ServiceTableEntry && locations)
: isServiceGroup_(other.isServiceGroup_)
, locations_(move(locations))
, partitionData_(other.partitionData_)
, storeVersion_(other.storeVersion_)
, generation_(other.generation_)
, psd_(other.psd_)
{
}
ResolvedServicePartition::ResolvedServicePartition(ResolvedServicePartition const & other)
: isServiceGroup_(other.isServiceGroup_)
, locations_(other.locations_)
, partitionData_(other.partitionData_)
, storeVersion_(other.storeVersion_)
, generation_(other.generation_)
, psd_(other.psd_)
{
}
ResolvedServicePartition::ResolvedServicePartition(ResolvedServicePartition && other)
: isServiceGroup_(std::move(other.isServiceGroup_))
, locations_(std::move(other.locations_))
, partitionData_(std::move(other.partitionData_))
, storeVersion_(std::move(other.storeVersion_))
, generation_(std::move(other.generation_))
, psd_(std::move(other.psd_))
{
}
ResolvedServicePartition & ResolvedServicePartition::operator = (ResolvedServicePartition const & other)
{
if (this != &other)
{
isServiceGroup_ = other.isServiceGroup_;
locations_ = other.locations_;
partitionData_ = other.partitionData_;
storeVersion_ = other.storeVersion_;
generation_ = other.generation_;
psd_ = other.psd_;
}
return *this;
}
ResolvedServicePartition & ResolvedServicePartition::operator = (ResolvedServicePartition && other)
{
if (this != &other)
{
isServiceGroup_ = std::move(other.isServiceGroup_);
locations_ = std::move(other.locations_);
partitionData_ = std::move(other.partitionData_);
storeVersion_ = std::move(other.storeVersion_);
generation_ = std::move(other.generation_);
psd_ = std::move(other.psd_);
}
return *this;
}
bool ResolvedServicePartition::operator == (ResolvedServicePartition const & other) const
{
return (IsServiceGroup == other.IsServiceGroup) &&
(PartitionData == other.PartitionData) &&
(Locations.ConsistencyUnitId == other.Locations.ConsistencyUnitId) &&
(Locations.ServiceName == other.Locations.ServiceName) &&
(Generation == other.Generation) &&
(FMVersion == other.FMVersion) &&
(StoreVersion == other.StoreVersion) &&
((psd_ == nullptr && other.psd_ == nullptr) || (psd_ != nullptr && other.psd_ != nullptr && *psd_ == *other.psd_));
}
bool ResolvedServicePartition::operator != (ResolvedServicePartition const & other) const
{
return !(*this == other);
}
ErrorCode ResolvedServicePartition::CompareVersion(
ResolvedServicePartitionSPtr const & other,
__out LONG & compareResult) const
{
if (!other)
{
return ErrorCode(ErrorCodeValue::InvalidArgument);
}
return CompareVersion(*other, compareResult);
}
ErrorCode ResolvedServicePartition::CompareVersion(
ResolvedServicePartition const & other,
__out LONG & compareResult) const
{
if (isServiceGroup_ != other.isServiceGroup_ ||
partitionData_ != other.partitionData_)
{
return ErrorCodeValue::ServiceMetadataMismatch;
}
NamingUri serviceName;
NamingUri otherServiceName;
if (!TryGetName(serviceName) || !TryGetName(otherServiceName))
{
return ErrorCodeValue::InvalidNameUri;
}
if (locations_.ConsistencyUnitId != other.locations_.ConsistencyUnitId)
{
return ErrorCodeValue::ServiceMetadataMismatch;
}
compareResult = CompareVersionNoValidation(other);
return ErrorCodeValue::Success;
}
ErrorCode ResolvedServicePartition::CompareVersion(
ResolvedServicePartitionMetadata const &metadata,
__out LONG & compareResult) const
{
if (locations_.ConsistencyUnitId != ConsistencyUnitId(metadata.PartitionId))
{
return ErrorCodeValue::ServiceMetadataMismatch;
}
compareResult = CompareVersionNoValidation(
metadata.Generation,
metadata.FMVersion);
return ErrorCodeValue::Success;
}
LONG ResolvedServicePartition::CompareVersionNoValidation(
ResolvedServicePartition const & other) const
{
return CompareVersionNoValidation(
other.Generation,
other.FMVersion);
}
LONG ResolvedServicePartition::CompareVersionNoValidation(
GenerationNumber const &otherGeneration,
__int64 otherFMVersion) const
{
if (this->Generation < otherGeneration)
{
return -1;
}
else if (this->Generation == otherGeneration)
{
if (this->FMVersion < otherFMVersion)
{
return -1;
}
else if (FMVersion == otherFMVersion)
{
return 0;
}
else
{
return +1;
}
}
else
{
return +1;
}
}
bool ResolvedServicePartition::TryGetName(__out NamingUri & name) const
{
return NamingUri::TryParse(locations_.ServiceName, name);
}
size_t ResolvedServicePartition::GetEndpointCount() const
{
size_t count = 0;
if (IsStateful)
{
if (locations_.ServiceReplicaSet.IsPrimaryLocationValid)
{
++count;
}
count += locations_.ServiceReplicaSet.SecondaryLocations.size();
}
else
{
count += locations_.ServiceReplicaSet.ReplicaLocations.size();
}
return count;
}
void ResolvedServicePartition::ToPublicApi(
__inout Common::ScopedHeap & heap,
__out FABRIC_RESOLVED_SERVICE_PARTITION & resolvedServicePartition) const
{
wstring name = L"";
NamingUri nativeServiceName;
if (this->TryGetName(nativeServiceName))
{
// For all user services, TryGetName should be true. The NamingService and ClusterManager do not use URI service names.
name = nativeServiceName.ToString();
}
resolvedServicePartition.ServiceName = heap.AddString(name.c_str());
ServiceEndpointsUtility::SetEndpoints(
this->Locations.ServiceReplicaSet,
heap,
resolvedServicePartition.EndpointCount,
&resolvedServicePartition.Endpoints);
ServiceEndpointsUtility::SetPartitionInfo(
this->Locations,
this->PartitionData,
heap,
resolvedServicePartition.Info);
}
void ResolvedServicePartition::ToWrapper(ResolvedServicePartitionWrapper & rspWrapper)
{
wstring name;
NamingUri nativeServiceName;
if (this->TryGetName(nativeServiceName))
{
// For all user services, TryGetName should be true.
// The NamingService and ClusterManager do not use URI service names.
name = nativeServiceName.ToString();
}
size_t endpointsCount = this->GetEndpointCount();
vector<ServiceEndpointInformationWrapper> endpoints;
if (endpointsCount > 0)
{
if (this->IsStateful)
{
ServiceEndpointInformationWrapper endpoint;
if (this->Locations.ServiceReplicaSet.IsPrimaryLocationValid)
{
endpoint.Kind = FABRIC_SERVICE_ENDPOINT_ROLE::FABRIC_SERVICE_ROLE_STATEFUL_PRIMARY;
endpoint.Address = this->Locations.ServiceReplicaSet.PrimaryLocation;
endpoints.push_back(endpoint);
}
endpoint.Kind = FABRIC_SERVICE_ENDPOINT_ROLE::FABRIC_SERVICE_ROLE_STATEFUL_SECONDARY;
for (size_t i = 0; i < this->Locations.ServiceReplicaSet.SecondaryLocations.size(); ++i)
{
endpoint.Kind = FABRIC_SERVICE_ENDPOINT_ROLE::FABRIC_SERVICE_ROLE_STATEFUL_SECONDARY;
endpoint.Address = this->Locations.ServiceReplicaSet.SecondaryLocations[i];
endpoints.push_back(endpoint);
}
}
else
{
ServiceEndpointInformationWrapper endpoint;
endpoint.Kind = FABRIC_SERVICE_ENDPOINT_ROLE::FABRIC_SERVICE_ROLE_STATELESS;
for (size_t i = 0; i < this->Locations.ServiceReplicaSet.ReplicaLocations.size(); ++i)
{
endpoint.Address = this->Locations.ServiceReplicaSet.ReplicaLocations[i];
endpoints.push_back(endpoint);
}
}
}
ServicePartitionInformation servicePartitionInfo;
ResolvedServicePartitionMetadata rspMetadata(
Locations.ConsistencyUnitId.Guid,
this->FMVersion,
storeVersion_,
generation_);
wstring version;
JsonHelper::Serialize(rspMetadata, version);
servicePartitionInfo.FromPartitionInfo(Locations.ConsistencyUnitId.Guid, PartitionData);
ResolvedServicePartitionWrapper rsp(
move(name),
move(servicePartitionInfo),
move(endpoints),
move(version));
rspWrapper = move(rsp);
}
bool ResolvedServicePartition::IsMoreRecent(ServiceLocationVersion const & prev)
{
return
(Generation > prev.Generation) ||
((Generation == prev.Generation) && (FMVersion > prev.FMVersion)) ||
(StoreVersion > prev.StoreVersion);
}
void ResolvedServicePartition::WriteTo(Common::TextWriter & w, Common::FormatOptions const &) const
{
w << "RSP(serviceName='" << locations_.ServiceName << "'";
w << ", partition='" << partitionData_ << "'";
w << ", generation='" << generation_ << "', locations='" << locations_ << "'";
w << ", ServiceGroup=" << isServiceGroup_;
w << ")";
}
void ResolvedServicePartition::WriteToEtw(uint16 contextSequenceId) const
{
ServiceModelEventSource::Trace->RSPTrace(
contextSequenceId,
locations_.ServiceName,
partitionData_.ToString(),
generation_,
locations_,
isServiceGroup_);
}
wstring ResolvedServicePartition::ToString() const
{
std::wstring product;
Common::StringWriter writer(product);
WriteTo(writer, Common::FormatOptions(0, false, ""));
return product;
}
}
| 5,403 |
4,262 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.processor.resequencer;
/**
* Synchronization facade for {@link ResequencerEngine} for testing purposes only. This facade is used for both
* exclusion purposes and for visibility of changes performed by different threads in unit tests. This facade is
* <i>not</i> needed in {@link ResequencerEngine} applications because it is expected that resequencing is performed by
* a single thread.
*/
public class ResequencerEngineSync<E> {
private ResequencerEngine<E> resequencer;
public ResequencerEngineSync(ResequencerEngine<E> resequencer) {
this.resequencer = resequencer;
}
public synchronized void stop() {
resequencer.stop();
}
public synchronized int size() {
return resequencer.size();
}
public synchronized long getTimeout() {
return resequencer.getTimeout();
}
public synchronized void setTimeout(long timeout) {
resequencer.setTimeout(timeout);
}
public synchronized SequenceSender<E> getSequenceSender() {
return resequencer.getSequenceSender();
}
public synchronized void setSequenceSender(SequenceSender<E> sequenceSender) {
resequencer.setSequenceSender(sequenceSender);
}
synchronized E getLastDelivered() {
return resequencer.getLastDelivered();
}
synchronized void setLastDelivered(E o) {
resequencer.setLastDelivered(o);
}
public synchronized void insert(E o) {
resequencer.insert(o);
}
public synchronized void deliver() throws Exception {
resequencer.deliver();
}
public synchronized boolean deliverNext() throws Exception {
return resequencer.deliverNext();
}
}
| 770 |
335 |
<gh_stars>100-1000
{
"word": "Paramount",
"definitions": [
"more important than anything else; supreme."
],
"parts-of-speech": "Adjective"
}
| 71 |
348 |
{"nom":"Cheyssieu","circ":"8ème circonscription","dpt":"Isère","inscrits":809,"abs":493,"votants":316,"blancs":8,"nuls":3,"exp":305,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":101},{"nuance":"FN","nom":"<NAME>","voix":61},{"nuance":"FI","nom":"Mme <NAME>","voix":48},{"nuance":"SOC","nom":"<NAME>","voix":47},{"nuance":"LR","nom":"Mme <NAME>","voix":33},{"nuance":"ECO","nom":"<NAME>","voix":4},{"nuance":"DIV","nom":"Mme <NAME>","voix":4},{"nuance":"ECO","nom":"Mme <NAME>","voix":3},{"nuance":"EXG","nom":"M. <NAME>","voix":2},{"nuance":"ECO","nom":"Mme <NAME>","voix":2}]}
| 235 |
304 |
<reponame>fjjdev/warnings-ng-plugin
package io.jenkins.plugins.analysis.warnings;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.jenkinsci.test.acceptance.po.Build;
import org.jenkinsci.test.acceptance.po.PageObject;
/**
* {@link PageObject} representing the analysis summary on the build page of a job.
*
* @author <NAME>
* @author <NAME>
* @author <NAME>
* @author <NAME>
*/
public class AnalysisSummary extends PageObject {
private static final Pattern NUMBER = Pattern.compile("\\d+");
private static final String UNDEFINED = "-";
private final WebElement summary;
private final String title;
private final List<WebElement> results;
private final String id;
/**
* Creates a new page object representing the analysis summary on the build page of a job.
*
* @param parent
* a finished build configured with a static analysis tool
* @param id
* the type of the result page (e.g. simian, checkstyle, cpd, etc.)
*/
public AnalysisSummary(final Build parent, final String id) {
super(parent, parent.url(id));
parent.open();
this.id = id;
summary = getElement(By.id(id + "-summary"));
if (summary == null) {
results = new ArrayList<>();
title = StringUtils.EMPTY;
}
else {
results = summary.findElements(by.xpath("./ul/li"));
title = find(By.id(id + "-title")).getText();
}
}
/**
* Determines whether this summary page exists.
*
* @return {@code true} if the page exists, {@code false} otherwise
*/
public boolean isDisplayed() {
return summary != null && summary.isDisplayed();
}
/**
* Return the title text of the summary.
*
* @return the title text
*/
public String getTitleText() {
return title;
}
/**
* Returns the number of new issues.
*
* @return the number of new issues
*/
public int getNewSize() {
return getSize("new");
}
/**
* Returns the number of fixed issues.
*
* @return the number of fixed issues
*/
public int getFixedSize() {
return getSize("fixed");
}
/**
* Returns the reference build that is used to compute the number of new issues. If there is no such reference
* build, then 0 is returned.
*
* @return the reference build
*/
public int getReferenceBuild() {
return getSize("#");
}
/**
* Returns whether the tool produced some errors or not. If there are errors, then the info messages view will
* contain errors and info messages. Otherwise, only info messages are shown.
*
* @return the type of the icon that links to the info messages view
*/
public InfoType getInfoType() {
String iconName = find(by.xpath("//a[@href='" + id + "/info']")).findElements(by.css("*"))
.get(1)
.getAttribute("href");
return InfoType.valueOfClass(iconName);
}
/**
* Returns the tools that are part of the aggregated results. If aggregation is disabled, then {@link #UNDEFINED} is
* returned.
*
* @return the tools that participate in the aggregation
*/
public String getAggregation() {
for (WebElement result : results) {
String message = result.getText();
String aggregation = "Static analysis results from: ";
if (message.startsWith(aggregation)) {
return StringUtils.removeStart(message, aggregation);
}
}
return UNDEFINED;
}
/**
* Returns the texts of the detail elements of the summary.
*
* @return the details
*/
public List<String> getDetails() {
return results.stream().map(WebElement::getText).collect(Collectors.toList());
}
private int getSize(final String linkName) {
Optional<WebElement> newLink = findClickableResultEntryByNamePart(linkName);
return newLink.map(webElement -> extractNumber(webElement.getText())).orElse(0);
}
private int extractNumber(final String linkText) {
Matcher matcher = NUMBER.matcher(linkText);
if (matcher.find()) {
return Integer.parseInt(matcher.group(0));
}
else if (linkText.startsWith("One")) {
return 1;
}
else {
return 0;
}
}
/**
* Clicks the title link that opens the details page with the analysis results.
*
* @return the details page with the analysis result
*/
public AnalysisResult openOverallResult() {
return openPage(getTitleResultLink(), AnalysisResult.class);
}
/**
* Clicks the info link that opens the messages page showing all info and error messages.
*
* @return the messages page showing all info and error messages
*/
public InfoView openInfoView() {
return openPage(getTitleResultInfoLink(), InfoView.class);
}
/**
* Clicks the new link that opens details page with the analysis results - filtered by new issues.
*
* @return the details page with the analysis result
*/
public AnalysisResult openNewIssues() {
return openLink("new", "No new link found");
}
/**
* Clicks the fixed link that opens details page with the fixed issues.
*
* @return the details page with the analysis result
*/
public AnalysisResult openFixedIssues() {
return openLink("fixed", "No fixed link found");
}
/**
* Clicks the reference build link that opens details page with the analysis results of the reference build.
*
* @return the details page with the analysis result of the reference build
*/
public AnalysisResult openReferenceBuildResults() {
return openLink("Reference", "No reference build link found");
}
private AnalysisResult openLink(final String linkText, final String errorMessage) {
Optional<WebElement> link = findClickableResultEntryByNamePart(linkText);
if (link.isPresent()) {
return openPage(link.get(), AnalysisResult.class);
}
throw new NoSuchElementException(errorMessage);
}
private <T extends PageObject> T openPage(final WebElement link, final Class<T> type) {
String href = link.getAttribute("href");
T result = newInstance(type, injector, url(href), id);
link.click();
return result;
}
/**
* Returns the quality gate result of this parser, if set.
*
* @return Success - if the quality gate thresholds have not been reached. Failed - otherwise.
*/
public QualityGateResult getQualityGateResult() {
for (WebElement result : results) {
if (result.getText().contains("Quality gate")) {
return QualityGateResult.valueOf(
result.findElement(by.tagName("img")).getAttribute("title").toUpperCase(Locale.ENGLISH));
}
}
return QualityGateResult.INACTIVE;
}
/**
* Gets the {@link WebElement} of the reset button.
*
* @return the button
* @throws org.openqa.selenium.NoSuchElementException
* When there is no quality gate reset button.
*/
public WebElement getQualityGateResetButton() throws org.openqa.selenium.NoSuchElementException {
for (WebElement result : results) {
if (result.getText().contains("Quality gate")) {
return result.findElement(by.id(id + "-resetReference"));
}
}
throw new org.openqa.selenium.NoSuchElementException("Quality gate reset button not found");
}
/**
* Checks if the quality gate reset button is present.
*
* @return True, if quality gate reset button is present.
*/
public boolean hasQualityGateResetButton() {
try {
if (getQualityGateResetButton() != null) {
return true;
}
}
catch (org.openqa.selenium.NoSuchElementException ignored) {
// ignore and continue
}
return false;
}
/**
* Returns a clickable WebElement (a-tag), by a part of the elements text.
*
* @param namePart
* part of the visible text (should be unique within the item list)
*
* @return WebElement that belongs to the name part
*/
private Optional<WebElement> findClickableResultEntryByNamePart(final String namePart) {
for (WebElement el : results) {
if (el.getText().contains(namePart)) {
return Optional.of(el.findElement(by.tagName("a")));
}
}
return Optional.empty();
}
/**
* Returns the complete visible text by a part of the elements text.
*
* @param namePart
* part of the visible text (should be unique within the item list)
*
* @return String that belongs to the name part
*/
public String findResultEntryTextByNamePart(final String namePart) {
for (WebElement el : results) {
if (el.getText().contains(namePart)) {
return el.getText();
}
}
return null;
}
private WebElement getTitleResultLink() {
return summary.findElement(by.href(id));
}
private WebElement getTitleResultInfoLink() {
return summary.findElement(by.href(id + "/info"));
}
/**
* Determines which icon is shown to represent the info messages view.
*/
public enum InfoType {
/** Info messages only. */
INFO("info-circle"),
/** Info and error messages. */
ERROR("exclamation-triangle");
private String iconName;
InfoType(final String iconName) {
this.iconName = iconName;
}
private String getIconName() {
return iconName;
}
static InfoType valueOfClass(final String iconName) {
if (iconName.contains(INFO.getIconName())) {
return INFO;
}
if (iconName.contains(ERROR.getIconName())) {
return ERROR;
}
throw new NoSuchElementException("No such info type with classes " + iconName);
}
}
/**
* Determines the quality gate result.
*/
public enum QualityGateResult {
SUCCESS, FAILED, UNSTABLE, INACTIVE
}
}
| 4,252 |
700 |
<filename>skidl/protonet.py
# -*- coding: utf-8 -*-
# The MIT License (MIT) - Copyright (c) 2016-2021 <NAME>.
"""
Prototype of a net which can become a Net or a Bus depending upon what is connected to it.
"""
from __future__ import ( # isort:skip
absolute_import,
division,
print_function,
unicode_literals,
)
from builtins import range, super
from future import standard_library
from .logger import active_logger
from .net import Net
from .network import Network
from .pin import Pin
from .skidlbaseobj import SkidlBaseObject
from .utilities import *
standard_library.install_aliases()
class ProtoNet(SkidlBaseObject):
def __init__(self, name=None, circuit=None):
super().__init__()
self.name = name
self.circuit = circuit or default_circuit
def __iadd__(self, *nets_pins_buses):
from .bus import Bus
# Check the stuff you want to connect to see if it's the right kind.
nets_pins = expand_buses(flatten(nets_pins_buses))
allowed_types = (Pin, Net, ProtoNet)
illegal = (np for np in nets_pins if type(np) not in allowed_types)
for np in illegal:
active_logger.raise_(
ValueError,
"Can't make connections to a {} ({}).".format(
type(np), getattr(np, "__name__", "")
),
)
sz = len(nets_pins)
if sz == 0:
active_logger.raise_(
ValueError,
"Connecting empty set of pins, nets, busses to a {}".format(
self.__class__.__name__
),
)
else:
# Create implicitly-named net/bus so the name will be overridden
# by whatever connects to it.
if sz == 1:
cnct = Net(name=None, circuit=self.circuit)
else:
cnct = Bus(None, sz, circuit=self.circuit)
try:
self.intfc[self.intfc_key] = cnct
except AttributeError:
pass
cnct += nets_pins
return cnct
def __len__(self):
# ProtoNets never have attached pins because then they would become Nets.
return 0
def create_network(self):
"""Create a network from a single ProtoNet."""
self += Net() # Turn ProtoNet into a Net.
ntwk = Network()
ntwk.append(self)
return ntwk
def __and__(self, obj):
"""Attach a net and another part/pin/net in serial."""
return Network(self) & obj
def __rand__(self, obj):
"""Attach a net and another part/pin/net in serial."""
return obj & Network(self)
def __or__(self, obj):
"""Attach a net and another part/pin/net in parallel."""
return Network(self) | obj
def __ror__(self, obj):
"""Attach a net and another part/pin/net in parallel."""
return obj | Network(self)
def __iter__(self):
"""
Return an iterator for stepping through the ProtoNet.
"""
# You can only iterate a ProtoNet one time.
return (self for _ in [self]) # Return generator expr.
def is_movable(self):
return True # A ProtoNet is never connected, so it's always movable.
| 1,461 |
1,144 |
/* SPDX-License-Identifier: GPL-2.0+ */
/*
* Copyright (c) 2011 The Chromium OS Authors.
* Copyright (c) 2011, NVIDIA Corp. All rights reserved.
*/
#ifndef _ASM_GENERIC_GPIO_H_
#define _ASM_GENERIC_GPIO_H_
#include <dm/ofnode.h>
struct ofnode_phandle_args;
/*
* Generic GPIO API for U-Boot
*
* --
* NB: This is deprecated. Please use the driver model functions instead:
*
* - gpio_request_by_name()
* - dm_gpio_get_value() etc.
*
* For now we need a dm_ prefix on some functions to avoid name collision.
* --
*
* GPIOs are numbered from 0 to GPIO_COUNT-1 which value is defined
* by the SOC/architecture.
*
* Each GPIO can be an input or output. If an input then its value can
* be read as 0 or 1. If an output then its value can be set to 0 or 1.
* If you try to write an input then the value is undefined. If you try
* to read an output, barring something very unusual, you will get
* back the value of the output that you previously set.
*
* In some cases the operation may fail, for example if the GPIO number
* is out of range, or the GPIO is not available because its pin is
* being used by another function. In that case, functions may return
* an error value of -1.
*/
/**
* @deprecated Please use driver model instead
* Request a GPIO. This should be called before any of the other functions
* are used on this GPIO.
*
* Note: With driver model, the label is allocated so there is no need for
* the caller to preserve it.
*
* @param gpio GPIO number
* @param label User label for this GPIO
* @return 0 if ok, -1 on error
*/
int gpio_request(unsigned gpio, const char *label);
/**
* @deprecated Please use driver model instead
* Stop using the GPIO. This function should not alter pin configuration.
*
* @param gpio GPIO number
* @return 0 if ok, -1 on error
*/
int gpio_free(unsigned gpio);
/**
* @deprecated Please use driver model instead
* Make a GPIO an input.
*
* @param gpio GPIO number
* @return 0 if ok, -1 on error
*/
int gpio_direction_input(unsigned gpio);
/**
* @deprecated Please use driver model instead
* Make a GPIO an output, and set its value.
*
* @param gpio GPIO number
* @param value GPIO value (0 for low or 1 for high)
* @return 0 if ok, -1 on error
*/
int gpio_direction_output(unsigned gpio, int value);
/**
* @deprecated Please use driver model instead
* Get a GPIO's value. This will work whether the GPIO is an input
* or an output.
*
* @param gpio GPIO number
* @return 0 if low, 1 if high, -1 on error
*/
int gpio_get_value(unsigned gpio);
/**
* @deprecated Please use driver model instead
* Set an output GPIO's value. The GPIO must already be an output or
* this function may have no effect.
*
* @param gpio GPIO number
* @param value GPIO value (0 for low or 1 for high)
* @return 0 if ok, -1 on error
*/
int gpio_set_value(unsigned gpio, int value);
/* State of a GPIO, as reported by get_function() */
enum gpio_func_t {
GPIOF_INPUT = 0,
GPIOF_OUTPUT,
GPIOF_UNUSED, /* Not claimed */
GPIOF_UNKNOWN, /* Not known */
GPIOF_FUNC, /* Not used as a GPIO */
GPIOF_COUNT,
};
struct udevice;
struct gpio_desc {
struct udevice *dev; /* Device, NULL for invalid GPIO */
unsigned long flags;
#define GPIOD_REQUESTED (1 << 0) /* Requested/claimed */
#define GPIOD_IS_OUT (1 << 1) /* GPIO is an output */
#define GPIOD_IS_IN (1 << 2) /* GPIO is an input */
#define GPIOD_ACTIVE_LOW (1 << 3) /* value has active low */
#define GPIOD_IS_OUT_ACTIVE (1 << 4) /* set output active */
uint offset; /* GPIO offset within the device */
/*
* We could consider adding the GPIO label in here. Possibly we could
* use this structure for internal GPIO information.
*/
};
/**
* dm_gpio_is_valid() - Check if a GPIO is valid
*
* @desc: GPIO description containing device, offset and flags,
* previously returned by gpio_request_by_name()
* @return true if valid, false if not
*/
static inline bool dm_gpio_is_valid(const struct gpio_desc *desc)
{
return desc->dev != NULL;
}
/**
* gpio_get_status() - get the current GPIO status as a string
*
* Obtain the current GPIO status as a string which can be presented to the
* user. A typical string is:
*
* "b4: in: 1 [x] sdmmc_cd"
*
* which means this is GPIO bank b, offset 4, currently set to input, current
* value 1, [x] means that it is requested and the owner is 'sdmmc_cd'
*
* TODO(<EMAIL>): This should use struct gpio_desc
*
* @dev: Device to check
* @offset: Offset of device GPIO to check
* @buf: Place to put string
* @buffsize: Size of string including \0
*/
int gpio_get_status(struct udevice *dev, int offset, char *buf, int buffsize);
/**
* gpio_get_function() - get the current function for a GPIO pin
*
* Note this returns GPIOF_UNUSED if the GPIO is not requested.
*
* TODO(<EMAIL>): This should use struct gpio_desc
*
* @dev: Device to check
* @offset: Offset of device GPIO to check
* @namep: If non-NULL, this is set to the name given when the GPIO
* was requested, or -1 if it has not been requested
* @return -ENODATA if the driver returned an unknown function,
* -ENODEV if the device is not active, -EINVAL if the offset is invalid.
* GPIOF_UNUSED if the GPIO has not been requested. Otherwise returns the
* function from enum gpio_func_t.
*/
int gpio_get_function(struct udevice *dev, int offset, const char **namep);
/**
* gpio_get_raw_function() - get the current raw function for a GPIO pin
*
* Note this does not return GPIOF_UNUSED - it will always return the GPIO
* driver's view of a pin function, even if it is not correctly set up.
*
* TODO(<EMAIL>): This should use struct gpio_desc
*
* @dev: Device to check
* @offset: Offset of device GPIO to check
* @namep: If non-NULL, this is set to the name given when the GPIO
* was requested, or -1 if it has not been requested
* @return -ENODATA if the driver returned an unknown function,
* -ENODEV if the device is not active, -EINVAL if the offset is invalid.
* Otherwise returns the function from enum gpio_func_t.
*/
int gpio_get_raw_function(struct udevice *dev, int offset, const char **namep);
/**
* gpio_requestf() - request a GPIO using a format string for the owner
*
* This is a helper function for gpio_request(). It allows you to provide
* a printf()-format string for the GPIO owner. It calls gpio_request() with
* the string that is created
*/
int gpio_requestf(unsigned gpio, const char *fmt, ...)
__attribute__ ((format (__printf__, 2, 3)));
struct fdtdec_phandle_args;
/**
* gpio_xlate_offs_flags() - implementation for common use of dm_gpio_ops.xlate
*
* This routine sets the offset field to args[0] and the flags field to
* GPIOD_ACTIVE_LOW if the GPIO_ACTIVE_LOW flag is present in args[1].
*/
int gpio_xlate_offs_flags(struct udevice *dev, struct gpio_desc *desc,
struct ofnode_phandle_args *args);
/**
* struct struct dm_gpio_ops - Driver model GPIO operations
*
* Refer to functions above for description. These function largely copy
* the old API.
*
* This is trying to be close to Linux GPIO API. Once the U-Boot uses the
* new DM GPIO API, this should be really easy to flip over to the Linux
* GPIO API-alike interface.
*
* Also it would be useful to standardise additional functions like
* pullup, slew rate and drive strength.
*
* gpio_request() and gpio_free() are optional - if NULL then they will
* not be called.
*
* Note that @offset is the offset from the base GPIO of the device. So
* offset 0 is the device's first GPIO and offset o-1 is the last GPIO,
* where o is the number of GPIO lines controlled by the device. A device
* is typically used to control a single bank of GPIOs. Within complex
* SoCs there may be many banks and therefore many devices all referring
* to the different IO addresses within the SoC.
*
* The uclass combines all GPIO devices together to provide a consistent
* numbering from 0 to n-1, where n is the number of GPIOs in total across
* all devices. Be careful not to confuse offset with gpio in the parameters.
*/
struct dm_gpio_ops {
int (*request)(struct udevice *dev, unsigned offset, const char *label);
int (*free)(struct udevice *dev, unsigned offset);
int (*direction_input)(struct udevice *dev, unsigned offset);
int (*direction_output)(struct udevice *dev, unsigned offset,
int value);
int (*get_value)(struct udevice *dev, unsigned offset);
int (*set_value)(struct udevice *dev, unsigned offset, int value);
int (*get_open_drain)(struct udevice *dev, unsigned offset);
int (*set_open_drain)(struct udevice *dev, unsigned offset, int value);
/**
* get_function() Get the GPIO function
*
* @dev: Device to check
* @offset: GPIO offset within that device
* @return current function - GPIOF_...
*/
int (*get_function)(struct udevice *dev, unsigned offset);
/**
* xlate() - Translate phandle arguments into a GPIO description
*
* This function should set up the fields in desc according to the
* information in the arguments. The uclass will have set up:
*
* @desc->dev to @dev
* @desc->flags to 0
* @desc->offset to 0
*
* This method is optional and defaults to gpio_xlate_offs_flags,
* which will parse offset and the GPIO_ACTIVE_LOW flag in the first
* two arguments.
*
* Note that @dev is passed in as a parameter to follow driver model
* uclass conventions, even though it is already available as
* desc->dev.
*
* @dev: GPIO device
* @desc: Place to put GPIO description
* @args: Arguments provided in description
* @return 0 if OK, -ve on error
*/
int (*xlate)(struct udevice *dev, struct gpio_desc *desc,
struct ofnode_phandle_args *args);
};
/**
* struct gpio_dev_priv - information about a device used by the uclass
*
* The uclass combines all active GPIO devices into a unified numbering
* scheme. To do this it maintains some private information about each
* device.
*
* To implement driver model support in your GPIO driver, add a probe
* handler, and set @gpio_count and @bank_name correctly in that handler.
* This tells the uclass the name of the GPIO bank and the number of GPIOs
* it contains.
*
* @bank_name: Name of the GPIO device (e.g 'a' means GPIOs will be called
* 'A0', 'A1', etc.
* @gpio_count: Number of GPIOs in this device
* @gpio_base: Base GPIO number for this device. For the first active device
* this will be 0; the numbering for others will follow sequentially so that
* @gpio_base for device 1 will equal the number of GPIOs in device 0.
* @name: Array of pointers to the name for each GPIO in this bank. The
* value of the pointer will be NULL if the GPIO has not been claimed.
*/
struct gpio_dev_priv {
const char *bank_name;
unsigned gpio_count;
unsigned gpio_base;
char **name;
};
/* Access the GPIO operations for a device */
#define gpio_get_ops(dev) ((struct dm_gpio_ops *)(dev)->driver->ops)
/**
* gpio_get_bank_info - Return information about a GPIO bank/device
*
* This looks up a device and returns both its GPIO base name and the number
* of GPIOs it controls.
*
* @dev: Device to look up
* @offset_count: Returns number of GPIOs within this bank
* @return bank name of this device
*/
const char *gpio_get_bank_info(struct udevice *dev, int *offset_count);
/**
* dm_gpio_lookup_name() - Look up a named GPIO and return its description
*
* The name of a GPIO is typically its bank name followed by a number from 0.
* For example A0 is the first GPIO in bank A. Each bank is a separate driver
* model device.
*
* @name: Name to look up
* @desc: Returns description, on success
* @return 0 if OK, -ve on error
*/
int dm_gpio_lookup_name(const char *name, struct gpio_desc *desc);
/**
* gpio_lookup_name - Look up a GPIO name and return its details
*
* This is used to convert a named GPIO into a device, offset and GPIO
* number.
*
* @name: GPIO name to look up
* @devp: Returns pointer to device which contains this GPIO
* @offsetp: Returns the offset number within this device
* @gpiop: Returns the absolute GPIO number, numbered from 0
*/
int gpio_lookup_name(const char *name, struct udevice **devp,
unsigned int *offsetp, unsigned int *gpiop);
/**
* gpio_get_values_as_int() - Turn the values of a list of GPIOs into an int
*
* This puts the value of the first GPIO into bit 0, the second into bit 1,
* etc. then returns the resulting integer.
*
* @gpio_list: List of GPIOs to collect
* @return resulting integer value, or -ve on error
*/
int gpio_get_values_as_int(const int *gpio_list);
/**
* dm_gpio_get_values_as_int() - Turn the values of a list of GPIOs into an int
*
* This puts the value of the first GPIO into bit 0, the second into bit 1,
* etc. then returns the resulting integer.
*
* @desc_list: List of GPIOs to collect
* @count: Number of GPIOs
* @return resulting integer value, or -ve on error
*/
int dm_gpio_get_values_as_int(const struct gpio_desc *desc_list, int count);
/**
* gpio_claim_vector() - claim a number of GPIOs for input
*
* @gpio_num_array: array of gpios to claim, terminated by -1
* @fmt: format string for GPIO names, e.g. "board_id%d"
* @return 0 if OK, -ve on error
*/
int gpio_claim_vector(const int *gpio_num_array, const char *fmt);
/**
* gpio_request_by_name() - Locate and request a GPIO by name
*
* This operates by looking up the given list name in the device (device
* tree property) and requesting the GPIO for use. The property must exist
* in @dev's node.
*
* Use @flags to specify whether the GPIO should be an input or output. In
* principle this can also come from the device tree binding but most
* bindings don't provide this information. Specifically, when the GPIO uclass
* calls the xlate() method, it can return default flags, which are then
* ORed with this @flags.
*
* If we find that requesting the GPIO is not always needed we could add a
* new function or a new GPIOD_NO_REQUEST flag.
*
* At present driver model has no reference counting so if one device
* requests a GPIO which subsequently is unbound, the @desc->dev pointer
* will be invalid. However this will only happen if the GPIO device is
* unbound, not if it is removed, so this seems like a reasonable limitation
* for now. There is no real use case for unbinding drivers in normal
* operation.
*
* The device tree binding is doc/device-tree-bindings/gpio/gpio.txt in
* generate terms and each specific device may add additional details in
* a binding file in the same directory.
*
* @dev: Device requesting the GPIO
* @list_name: Name of GPIO list (e.g. "board-id-gpios")
* @index: Index number of the GPIO in that list use request (0=first)
* @desc: Returns GPIO description information. If there is no such
* GPIO, dev->dev will be NULL.
* @flags: Indicates the GPIO input/output settings (GPIOD_...)
* @return 0 if OK, -ENOENT if the GPIO does not exist, -EINVAL if there is
* something wrong with the list, or other -ve for another error (e.g.
* -EBUSY if a GPIO was already requested)
*/
int gpio_request_by_name(struct udevice *dev, const char *list_name,
int index, struct gpio_desc *desc, int flags);
/**
* gpio_request_list_by_name() - Request a list of GPIOs
*
* Reads all the GPIOs from a list and requests them. See
* gpio_request_by_name() for additional details. Lists should not be
* misused to hold unrelated or optional GPIOs. They should only be used
* for things like parallel data lines. A zero phandle terminates the list
* the list.
*
* This function will either succeed, and request all GPIOs in the list, or
* fail and request none (it will free already-requested GPIOs in case of
* an error part-way through).
*
* @dev: Device requesting the GPIO
* @list_name: Name of GPIO list (e.g. "board-id-gpios")
* @desc_list: Returns a list of GPIO description information
* @max_count: Maximum number of GPIOs to return (@desc_list must be at least
* this big)
* @flags: Indicates the GPIO input/output settings (GPIOD_...)
* @return number of GPIOs requested, or -ve on error
*/
int gpio_request_list_by_name(struct udevice *dev, const char *list_name,
struct gpio_desc *desc_list, int max_count,
int flags);
/**
* dm_gpio_request() - manually request a GPIO
*
* Note: This function should only be used for testing / debugging. Instead.
* use gpio_request_by_name() to pull GPIOs from the device tree.
*
* @desc: GPIO description of GPIO to request (see dm_gpio_lookup_name())
* @label: Label to attach to the GPIO while claimed
* @return 0 if OK, -ve on error
*/
int dm_gpio_request(struct gpio_desc *desc, const char *label);
/**
* gpio_get_list_count() - Returns the number of GPIOs in a list
*
* Counts the GPIOs in a list. See gpio_request_by_name() for additional
* details.
*
* @dev: Device requesting the GPIO
* @list_name: Name of GPIO list (e.g. "board-id-gpios")
* @return number of GPIOs (0 for an empty property) or -ENOENT if the list
* does not exist
*/
int gpio_get_list_count(struct udevice *dev, const char *list_name);
/**
* gpio_request_by_name_nodev() - request GPIOs without a device
*
* This is a version of gpio_request_list_by_name() that does not use a
* device. Avoid it unless the caller is not yet using driver model
*/
int gpio_request_by_name_nodev(ofnode node, const char *list_name, int index,
struct gpio_desc *desc, int flags);
/**
* gpio_request_list_by_name_nodev() - request GPIOs without a device
*
* This is a version of gpio_request_list_by_name() that does not use a
* device. Avoid it unless the caller is not yet using driver model
*/
int gpio_request_list_by_name_nodev(ofnode node, const char *list_name,
struct gpio_desc *desc_list, int max_count,
int flags);
/**
* dm_gpio_free() - Free a single GPIO
*
* This frees a single GPIOs previously returned from gpio_request_by_name().
*
* @dev: Device which requested the GPIO
* @desc: GPIO to free
* @return 0 if OK, -ve on error
*/
int dm_gpio_free(struct udevice *dev, struct gpio_desc *desc);
/**
* gpio_free_list() - Free a list of GPIOs
*
* This frees a list of GPIOs previously returned from
* gpio_request_list_by_name().
*
* @dev: Device which requested the GPIOs
* @desc: List of GPIOs to free
* @count: Number of GPIOs in the list
* @return 0 if OK, -ve on error
*/
int gpio_free_list(struct udevice *dev, struct gpio_desc *desc, int count);
/**
* gpio_free_list_nodev() - free GPIOs without a device
*
* This is a version of gpio_free_list() that does not use a
* device. Avoid it unless the caller is not yet using driver model
*/
int gpio_free_list_nodev(struct gpio_desc *desc, int count);
/**
* dm_gpio_get_value() - Get the value of a GPIO
*
* This is the driver model version of the existing gpio_get_value() function
* and should be used instead of that.
*
* For now, these functions have a dm_ prefix since they conflict with
* existing names.
*
* @desc: GPIO description containing device, offset and flags,
* previously returned by gpio_request_by_name()
* @return GPIO value (0 for inactive, 1 for active) or -ve on error
*/
int dm_gpio_get_value(const struct gpio_desc *desc);
int dm_gpio_set_value(const struct gpio_desc *desc, int value);
/**
* dm_gpio_get_open_drain() - Check if open-drain-mode of a GPIO is active
*
* This checks if open-drain-mode for a GPIO is enabled or not. This method is
* optional.
*
* @desc: GPIO description containing device, offset and flags,
* previously returned by gpio_request_by_name()
* @return Value of open drain mode for GPIO (0 for inactive, 1 for active) or
* -ve on error
*/
int dm_gpio_get_open_drain(struct gpio_desc *desc);
/**
* dm_gpio_set_open_drain() - Switch open-drain-mode of a GPIO on or off
*
* This enables or disables open-drain mode for a GPIO. This method is
* optional; if the driver does not support it, nothing happens when the method
* is called.
*
* In open-drain mode, instead of actively driving the output (Push-pull
* output), the GPIO's pin is connected to the collector (for a NPN transistor)
* or the drain (for a MOSFET) of a transistor, respectively. The pin then
* either forms an open circuit or a connection to ground, depending on the
* state of the transistor.
*
* @desc: GPIO description containing device, offset and flags,
* previously returned by gpio_request_by_name()
* @return 0 if OK, -ve on error
*/
int dm_gpio_set_open_drain(struct gpio_desc *desc, int value);
/**
* dm_gpio_set_dir() - Set the direction for a GPIO
*
* This sets up the direction according tot the provided flags. It will do
* nothing unless the direction is actually specified.
*
* @desc: GPIO description containing device, offset and flags,
* previously returned by gpio_request_by_name()
* @return 0 if OK, -ve on error
*/
int dm_gpio_set_dir(struct gpio_desc *desc);
/**
* dm_gpio_set_dir_flags() - Set direction using specific flags
*
* This is like dm_gpio_set_dir() except that the flags value is provided
* instead of being used from desc->flags. This is needed because in many
* cases the GPIO description does not include direction information.
* Note that desc->flags is updated by this function.
*
* @desc: GPIO description containing device, offset and flags,
* previously returned by gpio_request_by_name()
* @flags: New flags to use
* @return 0 if OK, -ve on error, in which case desc->flags is not updated
*/
int dm_gpio_set_dir_flags(struct gpio_desc *desc, ulong flags);
/**
* gpio_get_number() - Get the global GPIO number of a GPIO
*
* This should only be used for debugging or interest. It returns the number
* that should be used for gpio_get_value() etc. to access this GPIO.
*
* @desc: GPIO description containing device, offset and flags,
* previously returned by gpio_request_by_name()
* @return GPIO number, or -ve if not found
*/
int gpio_get_number(const struct gpio_desc *desc);
#endif /* _ASM_GENERIC_GPIO_H_ */
| 6,844 |
665 |
<filename>rest/opstats/stat_aggregator.h
/* graphite_connector.h -*- C++ -*-
<NAME>, 3 August 2011
Copyright (c) 2011 mldb.ai inc. All rights reserved.
This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
Class to accumulate operational stats and connect to graphite (directly).
*/
#pragma once
#include "mldb/utils/distribution.h"
#include "mldb/types/date.h"
#include "mldb/rest/stats_events.h"
#include <unordered_map>
#include <map>
#include <deque>
#include <atomic>
namespace MLDB {
struct StatReading {
StatReading(const std::string & name = "",
float value = 0.0,
Date timestamp = Date())
: name(name), value(value), timestamp(timestamp)
{
}
std::string name;
float value;
Date timestamp;
};
/*****************************************************************************/
/* STAT AGGREGATOR */
/*****************************************************************************/
/** Generic class that aggregates statistics. */
struct StatAggregator {
virtual ~StatAggregator()
{
}
/** Record a value. */
virtual void record(float value) = 0;
/** Read and reset the counter, providing output in Graphite's preferred
format. */
virtual std::vector<StatReading> read(const std::string & prefix) = 0;
};
/*****************************************************************************/
/* COUNTER AGGREGATOR */
/*****************************************************************************/
/** Class that aggregates counts over a period of time. */
struct CounterAggregator : public StatAggregator {
CounterAggregator();
virtual ~CounterAggregator();
virtual void record(float value);
std::pair<double, Date> reset();
/** Read and reset the counter, providing output in Graphite's preferred
format. */
virtual std::vector<StatReading> read(const std::string & prefix);
private:
Date start; //< Date at which we last cleared the counter
std::atomic<double> total; //< total since we last added it up
std::deque<double> totalsBuffer; //< Totals for the last n reads.
};
/*****************************************************************************/
/* GAUGE AGGREGATOR */
/*****************************************************************************/
/** Class that aggregates a gauge over a period of time. */
struct GaugeAggregator : public StatAggregator {
enum Verbosity
{
StableLevel, ///< mean
Level, ///< mean, min, max
Outcome ///< mean, min, max, percentiles, count
};
GaugeAggregator(Verbosity verbosity = Outcome,
const std::vector<int>& extra = DefaultOutcomePercentiles);
virtual ~GaugeAggregator();
/** Record a new value of the stat. Lock-free but may spin briefly. */
virtual void record(float value);
/** Obtain a the current statistics and replace with a new version. */
std::pair<distribution<float> *, Date> reset();
/** Read and reset the counter, providing output in Graphite's preferred
format.
*/
virtual std::vector<StatReading> read(const std::string & prefix);
private:
Verbosity verbosity;
Date start; //< Date at which we last cleared the counter
std::atomic<distribution<float> *> values; //< List of added values
std::vector<int> extra;
};
} // namespace MLDB
| 1,286 |
1,484 |
#!usr/bin/env python3
import threading
import time
from typing import Optional
import pytest
from anchore_engine.subsys.caching import (
TTLCache,
local_named_cache,
thread_local_cache,
)
@pytest.fixture
def ttl_cache(request):
cache: TTLCache = TTLCache()
value: str = "test_value"
cache.cache_it("test_key", value, request.param)
return cache
class TestTTLCache:
@pytest.mark.parametrize(
"ttl_cache, sleep_time, expected_type",
[
(None, 0, str),
(-1, 0, str),
(1, 1, type(None)),
(0, 0, type(None)),
],
indirect=["ttl_cache"],
)
def test_cache(self, ttl_cache, sleep_time, expected_type):
time.sleep(sleep_time)
cached: Optional[str] = ttl_cache.lookup("test_key")
assert isinstance(cached, expected_type)
if expected_type != type(None):
assert id(cached) == id("test_value")
@pytest.mark.parametrize("ttl_cache", [(None)], indirect=["ttl_cache"])
def test_cache_flush(self, ttl_cache):
ttl_cache.flush()
cached: Optional[str] = ttl_cache.lookup("test_key")
assert isinstance(cached, type(None))
@pytest.mark.parametrize("ttl_cache", [(None)], indirect=["ttl_cache"])
def test_cache_delete(self, ttl_cache):
ttl_cache.delete("test_key")
cached: Optional[str] = ttl_cache.lookup("test_key")
assert isinstance(cached, type(None))
class TestLocalCaches:
def test_threadlocal_singleton(self):
cache: threading.local = thread_local_cache()
cache2: threading.local = thread_local_cache()
assert id(cache) == id(cache2)
def test_threadlocal_has_cache(self):
cache: threading.local = thread_local_cache()
assert hasattr(cache, "general")
assert isinstance(cache.general, TTLCache)
def test_localnamed_has_name(self):
cache: TTLCache = local_named_cache("mycache")
tlocal: threading.local = thread_local_cache()
assert isinstance(cache, TTLCache)
assert hasattr(tlocal, "mycache")
def test_threadlocal_is_thread_local(self):
thread_cache_id: Optional[int] = None
def thread_func():
nonlocal thread_cache_id
thread_cache_id = id(thread_local_cache().general)
t1: threading.Thread = threading.Thread(target=thread_func)
t1.start()
t1.join()
main_cache_id: int = id(thread_local_cache().general)
assert main_cache_id != thread_cache_id
| 1,117 |
425 |
// Copyright 2017-2019 VMware, Inc.
// SPDX-License-Identifier: BSD-2-Clause
//
// The BSD-2 license (the License) set forth below applies to all parts of the
// Cascade project. You may not use this file except in compliance with the
// License.
//
// BSD-2 License
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef CASCADE_SRC_TARGET_CORE_AVMM_AVMM_LOGIC_H
#define CASCADE_SRC_TARGET_CORE_AVMM_AVMM_LOGIC_H
#include <cassert>
#include <functional>
#include <unordered_map>
#include <vector>
#include "common/bits.h"
#include "target/core.h"
#include "target/core/avmm/var_table.h"
#include "target/core/common/interfacestream.h"
#include "target/core/common/printf.h"
#include "target/core/common/scanf.h"
#include "target/input.h"
#include "target/state.h"
#include "verilog/ast/ast.h"
#include "verilog/analyze/evaluate.h"
#include "verilog/analyze/module_info.h"
#include "verilog/ast/visitors/visitor.h"
namespace cascade::avmm {
template <size_t V, typename A, typename T>
class AvmmLogic : public Logic {
public:
// Typedefs:
typedef std::function<void()> Callback;
// Constructors:
AvmmLogic(Interface* interface, ModuleDeclaration* md, size_t slot);
~AvmmLogic() override;
// Configuration Methods:
AvmmLogic& set_input(const Identifier* id, VId vid);
AvmmLogic& set_state(const Identifier* id, VId vid);
AvmmLogic& set_output(const Identifier* id, VId vid);
AvmmLogic& index_tasks();
AvmmLogic& set_callback(Callback cb);
// Configuraton Properties:
VarTable<V,A,T>* get_table();
const VarTable<V,A,T>* get_table() const;
// Core Interface:
State* get_state() override;
void set_state(const State* s) override;
Input* get_input() override;
void set_input(const Input* i) override;
void finalize() override;
void read(VId id, const Bits* b) override;
void evaluate() override;
bool there_are_updates() const override;
void update() override;
bool there_were_tasks() const override;
size_t open_loop(VId clk, bool val, size_t itr) override;
// Optimization Properties:
const Identifier* open_loop_clock();
private:
// Compiler State:
Callback cb_;
size_t slot_;
// Source Management:
ModuleDeclaration* src_;
std::vector<const Identifier*> inputs_;
std::unordered_map<VId, const Identifier*> state_;
std::vector<std::pair<const Identifier*, VId>> outputs_;
std::vector<const SystemTaskEnableStatement*> tasks_;
// Control State:
bool there_were_tasks_;
VarTable<V,A,T> table_;
std::unordered_map<FId, interfacestream*> streams_;
std::vector<std::pair<FId, interfacestream*>> stream_cache_;
// Stream Caching Helpers:
bool is_constant(const Expression* e) const;
// Control Helpers:
interfacestream* get_stream(FId fd);
bool handle_tasks();
// Indexes system tasks and inserts the identifiers which appear in those
// tasks into the variable table.
class Inserter : public Visitor {
public:
explicit Inserter(AvmmLogic* av);
~Inserter() override = default;
private:
AvmmLogic* av_;
bool in_args_;
void visit(const Identifier* id) override;
void visit(const FeofExpression* fe) override;
void visit(const DebugStatement* ds) override;
void visit(const FflushStatement* fs) override;
void visit(const FinishStatement* fs) override;
void visit(const FseekStatement* fs) override;
void visit(const GetStatement* gs) override;
void visit(const PutStatement* ps) override;
void visit(const RestartStatement* rs) override;
void visit(const RetargetStatement* rs) override;
void visit(const SaveStatement* ss) override;
};
// Synchronizes the locations in the variable table which correspond to the
// identifiers which appear in an AST subtree.
class Sync : public Visitor {
public:
explicit Sync(AvmmLogic* av);
~Sync() override = default;
private:
AvmmLogic* av_;
void visit(const Identifier* id) override;
};
// Evaluation Helpers:
Evaluate eval_;
Sync sync_;
Scanf scanf_;
Printf printf_;
};
template <size_t V, typename A, typename T>
inline AvmmLogic<V,A,T>::AvmmLogic(Interface* interface, ModuleDeclaration* src, size_t slot) : Logic(interface), sync_(this) {
src_ = src;
cb_ = nullptr;
slot_ = slot;
tasks_.push_back(nullptr);
}
template <size_t V, typename A, typename T>
inline AvmmLogic<V,A,T>::~AvmmLogic() {
if (cb_ != nullptr) {
cb_();
}
delete src_;
for (auto& s : streams_) {
delete s.second;
}
}
template <size_t V, typename A, typename T>
inline AvmmLogic<V,A,T>& AvmmLogic<V,A,T>::set_input(const Identifier* id, VId vid) {
if (table_.find(id) == table_.end()) {
table_.insert(id);
}
if (inputs_.size() <= vid) {
inputs_.resize(vid+1, nullptr);
}
inputs_[vid] = id;
return *this;
}
template <size_t V, typename A, typename T>
inline AvmmLogic<V,A,T>& AvmmLogic<V,A,T>::set_state(const Identifier* id, VId vid) {
if (table_.find(id) == table_.end()) {
table_.insert(id);
}
state_.insert(std::make_pair(vid, id));
return *this;
}
template <size_t V, typename A, typename T>
inline AvmmLogic<V,A,T>& AvmmLogic<V,A,T>::set_output(const Identifier* id, VId vid) {
if (table_.find(id) == table_.end()) {
table_.insert(id);
}
outputs_.push_back(std::make_pair(id, vid));
return *this;
}
template <size_t V, typename A, typename T>
inline AvmmLogic<V,A,T>& AvmmLogic<V,A,T>::index_tasks() {
Inserter i(this);
src_->accept(&i);
return *this;
}
template <size_t V, typename A, typename T>
inline AvmmLogic<V,A,T>& AvmmLogic<V,A,T>::set_callback(Callback cb) {
cb_ = cb;
return *this;
}
template <size_t V, typename A, typename T>
inline VarTable<V,A,T>* AvmmLogic<V,A,T>::get_table() {
return &table_;
}
template <size_t V, typename A, typename T>
inline const VarTable<V,A,T>* AvmmLogic<V,A,T>::get_table() const {
return &table_;
}
template <size_t V, typename A, typename T>
inline State* AvmmLogic<V,A,T>::get_state() {
auto* s = new State();
for (const auto& sv : state_) {
table_.read_var(slot_, sv.second);
s->insert(sv.first, eval_.get_array_value(sv.second));
}
return s;
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::set_state(const State* s) {
table_.write_control_var(table_.reset_index(), 1);
for (const auto& sv : state_) {
const auto itr = s->find(sv.first);
if (itr != s->end()) {
table_.write_var(slot_, sv.second, itr->second);
}
}
table_.write_control_var(table_.reset_index(), 1);
table_.write_control_var(table_.resume_index(), 1);
}
template <size_t V, typename A, typename T>
inline Input* AvmmLogic<V,A,T>::get_input() {
auto* i = new Input();
for (size_t v = 0, ve = inputs_.size(); v < ve; ++v) {
const auto* id = inputs_[v];
if (id == nullptr) {
continue;
}
table_.read_var(slot_, id);
i->insert(v, eval_.get_value(id));
}
return i;
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::set_input(const Input* i) {
table_.write_control_var(table_.reset_index(), 1);
for (size_t v = 0, ve = inputs_.size(); v < ve; ++v) {
const auto* id = inputs_[v];
if (id == nullptr) {
continue;
}
const auto itr = i->find(v);
if (itr != i->end()) {
table_.write_var(slot_, id, itr->second);
}
}
table_.write_control_var(table_.reset_index(), 1);
table_.write_control_var(table_.resume_index(), 1);
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::finalize() {
// Iterate over tasks. Now that we have the program state in place, we can
// cache pointers to streams to make system task handling faster. Remember,
// the task index starts from 1.
stream_cache_.resize(tasks_.size(), std::make_pair(0, nullptr));
for (size_t i = 1, ie = tasks_.size(); i < ie; ++i) {
const auto* t = tasks_[i];
const Expression* fd = nullptr;
switch (t->get_tag()) {
case Node::Tag::get_statement:
fd = static_cast<const GetStatement*>(t)->get_fd();
break;
case Node::Tag::fflush_statement:
fd = static_cast<const FflushStatement*>(t)->get_fd();
break;
case Node::Tag::put_statement:
fd = static_cast<const PutStatement*>(t)->get_fd();
break;
case Node::Tag::fseek_statement:
fd = static_cast<const FseekStatement*>(t)->get_fd();
break;
default:
continue;
}
fd->accept(&sync_);
const auto fd_val = eval_.get_value(fd).to_uint();
stream_cache_[i] = make_pair(fd_val, get_stream(fd_val));
}
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::read(VId id, const Bits* b) {
assert(id < inputs_.size());
assert(inputs_[id] != nullptr);
table_.write_var(slot_, inputs_[id], *b);
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::evaluate() {
there_were_tasks_ = false;
while (handle_tasks()) {
table_.write_control_var(table_.resume_index(), 1);
}
for (const auto& o : outputs_) {
table_.read_var(slot_, o.first);
interface()->write(o.second, &eval_.get_value(o.first));
}
}
template <size_t V, typename A, typename T>
inline bool AvmmLogic<V,A,T>::there_are_updates() const {
return table_.read_control_var(table_.there_are_updates_index()) != 0;
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::update() {
table_.write_control_var(table_.apply_update_index(), 1);
evaluate();
}
template <size_t V, typename A, typename T>
inline bool AvmmLogic<V,A,T>::there_were_tasks() const {
return there_were_tasks_;
}
template <size_t V, typename A, typename T>
inline size_t AvmmLogic<V,A,T>::open_loop(VId clk, bool val, size_t itr) {
// The fpga already knows the value of clk. We can ignore it.
(void) clk;
(void) val;
there_were_tasks_ = false;
// Setting the open loop variable allows the continue flag to span clock
// ticks. Loop here either until control returns without having hit a task
// (indicating that we've finished) or it trips a task that requires
// immediate attention.
table_.write_control_var(table_.open_loop_index(), itr);
while (handle_tasks() && !there_were_tasks_) {
table_.write_control_var(table_.resume_index(), 1);
}
// If we hit a task that requires immediate attention, clear the open loop
// counter, finish out this clock, and return the number of iterations that
// we ran for. Otherwise, we finished our quota.
if (there_were_tasks_) {
const auto res = table_.read_control_var(table_.open_loop_index());
table_.write_control_var(table_.open_loop_index(), 0);
while (handle_tasks()) {
table_.write_control_var(table_.resume_index(), 1);
}
return res;
} else {
return itr;
}
}
template <size_t V, typename A, typename T>
inline const Identifier* AvmmLogic<V,A,T>::open_loop_clock() {
ModuleInfo info(src_);
if (info.inputs().size() != 1) {
return nullptr;
}
if (eval_.get_width(*info.inputs().begin()) != 1) {
return nullptr;
}
if (!info.outputs().empty()) {
return nullptr;
}
return *ModuleInfo(src_).inputs().begin();
}
template <size_t V, typename A, typename T>
inline bool AvmmLogic<V,A,T>::is_constant(const Expression* e) const {
// Numbers are constants
if (e->is(Node::Tag::number)) {
return true;
}
// Anything other than an identifier might not be
if (!e->is(Node::Tag::identifier)) {
return false;
}
// Resolve this id
const auto* id = static_cast<const Identifier*>(e);
const auto* r = Resolve().get_resolution(id);
assert(r != nullptr);
// Anything other than a reg declaration might not be a constant
const auto* p = r->get_parent();
if (!p->is(Node::Tag::reg_declaration)) {
return false;
}
// Anything other than a number or fopen val might not be constant
const auto* d = static_cast<const RegDeclaration*>(p);
const auto fo = d->get_val()->is(Node::Tag::fopen_expression);
const auto n = d->get_val()->is(Node::Tag::number);
if (!fo && !n) {
return false;
}
// If this fd ever appears on the lhs of an assignment, it might not be a constant
for (auto i = Resolve().use_begin(r), ie = Resolve().use_end(r); i != ie; ++i) {
const auto* p = (*i)->get_parent();
switch (p->get_tag()) {
case Node::Tag::blocking_assign:
if (static_cast<const BlockingAssign*>(p)->get_lhs() == *i) {
return false;
}
break;
case Node::Tag::nonblocking_assign:
if (static_cast<const NonblockingAssign*>(p)->get_lhs() == *i) {
return false;
}
break;
case Node::Tag::variable_assign:
if (static_cast<const VariableAssign*>(p)->get_lhs() == *i) {
return false;
}
break;
default:
assert(false);
}
}
// This is definitely a constant
return true;
}
template <size_t V, typename A, typename T>
inline interfacestream* AvmmLogic<V,A,T>::get_stream(FId fd) {
const auto itr = streams_.find(fd);
if (itr != streams_.end()) {
return itr->second;
}
auto* is = new interfacestream(interface(), fd);
streams_[fd] = is;
return is;
}
template <size_t V, typename A, typename T>
inline bool AvmmLogic<V,A,T>::handle_tasks() {
volatile auto task_id = table_.read_control_var(table_.there_were_tasks_index());
if (task_id == 0) {
return false;
}
assert(task_id != T(-1));
const auto* task = tasks_[task_id];
switch (task->get_tag()) {
case Node::Tag::debug_statement: {
const auto* ds = static_cast<const DebugStatement*>(task);
std::stringstream ss;
ss << ds->get_arg();
interface()->debug(eval_.get_value(ds->get_action()).to_uint(), ss.str());
break;
}
case Node::Tag::finish_statement: {
const auto* fs = static_cast<const FinishStatement*>(task);
fs->accept_arg(&sync_);
interface()->finish(eval_.get_value(fs->get_arg()).to_uint());
there_were_tasks_ = true;
break;
}
case Node::Tag::fflush_statement: {
const auto* fs = static_cast<const FflushStatement*>(task);
auto is = stream_cache_[task_id];
if (is.second == nullptr) {
fs->accept_fd(&sync_);
is.first = eval_.get_value(fs->get_fd()).to_uint();
is.second = get_stream(is.first);
}
is.second->clear();
is.second->flush();
table_.write_control_var(table_.feof_index(), (is.first << 1) | is.second->eof());
break;
}
case Node::Tag::fseek_statement: {
const auto* fs = static_cast<const FseekStatement*>(task);
auto is = stream_cache_[task_id];
if (is.second == nullptr) {
fs->accept_fd(&sync_);
is.first = eval_.get_value(fs->get_fd()).to_uint();
is.second = get_stream(is.first);
}
const auto offset = eval_.get_value(fs->get_offset()).to_uint();
const auto op = eval_.get_value(fs->get_op()).to_uint();
const auto way = (op == 0) ? std::ios_base::beg : (op == 1) ? std::ios_base::cur : std::ios_base::end;
is.second->clear();
is.second->seekg(offset, way);
is.second->seekp(offset, way);
table_.write_control_var(table_.feof_index(), (is.first << 1) | is.second->eof());
break;
}
case Node::Tag::get_statement: {
const auto* gs = static_cast<const GetStatement*>(task);
auto is = stream_cache_[task_id];
if (is.second == nullptr) {
gs->accept_fd(&sync_);
is.first = eval_.get_value(gs->get_fd()).to_uint();
is.second = get_stream(is.first);
}
scanf_.read_without_update(*is.second, &eval_, gs);
if (gs->is_non_null_var()) {
const auto* r = Resolve().get_resolution(gs->get_var());
assert(r != nullptr);
table_.write_var(slot_, r, scanf_.get());
}
if (is.second->eof()) {
table_.write_control_var(table_.feof_index(), (is.first << 1) | 1);
}
break;
}
case Node::Tag::put_statement: {
const auto* ps = static_cast<const PutStatement*>(task);
auto is = stream_cache_[task_id];
if (is.second == nullptr) {
ps->accept_fd(&sync_);
is.first = eval_.get_value(ps->get_fd()).to_uint();
is.second = get_stream(is.first);
}
ps->accept_expr(&sync_);
printf_.write(*is.second, &eval_, ps);
if (is.second->eof()) {
table_.write_control_var(table_.feof_index(), (is.first << 1) | 1);
}
break;
}
case Node::Tag::restart_statement: {
const auto* rs = static_cast<const RestartStatement*>(task);
interface()->restart(rs->get_arg()->get_readable_val());
there_were_tasks_ = true;
break;
}
case Node::Tag::retarget_statement: {
const auto* rs = static_cast<const RetargetStatement*>(task);
interface()->retarget(rs->get_arg()->get_readable_val());
there_were_tasks_ = true;
break;
}
case Node::Tag::save_statement: {
const auto* ss = static_cast<const SaveStatement*>(task);
interface()->save(ss->get_arg()->get_readable_val());
there_were_tasks_ = true;
break;
}
default:
assert(false);
break;
}
return true;
}
template <size_t V, typename A, typename T>
inline AvmmLogic<V,A,T>::Inserter::Inserter(AvmmLogic* av) : Visitor() {
av_ = av;
in_args_ = false;
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::Inserter::visit(const Identifier* id) {
Visitor::visit(id);
const auto* r = Resolve().get_resolution(id);
if (in_args_ && (av_->table_.find(r) == av_->table_.end())) {
av_->table_.insert(r);
}
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::Inserter::visit(const FeofExpression* fe) {
// Don't insert this into the task index
in_args_ = true;
fe->accept_fd(this);
in_args_ = false;
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::Inserter::visit(const DebugStatement* ds) {
av_->tasks_.push_back(ds);
// Don't descend, there aren't any expressions below here
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::Inserter::visit(const FflushStatement* fs) {
av_->tasks_.push_back(fs);
in_args_ = true;
fs->accept_fd(this);
in_args_ = false;
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::Inserter::visit(const FinishStatement* fs) {
av_->tasks_.push_back(fs);
in_args_ = true;
fs->accept_arg(this);
in_args_ = false;
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::Inserter::visit(const FseekStatement* fs) {
av_->tasks_.push_back(fs);
in_args_ = true;
fs->accept_fd(this);
in_args_ = false;
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::Inserter::visit(const GetStatement* gs) {
av_->tasks_.push_back(gs);
in_args_ = true;
gs->accept_fd(this);
in_args_ = false;
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::Inserter::visit(const PutStatement* ps) {
av_->tasks_.push_back(ps);
in_args_ = true;
ps->accept_fd(this);
ps->accept_expr(this);
in_args_ = false;
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::Inserter::visit(const RestartStatement* rs) {
av_->tasks_.push_back(rs);
in_args_ = true;
rs->accept_arg(this);
in_args_ = false;
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::Inserter::visit(const RetargetStatement* rs) {
av_->tasks_.push_back(rs);
in_args_ = true;
rs->accept_arg(this);
in_args_ = false;
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::Inserter::visit(const SaveStatement* ss) {
av_->tasks_.push_back(ss);
in_args_ = true;
ss->accept_arg(this);
in_args_ = false;
}
template <size_t V, typename A, typename T>
inline AvmmLogic<V,A,T>::Sync::Sync(AvmmLogic* av) : Visitor() {
av_ = av;
}
template <size_t V, typename A, typename T>
inline void AvmmLogic<V,A,T>::Sync::visit(const Identifier* id) {
id->accept_dim(this);
const auto* r = Resolve().get_resolution(id);
assert(r != nullptr);
assert(av_->table_.find(r) != av_->table_.end());
av_->table_.read_var(av_->slot_, r);
}
} // namespace cascade::avmm
#endif
| 8,750 |
348 |
{"nom":"Heining-lès-Bouzonville","circ":"7ème circonscription","dpt":"Moselle","inscrits":266,"abs":147,"votants":119,"blancs":6,"nuls":0,"exp":113,"res":[{"nuance":"REM","nom":"<NAME>","voix":71},{"nuance":"FN","nom":"<NAME>","voix":42}]}
| 98 |
2,177 |
<gh_stars>1000+
package org.nutz.lang.reflect;
public interface FastMethod {
Object invoke(Object obj, Object ... args) throws Exception;
}
| 50 |
2,085 |
def test():
assert (
"for doc in nlp.pipe(TEXTS)" in __solution__
), "Are you iterating over docs yielded by nlp.pipe?"
__msg__.good("Nice!")
| 68 |
1,449 |
#include <QSharedPointer>
#include <QStringList>
#include "models/image.h"
#include "tags/tag.h"
#include "catch.h"
#include "integration-helpers.h"
TEST_CASE("Booru.org")
{
SECTION("Html")
{
QList<QSharedPointer<Image>> images = getImages("Gelbooru (0.1)", "rm.booru.org", "regex", "rating:safe", "results.html");
// Convert results
QStringList md5s;
md5s.reserve(images.count());
for (const auto &img : images) {
md5s.append(img->md5());
}
// Check results
md5s = md5s.mid(0, 3);
QStringList expected = QStringList() << "88407041cfd2d8358dda2f8699bfe98d84a7cf74" << "e0c2ddaf9403901cc1e293bcd369806d1deffd95" << "44f0f9560431d1b61ba1e9c401fdb3cc75920b38";
REQUIRE(images.count() == 20);
REQUIRE(md5s == expected);
}
SECTION("PageTags")
{
QList<Tag> tags = getPageTags("Gelbooru (0.1)", "rm.booru.org", "regex", "rating:safe", "results.html");
REQUIRE(tags.count() == 5);
REQUIRE(tags[0].text() == QString("barasuishou"));
REQUIRE(tags[0].count() == 4825);
REQUIRE(tags[1].text() == QString("image"));
REQUIRE(tags[1].count() == 94810);
REQUIRE(tags[2].text() == QString("rozen_maiden"));
REQUIRE(tags[2].count() == 125996);
}
}
| 528 |
14,668 |
<gh_stars>1000+
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.gesturenav;
import android.graphics.RectF;
import android.view.ViewGroup;
import org.chromium.chrome.browser.layouts.EventFilter;
import org.chromium.chrome.browser.layouts.SceneOverlay;
import org.chromium.chrome.browser.layouts.components.VirtualView;
import org.chromium.chrome.browser.layouts.scene_layer.SceneOverlayLayer;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.ui.resources.ResourceManager;
import java.util.List;
/**
* Handles overscroll glow effect when gesture navigation can't go forward any more.
* Renders the effect on a compositor layer in scene overlay layer tree.
*/
class OverscrollGlowOverlay extends NavigationGlow implements SceneOverlay {
private final OverscrollSceneLayer mSceneLayer;
private final Runnable mRequestLayerUpdate;
// True while the overlay is visible for showing overscroll effect.
private boolean mIsShowing;
private float mOffset;
OverscrollGlowOverlay(WindowAndroid window, ViewGroup parentView, Runnable requestLayerUpdate) {
super(parentView);
mSceneLayer = new OverscrollSceneLayer(window, parentView);
mRequestLayerUpdate = requestLayerUpdate;
}
// NavigationGlow implementation
@Override
public void prepare(float startX, float startY) {
mSceneLayer.prepare(startX, startY);
setIsShowing(true);
}
private void setIsShowing(boolean isShowing) {
mIsShowing = isShowing;
mOffset = 0.f;
}
@Override
public void onScroll(float offset) {
mOffset = offset;
if (mIsShowing) mRequestLayerUpdate.run();
}
@Override
public void release() {
mSceneLayer.release();
mOffset = 0.f;
}
@Override
public void reset() {
setIsShowing(false);
mSceneLayer.reset();
}
@Override
public void destroy() {
mSceneLayer.destroy();
}
// SceneOverlay implementation
@Override
public SceneOverlayLayer getUpdatedSceneOverlayTree(
RectF viewport, RectF visibleViewport, ResourceManager resourceManager, float yOffset) {
if (!mSceneLayer.update(resourceManager, mOffset)) setIsShowing(false);
return mSceneLayer;
}
@Override
public boolean isSceneOverlayTreeShowing() {
return mIsShowing;
}
@Override
public EventFilter getEventFilter() {
return null;
}
@Override
public void onSizeChanged(
float width, float height, float visibleViewportOffsetY, int orientation) {}
@Override
public void getVirtualViews(List<VirtualView> views) {}
@Override
public boolean shouldHideAndroidBrowserControls() {
return false;
}
@Override
public boolean updateOverlay(long time, long dt) {
return true;
}
@Override
public boolean onBackPressed() {
return false;
}
@Override
public boolean handlesTabCreating() {
return false;
}
}
| 1,132 |
1,090 |
<filename>buildSrc/src/main/java/com/uber/okbuck/core/model/base/SourceSetType.java
package com.uber.okbuck.core.model.base;
public enum SourceSetType {
MAIN,
TEST,
INTEGRATION_TEST
}
| 75 |
312 |
from datetime import datetime
from django.contrib.sessions.models import Session
from django.core.cache import cache
#from apps.forum.views import get_online_count
from apps.support.models import QQ
from apps.forum.models import Forum
from django import template
from django.utils.timezone import now, timedelta
from apps.user.models import User
register = template.Library()
@register.inclusion_tag('pc/aside/forum_side.html')
def get_fourm():
qq = QQ.objects.all()
fourm = Forum.objects.filter(hidden=False,category__name='求职招聘')[:10]
sessions = Session.objects.filter(expire_date__gte=datetime.now()).count()
#print(get_online_count())
user = User.objects.count()
cur_date = now().date() + timedelta(days=0)
days = Forum.objects.filter(hidden=False,add_time__gte=cur_date).count()
count = Forum.objects.filter(hidden=False).count()
Hottest = Forum.objects.filter(hidden=False).order_by('-click_nums')[:10]
return {'fourm':fourm,'qq':qq,'user':user,'sessions':sessions,'days':days,'count':count,'Hottest':Hottest}
@register.filter
def get_count(x):
return x.filter(hidden=False).count()
@register.filter
def get_counts(x):
return x.filter(is_show=True).count()
| 434 |
349 |
/*
* Copyright (C) 2016-2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.tomakehurst.wiremock.standalone;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.ok;
import static com.github.tomakehurst.wiremock.testsupport.TestFiles.filePath;
import static com.google.common.base.Charsets.UTF_8;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.fail;
import com.github.tomakehurst.wiremock.common.ClasspathFileSource;
import com.github.tomakehurst.wiremock.common.NotWritableException;
import com.github.tomakehurst.wiremock.common.SingleRootFileSource;
import com.github.tomakehurst.wiremock.stubbing.InMemoryStubMappings;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import com.google.common.io.Files;
import java.io.File;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
public class JsonFileMappingsSourceTest {
@TempDir public File tempDir;
InMemoryStubMappings stubMappings;
JsonFileMappingsSource source;
File stubMappingFile;
@BeforeEach
public void init() throws Exception {
stubMappings = new InMemoryStubMappings();
}
private void configureWithMultipleMappingFile() throws Exception {
stubMappingFile = File.createTempFile("multi", ".json", tempDir);
Files.copy(new File(filePath("multi-stub/multi.json")), stubMappingFile);
load();
}
private void configureWithSingleMappingFile() throws Exception {
stubMappingFile = File.createTempFile("single", ".json", tempDir);
Files.copy(new File(filePath("multi-stub/single.json")), stubMappingFile);
load();
}
private void load() {
source = new JsonFileMappingsSource(new SingleRootFileSource(tempDir));
source.loadMappingsInto(stubMappings);
}
@Test
public void loadsMappingsViaClasspathFileSource() {
ClasspathFileSource fileSource = new ClasspathFileSource("jar-filesource");
JsonFileMappingsSource source = new JsonFileMappingsSource(fileSource);
InMemoryStubMappings stubMappings = new InMemoryStubMappings();
source.loadMappingsInto(stubMappings);
List<StubMapping> allMappings = stubMappings.getAll();
assertThat(allMappings, hasSize(2));
List<String> mappingRequestUrls =
asList(allMappings.get(0).getRequest().getUrl(), allMappings.get(1).getRequest().getUrl());
assertThat(mappingRequestUrls, is(asList("/second_test", "/test")));
}
@Test
public void stubMappingFilesAreWrittenWithInsertionIndex() throws Exception {
JsonFileMappingsSource source = new JsonFileMappingsSource(new SingleRootFileSource(tempDir));
StubMapping stub = get("/saveable").willReturn(ok()).build();
source.save(stub);
File savedFile = tempDir.listFiles()[0];
String savedStub = FileUtils.readFileToString(savedFile, UTF_8);
assertThat(savedStub, containsString("\"insertionIndex\" : 0"));
}
@Test
public void refusesToRemoveStubMappingContainedInMultiFile() throws Exception {
configureWithMultipleMappingFile();
StubMapping firstStub = stubMappings.getAll().get(0);
try {
source.remove(firstStub);
fail("Expected an exception to be thrown");
} catch (Exception e) {
assertThat(e, Matchers.instanceOf(NotWritableException.class));
assertThat(
e.getMessage(),
is(
"Stubs loaded from multi-mapping files are read-only, and therefore cannot be removed"));
}
assertThat(stubMappingFile.exists(), is(true));
}
@Test
public void refusesToRemoveAllWhenMultiMappingFilesArePresent() throws Exception {
configureWithMultipleMappingFile();
try {
source.removeAll();
fail("Expected an exception to be thrown");
} catch (Exception e) {
assertThat(e, Matchers.instanceOf(NotWritableException.class));
assertThat(
e.getMessage(),
is(
"Some stubs were loaded from multi-mapping files which are read-only, so remove all cannot be performed"));
}
assertThat(stubMappingFile.exists(), is(true));
}
@Test
public void refusesToSaveStubMappingOriginallyLoadedFromMultiMappingFile() throws Exception {
configureWithMultipleMappingFile();
StubMapping firstStub = stubMappings.getAll().get(0);
try {
source.save(firstStub);
fail("Expected an exception to be thrown");
} catch (Exception e) {
assertThat(e, Matchers.instanceOf(NotWritableException.class));
assertThat(
e.getMessage(),
is("Stubs loaded from multi-mapping files are read-only, and therefore cannot be saved"));
}
assertThat(stubMappingFile.exists(), is(true));
}
@Test
public void savesStubMappingOriginallyLoadedFromSingleMappingFile() throws Exception {
configureWithSingleMappingFile();
StubMapping firstStub = stubMappings.getAll().get(0);
firstStub.setName("New name");
source.save(firstStub);
assertThat(FileUtils.readFileToString(stubMappingFile, UTF_8), containsString("New name"));
}
@Test
public void removesStubMappingOriginallyLoadedFromSingleMappingFile() throws Exception {
configureWithSingleMappingFile();
StubMapping firstStub = stubMappings.getAll().get(0);
source.remove(firstStub);
assertThat(stubMappingFile.exists(), is(false));
}
}
| 2,063 |
605 |
#include "libvim.h"
#include "minunit.h"
void test_setup(void)
{
vimExecute("e!");
vimInput("g");
vimInput("g");
vimInput("0");
}
void test_teardown(void) {}
MU_TEST(test_jumplist_openfile)
{
buf_T *firstBuf = vimBufferOpen("collateral/testfile.txt", 1, 0);
buf_T *secondBuf = vimBufferOpen("collateral/lines_100.txt", 1, 0);
mu_check(firstBuf != secondBuf);
mu_check(curbuf == secondBuf);
vimKey("<c-o>");
mu_check(curbuf == firstBuf);
vimKey("<c-i>");
mu_check(curbuf == secondBuf);
}
MU_TEST(test_jumplist_editnew)
{
buf_T *firstBuf = vimBufferOpen("collateral/testfile.txt", 1, 0);
vimExecute("e! collateral/a_new_file.txt");
buf_T *secondBuf = curbuf;
mu_check(firstBuf != secondBuf);
mu_check(curbuf == secondBuf);
vimKey("<c-o>");
mu_check(curbuf == firstBuf);
vimKey("<c-i>");
mu_check(curbuf == secondBuf);
}
MU_TEST_SUITE(test_suite)
{
MU_SUITE_CONFIGURE(&test_setup, &test_teardown);
MU_RUN_TEST(test_jumplist_openfile);
MU_RUN_TEST(test_jumplist_editnew);
}
int main(int argc, char **argv)
{
vimInit(argc, argv);
win_setwidth(5);
win_setheight(100);
vimBufferOpen("collateral/testfile.txt", 1, 0);
MU_RUN_SUITE(test_suite);
MU_REPORT();
MU_RETURN();
}
| 556 |
340 |
<gh_stars>100-1000
'''
A collection of utility functions.
'''
import numpy as np
import scipy.stats as stats
from typing import Iterable
def sim_seasonal_data(n_series, timesteps, measure_noise,
freq=None, level=None, amp=None):
"""Generate sinusoidal data with periodic patterns.
Parameters
----------
n_series : int
Number of timeseries to generate.
timesteps : int
How many timesteps every generated series must have.
measure_noise : int
The noise present in the signals.
freq : int or 1D array-like, default=None
The frequencies of the sinusoidal timeseries to generate.
If a single integer is passed, all the series generated have
the same frequencies. If a 1D array-like is passed, the
frequencies of timeseries are random sampled from the iterable
passed. If None, the frequencies are random generated.
level : int or 1D array-like, default=None
The levels of the sinusoidal timeseries to generate.
If a single integer is passed, all the series generated have
the same levels. If a 1D array-like is passed, the levels
of timeseries are random sampled from the iterable passed.
If None, the levels are random generated.
amp : int or 1D array-like, default=None
The amplitudes of the sinusoidal timeseries to generate.
If a single integer is passed, all the series generated have
the same amplitudes. If a 1D array-like is passed, the amplitudes
of timeseries are random sampled from the iterable passed.
If None, the amplitudes are random generated.
Returns
-------
data : array of shape (series, timesteps)
The generated sinusoidal timeseries.
"""
if freq is None:
freq = np.random.randint(3, int(np.sqrt(timesteps)), (n_series, 1))
elif isinstance(freq, Iterable):
freq = np.random.choice(freq, size=n_series)[:, None]
else:
freq = np.asarray([[freq]] * n_series)
if level is None:
level = np.random.uniform(-100, 100, (n_series, 1))
elif isinstance(level, Iterable):
level = np.random.choice(level, size=n_series)[:, None]
else:
level = np.asarray([[level]] * n_series)
if amp is None:
amp = np.random.uniform(3, 100, (n_series, 1))
elif isinstance(amp, Iterable):
amp = np.random.choice(amp, size=n_series)[:, None]
else:
amp = np.asarray([[amp]] * n_series)
t = np.repeat([np.arange(timesteps)], n_series, axis=0)
e = np.random.normal(0, measure_noise, (n_series, timesteps))
data = level + amp * np.sin(t * (2 * np.pi / freq)) + e
return data
def sim_randomwalk(n_series, timesteps, process_noise, measure_noise,
level=None):
"""Generate randomwalks.
Parameters
----------
n_series : int
Number of randomwalks to generate.
timesteps : int
How many timesteps every generated randomwalks must have.
process_noise : int
The noise present in randomwalks creation.
measure_noise : int
The noise present in the signals.
level : int or 1D array-like, default=None
The levels of the randomwalks to generate.
If a single integer is passed, all the randomwalks have
the same levels. If a 1D array-like is passed, the levels
of the randomwalks are random sampled from the iterable
passed. If None, the levels are set to 0 for all the series.
Returns
-------
data : array of shape (series, timesteps)
The generated randomwalks.
"""
if level is None:
level = 0
if isinstance(level, Iterable):
level = np.random.choice(level, size=n_series)[:, None]
else:
level = np.asarray([[level]] * n_series)
data = np.random.normal(0, process_noise, size=(n_series, timesteps))
e = np.random.normal(0, measure_noise, size=(n_series, timesteps))
data = level + np.cumsum(data, axis=1) + e
return data
def create_windows(data, window_shape, step=1,
start_id=None, end_id=None):
"""Create sliding windows of the same length from the series
received as input.
create_windows vectorizes, in an efficient way, the windows creation
on all the series received.
Parameters
----------
data : 2D array of shape (timestemps, series)
Timeseries to slide into equal size windows.
window_shape : int
Grather than 1. The shape of the sliding windows used to divide
the input series.
step : int, default=1
The step used to generate the sliding windows. The overlapping
portion of two adjacent windows can be defined as
(window_shape - step).
start_id : int, default=None
The starting position from where operate slicing. The same for
all the series. If None, the windows are generated from the index 0.
end_id : int, default=None
The ending position of the slicing operation. The same for all the
series. If None, the windows end on the last position available.
Returns
-------
window_data : 3D array of shape (window_slices, window_shape, series)
The input data sliced into windows of the same lengths.
"""
data = np.asarray(data)
if data.ndim != 2:
raise ValueError(
"Pass a 2D array-like in the format (timestemps, series)")
if window_shape < 1:
raise ValueError("window_shape must be >= 1")
if start_id is None:
start_id = 0
if end_id is None:
end_id = data.shape[0]
data = data[int(start_id):int(end_id), :]
window_shape = (int(window_shape), data.shape[-1])
step = (int(step),) * data.ndim
slices = tuple(slice(None, None, st) for st in step)
indexing_strides = data[slices].strides
win_indices_shape = ((np.array(data.shape) - window_shape) // step) + 1
new_shape = tuple(list(win_indices_shape) + list(window_shape))
strides = tuple(list(indexing_strides) + list(data.strides))
window_data = np.lib.stride_tricks.as_strided(
data, shape=new_shape, strides=strides)
return np.squeeze(window_data, 1)
def sigma_interval(true, prediction, n_sigma):
"""Compute smoothing intervals as n_sigma times the residuals of the
smoothing process.
Returns
-------
low : array
Lower bands.
up : array
Upper bands.
"""
std = np.nanstd(true - prediction, axis=1, keepdims=True)
low = prediction - n_sigma * std
up = prediction + n_sigma * std
return low, up
def kalman_interval(true, prediction, cov, confidence=0.05):
"""Compute smoothing intervals from a Kalman smoothing process.
Returns
-------
low : array
Lower bands.
up : array
Upper bands.
"""
g = stats.norm.ppf(1 - confidence / 2)
resid = true - prediction
std_err = np.sqrt(np.nanmean(np.square(resid), axis=1, keepdims=True))
low = prediction - g * (std_err * cov)
up = prediction + g * (std_err * cov)
return low, up
def confidence_interval(true, prediction, exog, confidence,
add_intercept=True):
"""Compute confidence intervals for regression tasks.
Returns
-------
low : array
Lower bands.
up : array
Upper bands.
"""
if exog.ndim == 1:
exog = exog[:, None]
if add_intercept:
exog = np.concatenate([np.ones((len(exog), 1)), exog], axis=1)
N = exog.shape[0]
d_free = exog.shape[1]
t = stats.t.ppf(1 - confidence / 2, N - d_free)
resid = true - prediction
mse = (np.square(resid).sum(axis=1, keepdims=True) / (N - d_free)).T
hat_matrix_diag = (exog * np.linalg.pinv(exog).T).sum(axis=1, keepdims=True)
predict_mean_se = np.sqrt(hat_matrix_diag * mse).T
low = prediction - t * predict_mean_se
up = prediction + t * predict_mean_se
return low, up
def prediction_interval(true, prediction, exog, confidence,
add_intercept=True):
"""Compute prediction intervals for regression tasks.
Returns
-------
low : array
Lower bands.
up : array
Upper bands.
"""
if exog.ndim == 1:
exog = exog[:, None]
if add_intercept:
exog = np.concatenate([np.ones((len(exog), 1)), exog], axis=1)
N = exog.shape[0]
d_free = exog.shape[1]
t = stats.t.ppf(1 - confidence / 2, N - d_free)
resid = true - prediction
mse = (np.square(resid).sum(axis=1, keepdims=True) / (N - d_free)).T
covb = np.linalg.pinv(np.dot(exog.T, exog))[..., None] * mse
predvar = mse + (exog[..., None] *
np.dot(covb.transpose(2, 0, 1), exog.T).T).sum(1)
predstd = np.sqrt(predvar).T
low = prediction - t * predstd
up = prediction + t * predstd
return low, up
def _check_noise_dict(noise_dict, component):
"""Ensure noise compatibility for the noises of the components
provided when building a state space model.
Returns
-------
noise_dict : dict
Checked input.
"""
sub_component = component.split('_')
if isinstance(noise_dict, dict):
for c in sub_component:
if c not in noise_dict:
raise ValueError(
"You need to provide noise for '{}' component".format(c))
if noise_dict[c] < 0:
raise ValueError(
"noise for '{}' must be >= 0".format(c))
return noise_dict
else:
raise ValueError(
"noise should be a dict. Received {}".format(type(noise_dict)))
def _check_knots(knots, min_n_knots):
"""Ensure knots compatibility for the knots provided when building
bases for linear regression.
Returns
-------
knots : array
Checked input.
"""
knots = np.asarray(knots, dtype=np.float64)
if np.prod(knots.shape) == np.max(knots.shape):
knots = knots.ravel()
if knots.ndim != 1:
raise ValueError("knots must be a list or 1D array")
knots = np.unique(knots)
min_k, max_k = knots[0], knots[-1]
if min_k < 0 or max_k > 1:
raise ValueError("Every knot must be in the range [0,1]")
if min_k > 0:
knots = np.append(0., knots)
if max_k < 1:
knots = np.append(knots, 1.)
if knots.shape[0] < min_n_knots + 2:
raise ValueError(
"Provide at least {} knots in the range (0,1)".format(min_n_knots))
return knots
def _check_weights(weights, basis_len):
"""Ensure weights compatibility for the weights provided in
linear regression applications.
Returns
-------
weights : array
Checked input.
"""
if weights is None:
return np.ones(basis_len, dtype=np.float64)
weights = np.asarray(weights, dtype=np.float64)
if np.prod(weights.shape) == np.max(weights.shape):
weights = weights.ravel()
if weights.ndim != 1:
raise ValueError("Sample weights must be a list or 1D array")
if weights.shape[0] != basis_len:
raise ValueError(
"Sample weights length must be equal to timesteps "
"dimension of the data received")
if np.any(weights < 0):
raise ValueError("weights must be >= 0")
if np.logical_or(np.isnan(weights), np.isinf(weights)).any():
raise ValueError("weights must not contain NaNs or Inf")
return weights
def _check_data(data):
"""Ensure data compatibility for the series received by the smoother.
Returns
-------
data : array
Checked input.
"""
data = np.asarray(data)
if np.prod(data.shape) == np.max(data.shape):
data = data.ravel()
if data.ndim > 2:
raise ValueError(
"The format of data received is not appropriate. "
"Pass an object with data in this format (series, timesteps)")
if data.ndim == 0:
raise ValueError(
"Pass an object with data in this format (series, timesteps)")
if data.dtype not in [np.float16, np.float32, np.float64,
np.int8, np.int16, np.int32, np.int64]:
raise ValueError("data contains not numeric types")
if np.logical_or(np.isnan(data), np.isinf(data)).any():
raise ValueError("data must not contain NaNs or Inf")
return data.T
def _check_data_nan(data):
"""Ensure data compatibility for the series received by the smoother.
(Without checking for inf and nans).
Returns
-------
data : array
Checked input.
"""
data = np.asarray(data)
if np.prod(data.shape) == np.max(data.shape):
data = data.ravel()
if data.ndim > 2:
raise ValueError(
"The format of data received is not appropriate. "
"Pass an objet with data in this format (series, timesteps)")
if data.ndim == 0:
raise ValueError(
"Pass an object with data in this format (series, timesteps)")
if data.dtype not in [np.float16, np.float32, np.float64,
np.int8, np.int16, np.int32, np.int64]:
raise ValueError("data contains not numeric types")
return data
def _check_output(output, transpose=True):
"""Ensure output compatibility for the series returned by the smoother.
Returns
-------
output : array
Checked input.
"""
if transpose:
output = output.T
if output.ndim == 1:
output = output[None, :]
return output
def _id_nb_bootstrap(n_obs, block_length):
"""Create bootstrapped indexes with the none overlapping block bootstrap
('nbb') strategy given the number of observations in a timeseries and
the length of the blocks.
Returns
-------
_id : array
Bootstrapped indexes.
"""
n_blocks = int(np.ceil(n_obs / block_length))
nexts = np.repeat([np.arange(0, block_length)], n_blocks, axis=0)
blocks = np.random.permutation(
np.arange(0, n_obs, block_length)
).reshape(-1, 1)
_id = (blocks + nexts).ravel()[:n_obs]
return _id
def _id_mb_bootstrap(n_obs, block_length):
"""Create bootstrapped indexes with the moving block bootstrap
('mbb') strategy given the number of observations in a timeseries
and the length of the blocks.
Returns
-------
_id : array
Bootstrapped indexes.
"""
n_blocks = int(np.ceil(n_obs / block_length))
nexts = np.repeat([np.arange(0, block_length)], n_blocks, axis=0)
last_block = n_obs - block_length
blocks = np.random.randint(0, last_block, (n_blocks, 1))
_id = (blocks + nexts).ravel()[:n_obs]
return _id
def _id_cb_bootstrap(n_obs, block_length):
"""Create bootstrapped indexes with the circular block bootstrap
('cbb') strategy given the number of observations in a timeseries
and the length of the blocks.
Returns
-------
_id : array
Bootstrapped indexes.
"""
n_blocks = int(np.ceil(n_obs / block_length))
nexts = np.repeat([np.arange(0, block_length)], n_blocks, axis=0)
last_block = n_obs
blocks = np.random.randint(0, last_block, (n_blocks, 1))
_id = np.mod((blocks + nexts).ravel(), n_obs)[:n_obs]
return _id
def _id_s_bootstrap(n_obs, block_length):
"""Create bootstrapped indexes with the stationary bootstrap
('sb') strategy given the number of observations in a timeseries
and the length of the blocks.
Returns
-------
_id : array
Bootstrapped indexes.
"""
random_block_length = np.random.poisson(block_length, n_obs)
random_block_length[random_block_length < 3] = 3
random_block_length[random_block_length >= n_obs] = n_obs
random_block_length = random_block_length[random_block_length.cumsum() <= n_obs]
residual_block = n_obs - random_block_length.sum()
if residual_block > 0:
random_block_length = np.append(random_block_length, residual_block)
n_blocks = random_block_length.shape[0]
nexts = np.zeros((n_blocks, random_block_length.max() + 1))
nexts[np.arange(n_blocks), random_block_length] = 1
nexts = np.flip(nexts, 1).cumsum(1).cumsum(1).ravel()
nexts = (nexts[nexts > 1] - 2).astype(int)
last_block = n_obs - random_block_length.max()
blocks = np.zeros(n_obs, dtype=int)
if last_block > 0:
blocks = np.random.randint(0, last_block, n_blocks)
blocks = np.repeat(blocks, random_block_length)
_id = blocks + nexts
return _id
| 6,695 |
743 |
<reponame>pipihi/nx<gh_stars>100-1000
#if defined(_MSC_VER) && _MSC_VER <= 1700
#include "msvc/headers/inttypes.h"
#else
#include <inttypes.h>
#endif
| 68 |
2,199 |
/*
* Copyright (c) 2016—2021 <NAME> and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package bt.net;
import org.junit.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static bt.TestUtil.assertExceptionWithMessage;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class ByteChannelReader_TimedSyncTest {
private static final Duration receiveTimeout = Duration.ofMillis(10);
private static final Duration waitBetweenReads = Duration.ofMillis(0);
/*************************************/
/******** Generic read tests *********/
/*************************************/
@Test
public void testReader_timedSync_NoMatch_ExactAmount_SingleBlock() throws IOException {
ReadByBlockChannel channel = createChannelWithTestData();
int[] limits = new int[] {10, 20, 30, 40, 50};
LimitingChannel limitedChannel = new LimitingChannel(channel, limits);
ByteChannelReader reader = testReader(limitedChannel);
ByteBuffer buf = ByteBuffer.allocate(100);
byte[] pattern = new byte[]{-1};
assertExceptionWithMessage(it -> {
try {
return reader.readExactly(50).sync(buf, pattern);
} catch (IOException e) {
throw new RuntimeException(e);
}
}, "Failed to synchronize: expected 50..50, received 50");
assertEquals(50, buf.position());
}
@Test
public void testReader_timedSync_NoMatch_ExactAmount_Unlimited() throws IOException {
byte[] part0 = new byte[100];
byte[] part1 = new byte[100];
byte[] part2 = new byte[100];
byte[] part3 = new byte[]{-1};
List<byte[]> data = new ArrayList<>(Arrays.asList(part0, part1, part2, part3));
ReadByBlockChannel channel = new ReadByBlockChannel(data);
int[] limits = new int[] {300, 300, 300, 301};
LimitingChannel limitedChannel = new LimitingChannel(channel, limits);
ByteChannelReader reader = testReader(limitedChannel);
ByteBuffer buf = ByteBuffer.allocate(301);
byte[] pattern = new byte[]{-1};
int read = reader.readExactly(301).sync(buf, pattern);
assertEquals(301, read);
assertEquals(buf.limit(), buf.position());
}
@Test
public void testReader_timedSync_NoMatch_ExactAmount_MultipleBlocks() throws IOException {
byte[] part0 = new byte[100];
byte[] part1 = new byte[100];
byte[] part2 = new byte[100];
byte[] part3 = new byte[]{-1};
Arrays.fill(part1, (byte) 1);
Arrays.fill(part2, (byte) 2);
List<byte[]> data = new ArrayList<>(Arrays.asList(part0, part1, part2, part3));
ReadByBlockChannel channel = new ReadByBlockChannel(data);
int[] limits = new int[] {10, 20, 100, 125, 160, 160, 230, 230, 300, 301};
LimitingChannel limitedChannel = new LimitingChannel(channel, limits);
ByteChannelReader reader = testReader(limitedChannel);
ByteBuffer buf = ByteBuffer.allocate(301);
int read = reader.readExactly(301).sync(buf, part3);
assertEquals(301, read);
assertEquals(buf.limit(), buf.position());
byte[] expected = new byte[301];
Arrays.fill(expected, 100, 200, (byte) 1);
Arrays.fill(expected, 200, 300, (byte) 2);
expected[expected.length - 1] = -1;
byte[] actual = new byte[301];
buf.flip();
buf.get(actual);
assertArrayEquals(expected, actual);
}
@Test
public void testReader_timedSync_NoMatch_InsufficientDataRead() throws IOException {
ReadByBlockChannel channel = createChannelWithTestData();
int[] limits = new int[] {10, 20, 30, 40, 50};
LimitingChannel limitedChannel = new LimitingChannel(channel, limits);
ByteChannelReader reader = testReader(limitedChannel);
ByteBuffer buf = ByteBuffer.allocate(100);
byte[] pattern = new byte[]{-1};
assertExceptionWithMessage(it -> {
try {
return reader.readExactly(60).sync(buf, pattern);
} catch (IOException e) {
throw new RuntimeException(e);
}
}, "Less than 60 bytes received: 50");
}
@Test
public void testReader_timedSync_NoMatch_ExcessiveDataRead() throws IOException {
ReadByBlockChannel channel = createChannelWithTestData();
int[] limits = new int[] {10, 20, 40};
LimitingChannel limitedChannel = new LimitingChannel(channel, limits);
ByteChannelReader reader = testReader(limitedChannel);
ByteBuffer buf = ByteBuffer.allocate(100);
byte[] pattern = new byte[]{-1};
assertExceptionWithMessage(it -> {
try {
return reader.readExactly(30).sync(buf, pattern);
} catch (IOException e) {
throw new RuntimeException(e);
}
}, "More than 30 bytes received: 40");
}
@Test
public void testReader_timedSync_NoMatch_EOF() throws IOException {
ReadByBlockChannel channel = createChannelWithTestData();
int[] limits = new int[] {10, 20, 30, 40, 50};
LimitingChannel limitedChannel = LimitingChannel.withEOF(channel, limits);
ByteChannelReader reader = testReader(limitedChannel);
ByteBuffer buf = ByteBuffer.allocate(100);
byte[] pattern = new byte[]{-1};
assertExceptionWithMessage(it -> {
try {
return reader.readExactly(60).sync(buf, pattern);
} catch (IOException e) {
throw new RuntimeException(e);
}
}, "Received EOF, total bytes read: 50, expected: 60..60");
}
/****************************************/
/******** Synchronization tests *********/
/****************************************/
/********** Single-byte pattern **********/
@Test
public void testReader_timedSync_Match_SingleBytePattern_BeginningOfStream() throws IOException {
ReadByBlockChannel channel = createChannelWithTestData();
int[] limits = new int[] {10, 20};
LimitingChannel limitedChannel = new LimitingChannel(channel, limits);
ByteChannelReader reader = testReader(limitedChannel);
ByteBuffer buf = ByteBuffer.allocate(100);
byte[] pattern = new byte[]{0};
int read = reader.readNoMoreThan(20).sync(buf, pattern);
assertEquals(20, read);
assertEquals(1, buf.position());
}
@Test
public void testReader_timedSync_Match_SingleBytePattern_MiddleOfStream() throws IOException {
ReadByBlockChannel channel = createChannelWithTestData();
int[] limits = new int[] {10, 20, 75, 125, 125};
LimitingChannel limitedChannel = new LimitingChannel(channel, limits);
ByteChannelReader reader = testReader(limitedChannel);
ByteBuffer buf = ByteBuffer.allocate(300);
byte[] pattern = new byte[]{1};
int read = reader.readNoMoreThan(125).sync(buf, pattern);
assertEquals(125, read);
assertEquals(101, buf.position());
}
@Test
public void testReader_timedSync_Match_SingleBytePattern_EndOfStream() throws IOException {
byte[] part0 = new byte[100];
byte[] part1 = new byte[100];
byte[] part2 = new byte[1];
Arrays.fill(part1, (byte) 1);
Arrays.fill(part2, (byte) 2);
List<byte[]> data = new ArrayList<>(Arrays.asList(part0, part1, part2));
ReadByBlockChannel channel = new ReadByBlockChannel(data);
int[] limits = new int[] {10, 20, 75, 125, 200, 201};
LimitingChannel limitedChannel = new LimitingChannel(channel, limits);
ByteChannelReader reader = testReader(limitedChannel);
ByteBuffer buf = ByteBuffer.allocate(300);
byte[] pattern = new byte[]{2};
int read = reader.readNoMoreThan(201).sync(buf, pattern);
assertEquals(201, read);
assertEquals(201, buf.position());
}
/********** Multi-byte pattern **********/
@Test
public void testReader_timedSync_Match_MultiBytePattern_ShorterThanReadBlock_BeginningOfStream() throws IOException {
ReadByBlockChannel channel = createChannelWithTestData();
int[] limits = new int[] {10};
LimitingChannel limitedChannel = new LimitingChannel(channel, limits);
ByteChannelReader reader = testReader(limitedChannel);
ByteBuffer buf = ByteBuffer.allocate(100);
byte[] pattern = new byte[]{0,0,0,0,0};
int read = reader.readNoMoreThan(10).sync(buf, pattern);
assertEquals(10, read);
assertEquals(pattern.length, buf.position());
}
@Test
public void testReader_timedSync_Match_MultiBytePattern_ShorterThanReadBlock_MiddleOfStream() throws IOException {
ReadByBlockChannel channel = createChannelWithTestData();
int[] limits = new int[] {100, 200};
LimitingChannel limitedChannel = new LimitingChannel(channel, limits);
ByteChannelReader reader = testReader(limitedChannel);
ByteBuffer buf = ByteBuffer.allocate(300);
byte[] pattern = new byte[]{1,1,1,1,1};
int read = reader.readNoMoreThan(200).sync(buf, pattern);
assertEquals(200, read);
assertEquals(100 + pattern.length, buf.position());
}
@Test
public void testReader_timedSync_Match_MultiBytePattern_ShorterThanReadBlock_EndOfStream() throws IOException {
byte[] part0 = new byte[100];
byte[] part1 = new byte[100];
byte[] part2 = new byte[10];
Arrays.fill(part1, (byte) 1);
Arrays.fill(part2, (byte) 2);
ReadByBlockChannel channel = new ReadByBlockChannel(Arrays.asList(part0, part1, part2));
int[] limits = new int[] {100, 200, 210};
LimitingChannel limitedChannel = new LimitingChannel(channel, limits);
ByteChannelReader reader = testReader(limitedChannel);
ByteBuffer buf = ByteBuffer.allocate(300);
byte[] pattern = new byte[]{2,2,2,2,2};
int read = reader.readNoMoreThan(210).sync(buf, pattern);
assertEquals(210, read);
assertEquals(200 + pattern.length, buf.position());
}
@Test
public void testReader_timedSync_Match_MultiBytePattern_LongerThanReadBlock_BeginningOfStream() throws IOException {
ReadByBlockChannel channel = createChannelWithTestData();
int[] limits = new int[] {10, 20, 30};
LimitingChannel limitedChannel = new LimitingChannel(channel, limits);
ByteChannelReader reader = testReader(limitedChannel);
ByteBuffer buf = ByteBuffer.allocate(100);
byte[] pattern = new byte[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int read = reader.readNoMoreThan(30).sync(buf, pattern);
assertEquals(30, read);
assertEquals(pattern.length, buf.position());
}
@Test
public void testReader_timedSync_Match_MultiBytePattern_LongerThanReadBlock_MiddleOfStream() throws IOException {
ReadByBlockChannel channel = createChannelWithTestData();
int[] limits = new int[] {90, 100, 120, 130};
LimitingChannel limitedChannel = new LimitingChannel(channel, limits);
ByteChannelReader reader = testReader(limitedChannel);
ByteBuffer buf = ByteBuffer.allocate(200);
byte[] pattern = new byte[]{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,};
int read = reader.readNoMoreThan(130).sync(buf, pattern);
assertEquals(130, read);
assertEquals(100 + pattern.length, buf.position());
}
@Test
public void testReader_timedSync_Match_MultiBytePattern_LongerThanReadBlock_EndOfStream() throws IOException {
byte[] part0 = new byte[100];
byte[] part1 = new byte[100];
byte[] part2 = new byte[30];
Arrays.fill(part1, (byte) 1);
Arrays.fill(part2, (byte) 2);
ReadByBlockChannel channel = new ReadByBlockChannel(Arrays.asList(part0, part1, part2));
int[] limits = new int[] {100, 200, 210, 220, 230};
LimitingChannel limitedChannel = new LimitingChannel(channel, limits);
ByteChannelReader reader = testReader(limitedChannel);
ByteBuffer buf = ByteBuffer.allocate(300);
byte[] pattern = new byte[]{2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,};
int read = reader.readNoMoreThan(230).sync(buf, pattern);
assertEquals(230, read);
assertEquals(200 + pattern.length, buf.position());
}
private static ReadByBlockChannel createChannelWithTestData() {
byte[] part0 = new byte[100];
byte[] part1 = new byte[100];
byte[] part2 = new byte[100];
Arrays.fill(part1, (byte) 1);
Arrays.fill(part2, (byte) 2);
List<byte[]> data = new ArrayList<>(Arrays.asList(part0, part1, part2));
return new ReadByBlockChannel(data);
}
private static ByteChannelReader testReader(ReadableByteChannel channel) {
return ByteChannelReader.forChannel(channel).withTimeout(receiveTimeout).waitBetweenReads(waitBetweenReads);
}
}
| 5,333 |
2,542 |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Management;
using namespace BackupRestoreAgentComponent;
RestoreOperationResultMessageBody::RestoreOperationResultMessageBody()
{
}
RestoreOperationResultMessageBody::RestoreOperationResultMessageBody(wstring serviceName, Common::Guid partitionId, Common::Guid operationId, HRESULT errorCode, Common::DateTime operationTimestampUtc, wstring message) :
serviceName_(serviceName),
partitionId_(partitionId),
operationId_(operationId),
errorCode_(errorCode),
operationTimestampUtc_(operationTimestampUtc),
message_(message)
{
}
RestoreOperationResultMessageBody::RestoreOperationResultMessageBody(const FABRIC_RESTORE_OPERATION_RESULT& operationResult) :
serviceName_(operationResult.ServiceName),
partitionId_(operationResult.PartitionId),
operationId_(operationResult.OperationId),
operationTimestampUtc_(operationResult.TimeStampUtc)
{
errorCode_ = operationResult.ErrorCode;
if (operationResult.Message != NULL)
{
Common::StringUtility::LpcwstrToTruncatedWstring(operationResult.Message, false, 0, 4096, message_);
}
}
RestoreOperationResultMessageBody::~RestoreOperationResultMessageBody()
{
}
| 412 |
973 |
package org.pcap4j.util;
import static org.junit.Assert.*;
import org.junit.Test;
@SuppressWarnings("javadoc")
public class ByteArraysTest {
@Test
public void testToHexString() throws Exception {
byte[] arr =
new byte[] {
(byte) 0x0,
(byte) 0x1,
(byte) 0x2,
(byte) 0x3,
(byte) 0x4,
(byte) 0x55,
(byte) 0x56,
(byte) 0x57,
(byte) 0x58,
(byte) 0x59,
(byte) 0xaa,
(byte) 0xab,
(byte) 0xac,
(byte) 0xad,
(byte) 0xae,
(byte) 0xaf,
(byte) 0xfa,
(byte) 0xfb,
(byte) 0xfc,
(byte) 0xfd,
(byte) 0xfe,
(byte) 0xff
};
assertEquals(
"00:01:02:03:04:55:56:57:58:59:aa:ab:ac:ad:ae:af:fa:fb:fc:fd:fe:ff",
ByteArrays.toHexString(arr, ":"));
assertEquals(
"00 : 01 : 02 : 03 : 04 : 55 : 56 : 57 : 58 : 59 : aa : ab : ac : ad : ae : af : fa : fb : fc : fd : fe : ff",
ByteArrays.toHexString(arr, " : "));
assertEquals("55-56-57-58-59", ByteArrays.toHexString(arr, "-", 5, 5));
assertEquals("aaabacadaeaf", ByteArrays.toHexString(arr, "", 10, 6));
}
}
| 719 |
30,023 |
"""Config flow for SiteSage Emonitor integration."""
import logging
from aioemonitor import Emonitor
import aiohttp
import voluptuous as vol
from homeassistant import config_entries, core
from homeassistant.components import dhcp
from homeassistant.const import CONF_HOST, CONF_NAME
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.device_registry import format_mac
from . import name_short_mac
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
async def fetch_mac_and_title(hass: core.HomeAssistant, host):
"""Validate the user input allows us to connect."""
session = aiohttp_client.async_get_clientsession(hass)
emonitor = Emonitor(host, session)
status = await emonitor.async_get_status()
mac_address = status.network.mac_address
return {"title": name_short_mac(mac_address[-6:]), "mac_address": mac_address}
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for SiteSage Emonitor."""
VERSION = 1
def __init__(self):
"""Initialize Emonitor ConfigFlow."""
self.discovered_ip = None
self.discovered_info = None
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
errors = {}
if user_input is not None:
try:
info = await fetch_mac_and_title(self.hass, user_input[CONF_HOST])
except aiohttp.ClientError:
errors[CONF_HOST] = "cannot_connect"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
await self.async_set_unique_id(
format_mac(info["mac_address"]), raise_on_progress=False
)
self._abort_if_unique_id_configured()
return self.async_create_entry(title=info["title"], data=user_input)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{vol.Required("host", default=self.discovered_ip): str}
),
errors=errors,
)
async def async_step_dhcp(self, discovery_info: dhcp.DhcpServiceInfo) -> FlowResult:
"""Handle dhcp discovery."""
self.discovered_ip = discovery_info.ip
await self.async_set_unique_id(format_mac(discovery_info.macaddress))
self._abort_if_unique_id_configured(updates={CONF_HOST: self.discovered_ip})
name = name_short_mac(short_mac(discovery_info.macaddress))
self.context["title_placeholders"] = {"name": name}
try:
self.discovered_info = await fetch_mac_and_title(
self.hass, self.discovered_ip
)
except Exception as ex: # pylint: disable=broad-except
_LOGGER.debug(
"Unable to fetch status, falling back to manual entry", exc_info=ex
)
return await self.async_step_user()
return await self.async_step_confirm()
async def async_step_confirm(self, user_input=None):
"""Attempt to confirm."""
if user_input is not None:
return self.async_create_entry(
title=self.discovered_info["title"],
data={CONF_HOST: self.discovered_ip},
)
self._set_confirm_only()
self.context["title_placeholders"] = {"name": self.discovered_info["title"]}
return self.async_show_form(
step_id="confirm",
description_placeholders={
CONF_HOST: self.discovered_ip,
CONF_NAME: self.discovered_info["title"],
},
)
def short_mac(mac):
"""Short version of the mac."""
return "".join(mac.split(":")[3:]).upper()
| 1,711 |
848 |
# -*- coding: utf-8 -*-
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Tests for Cudnn RNN models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import itertools
import os
from absl.testing import parameterized
import numpy as np
from tensorflow.contrib.cudnn_rnn.python.ops import cudnn_rnn_ops
from tensorflow.core.protobuf import saver_pb2
from tensorflow.python.compat import compat
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import random_seed
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gradients_impl
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import rnn
from tensorflow.python.ops import rnn_cell_impl
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import googletest
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.training import saver as saver_lib
CUDNN_RNN_UNIDIRECTION = cudnn_rnn_ops.CUDNN_RNN_UNIDIRECTION
CUDNN_RNN_BIDIRECTION = cudnn_rnn_ops.CUDNN_RNN_BIDIRECTION
CUDNN_LSTM = cudnn_rnn_ops.CUDNN_LSTM
CUDNN_GRU = cudnn_rnn_ops.CUDNN_GRU
CUDNN_RNN_RELU = cudnn_rnn_ops.CUDNN_RNN_RELU
CUDNN_RNN_TANH = cudnn_rnn_ops.CUDNN_RNN_TANH
CUDNN_LSTM_PARAMS_PER_LAYER = cudnn_rnn_ops.CUDNN_LSTM_PARAMS_PER_LAYER
CUDNN_GRU_PARAMS_PER_LAYER = cudnn_rnn_ops.CUDNN_GRU_PARAMS_PER_LAYER
CUDNN_RNN_TANH_PARAMS_PER_LAYER = cudnn_rnn_ops.CUDNN_RNN_TANH_PARAMS_PER_LAYER
CUDNN_RNN_RELU_PARAMS_PER_LAYER = cudnn_rnn_ops.CUDNN_RNN_RELU_PARAMS_PER_LAYER
def RunLSTM(sess,
num_units,
input_size,
batch_size,
time,
num_layers=1,
variable_seq_lengths=False,
time_major=True,
dynamic_shape_input=False,
is_training=True,
dropout=0.,
num_dirs=True,
dtype=dtypes.float32,
num_proj=None):
# TODO(jamesqin): add multi-layer tests.
# TODO(jamesqin): add multi-dir tests
assert num_layers == 1
assert num_dirs == 1
if is_training and not np.isclose(dropout, 0):
raise ValueError("dropout can not be 0. when test training.")
# set graph level random seed and numpy random seed.
random_seed.set_random_seed(0)
np.random.seed(0)
shape = ([time, batch_size, input_size]
if time_major else [batch_size, time, input_size])
inputs_np = np.random.rand(*shape).astype(dtype.as_numpy_dtype)
inputs_static = variable_scope.get_variable(
"inputs", initializer=inputs_np, dtype=dtype)
inputs_dynamic = array_ops.placeholder(
dtype, shape=[None, None, None], name="inputs")
inputs = inputs_dynamic if dynamic_shape_input else inputs_static
unified_num_units = num_proj if num_proj else num_units
unified_num_proj = num_proj if num_proj else None
initial_h_op = variable_scope.get_variable(
"initial_h_op",
initializer=np.random.rand(batch_size, unified_num_units).astype(
dtype.as_numpy_dtype),
dtype=dtype)
initial_c_op = variable_scope.get_variable(
"initial_c_op",
initializer=np.random.rand(batch_size,
num_units).astype(dtype.as_numpy_dtype),
dtype=dtype)
if variable_seq_lengths:
lengths_v = np.random.randint(low=1, high=time + 1, size=batch_size)
lengths_v[0] = time # make sure the max sequence has 'time' elems
lengths = ops.convert_to_tensor(lengths_v.astype(np.int32))
else:
lengths = None
initializer = init_ops.random_uniform_initializer(
-0.01, 0.01, dtype=dtype, seed=19980904)
with variable_scope.variable_scope("test", initializer=initializer):
w = variable_scope.get_variable(
"rnn/lstm_cell/kernel",
shape=[input_size + unified_num_units, num_units * 4],
dtype=dtype)
b = variable_scope.get_variable(
"rnn/lstm_cell/bias", shape=[num_units * 4], dtype=dtype)
if num_proj:
pw = variable_scope.get_variable(
"rnn/lstm_cell/projection/kernel",
shape=[num_units, num_proj],
dtype=dtype)
# canonical lstm. must set forget_bias to 0. to align with cudnn lstm.
cell = rnn_cell_impl.LSTMCell(
num_units, forget_bias=0., reuse=True, num_proj=unified_num_proj)
outputs_op, state_tuple_op = rnn.dynamic_rnn(
cell,
inputs_static,
sequence_length=lengths,
initial_state=rnn_cell_impl.LSTMStateTuple(
h=initial_h_op, c=initial_c_op),
dtype=dtype,
time_major=time_major,
scope=None)
# Convert to cudnn opaque param.
format_converter = cudnn_rnn_ops.CudnnParamsFormatConverterLSTM(
num_layers, num_units, input_size, num_proj=unified_num_proj)
if num_proj:
opaque_params = format_converter.tf_canonical_to_opaque([w, b], [
pw,
])
else:
opaque_params = format_converter.tf_canonical_to_opaque([w, b])
cu_initial_h_op = array_ops.expand_dims(
initial_h_op, axis=(0 if time_major else 1))
cu_initial_c_op = array_ops.expand_dims(
initial_c_op, axis=(0 if time_major else 1))
cu_outputs_op, cu_h_op, cu_c_op = cudnn_rnn_ops._cudnn_rnn(
inputs,
cu_initial_h_op,
cu_initial_c_op,
opaque_params,
sequence_lengths=lengths,
time_major=time_major,
dropout=dropout,
is_training=is_training,
rnn_mode=cudnn_rnn_ops.CUDNN_LSTM,
num_proj=unified_num_proj)
# Remove the trivial 1st dimension.
cu_state_tuple_op = rnn_cell_impl.LSTMStateTuple(
c=array_ops.squeeze(cu_c_op, axis=0 if time_major else 1),
h=array_ops.squeeze(cu_h_op, axis=0 if time_major else 1))
if is_training:
if num_proj:
(inp_grad_op, hgrad_op, cgrad_op,
wgrad_op, bgrad_op, pwgrad_op) = gradients_impl.gradients(
outputs_op, [inputs_static, initial_h_op, initial_c_op, w, b, pw])
else:
(inp_grad_op, hgrad_op,
cgrad_op, wgrad_op, bgrad_op) = gradients_impl.gradients(
outputs_op, [inputs_static, initial_h_op, initial_c_op, w, b])
(cu_inp_grad_op, cu_hgrad_op,
cu_cgrad_op, opaque_grad_op) = gradients_impl.gradients(
cu_outputs_op,
[inputs, cu_initial_h_op, cu_initial_c_op, opaque_params])
# Remove the trivial 1st dimension
cu_hgrad_op = array_ops.squeeze(cu_hgrad_op, axis=0 if time_major else 1)
# Remove the trivial 1st dimension
cu_cgrad_op = array_ops.squeeze(cu_cgrad_op, axis=0 if time_major else 1)
if num_proj:
cu_wgrad_op, cu_bgrad_op, cu_pwgrad_op = \
format_converter.opaque_to_tf_canonical(opaque_grad_op)
else:
cu_wgrad_op, cu_bgrad_op = format_converter.opaque_to_tf_canonical(
opaque_grad_op)
cu_wgrad_op = cu_wgrad_op[0]
cu_bgrad_op = cu_bgrad_op[0]
if num_proj:
cu_pwgrad_op = cu_pwgrad_op[0]
# cudnn lstm has 2 biases each gate. When converting to tf canonical format,
# the two biases are summed into one. Thus here bias gradient should be
# halved when comparing with tf lstm.
cu_bgrad_op *= 0.5
init_op = variables.global_variables_initializer()
sess.run(init_op)
if is_training:
if num_proj:
(outputs, state_tuple, inp_grad, state_grad, wgrad, bgrad,
pwgrad) = sess.run([
outputs_op, state_tuple_op, inp_grad_op, (hgrad_op, cgrad_op),
wgrad_op, bgrad_op, pwgrad_op
])
(cu_outputs, cu_state_tuple, cu_inp_grad, cu_state_grad, cu_wgrad,
cu_bgrad, cu_pwgrad) = sess.run(
[
cu_outputs_op, cu_state_tuple_op, cu_inp_grad_op,
(cu_hgrad_op, cu_cgrad_op), cu_wgrad_op, cu_bgrad_op,
cu_pwgrad_op
],
feed_dict={inputs: inputs_np} if dynamic_shape_input else None)
else:
outputs, state_tuple, inp_grad, state_grad, wgrad, bgrad = sess.run([
outputs_op, state_tuple_op, inp_grad_op, (hgrad_op, cgrad_op),
wgrad_op, bgrad_op
])
(cu_outputs, cu_state_tuple, cu_inp_grad, cu_state_grad, cu_wgrad,
cu_bgrad) = sess.run(
[
cu_outputs_op, cu_state_tuple_op, cu_inp_grad_op,
(cu_hgrad_op, cu_cgrad_op), cu_wgrad_op, cu_bgrad_op
],
feed_dict={inputs: inputs_np} if dynamic_shape_input else None)
logging.vlog(1, "outputs: %s" % outputs)
logging.vlog(1, "cu_outputs: %s" % cu_outputs)
logging.vlog(1, "state_tuple: %s" % str(state_tuple))
logging.vlog(1, "cu_state_tuple: %s" % str(cu_state_tuple))
logging.vlog(1, "inp_grad: %s" % inp_grad)
logging.vlog(1, "cu_inp_grad: %s" % cu_inp_grad)
logging.vlog(1, "state_grad: %s" % str(state_grad))
logging.vlog(1, "cu_state_grad: %s" % str(cu_state_grad))
logging.vlog(1, "wgrad: %s" % str(wgrad))
logging.vlog(1, "bgrad: %s" % str(bgrad))
if num_proj:
logging.vlog(1, "pwgrad: %s" % str(bgrad))
logging.vlog(1, "cu_wgrad: %s" % str(cu_wgrad))
logging.vlog(1, "cu_bgrad: %s" % str(cu_bgrad))
if num_proj:
logging.vlog(1, "cu_pwgrad: %s" % str(cu_bgrad))
if num_proj:
return (outputs, cu_outputs, state_tuple, cu_state_tuple, inp_grad,
cu_inp_grad, state_grad, cu_state_grad, wgrad, bgrad, pwgrad,
cu_wgrad, cu_bgrad, cu_pwgrad)
else:
return (outputs, cu_outputs, state_tuple, cu_state_tuple, inp_grad,
cu_inp_grad, state_grad, cu_state_grad, wgrad, bgrad, cu_wgrad,
cu_bgrad)
else:
outputs, state_tuple = sess.run([outputs_op, state_tuple_op])
cu_outputs, cu_state_tuple = sess.run([cu_outputs_op, cu_state_tuple_op],
feed_dict=({
inputs: inputs_np
} if dynamic_shape_input else None))
logging.vlog(1, "outputs: %s" % outputs)
logging.vlog(1, "cu_outputs: %s" % cu_outputs)
logging.vlog(1, "state_tuple: %s" % str(state_tuple))
logging.vlog(1, "cu_state_tuple: %s" % str(cu_state_tuple))
return outputs, cu_outputs, state_tuple, cu_state_tuple
# Basic set of RNN configs to test. They can be further extended in relevant
# test (e.g. adding num_dirs).
NAMED_RNN_TESTCASES = ({
"testcase_name": "xsmall",
"num_units": 1,
"input_size": 1,
"batch_size": 1,
"time": 1,
"num_layers": 1,
}, {
"testcase_name": "small",
"num_units": 4,
"input_size": 4,
"batch_size": 4,
"time": 4,
"num_layers": 1,
}, {
"testcase_name": "medium",
"num_units": 128,
"input_size": 64,
"batch_size": 8,
"time": 16,
"num_layers": 1,
}, {
"testcase_name": "large",
"num_units": 128,
"input_size": 128,
"batch_size": 16,
"time": 32,
"num_layers": 1,
})
def ExpandNamedTestCases(inputs, *remove_keys, **extra_configs):
"""Expands testcase with new config dimensions.
Example:
inputs = (
{'testcase_name': 'test1', 'gender': 'male'}
{'testcase_name': 'test2', 'gender': 'female'}
)
remove_keys: empty
extra_configs = {
'age': [40, 80]
'height': [5, 6]
}
Returns:
(
{'testcase_name': 'test1_age_40_height_5','gender': 'male', 'age':
40,'height': 5}
{'testcase_name': 'test1_age_40_height_6', 'gender': 'male', 'age': 40,
'height': 6}
{'testcase_name': 'test1_age_80_height_5', 'gender': 'male', 'age': 80,
'height': 5}
{'testcase_name': 'test1_age_80_height_6', 'gender': 'male', 'age': 80,
'height': 6}
{'testcase_name': 'test2_age_40_height_5', 'gender': 'female', 'age':
40,
'height': 5}
{'testcase_name': 'test2_age_40_height_6', 'gender': 'female', 'age':
40,
'height': 6}
{'testcase_name': 'test2_age_80_height_5', 'gender': 'female', 'age':
80,
'height': 5}
{'testcase_name': 'test2_age_80_height_6', 'gender': 'female', 'age':
80,
'height': 6}
)
Args:
inputs: A list of dictionary, each being a testcase.
*remove_keys: A list of keys into testcase which are not needed in new
testcases.
**extra_configs: A dict of new test dimension and applicable values in that
dimension.
Returns:
A list of dictionary with expanded test cases.
"""
res = []
ordered_extra_configs = collections.OrderedDict(extra_configs)
keys = ordered_extra_configs.keys()
# A list of list of configs.
# The outer loop is iterating keys, the innner is values of one key.
combined_kv = [[(k, v) for v in ordered_extra_configs[k]] for k in keys]
logging.info("combined_kv: %s", combined_kv)
for inp in inputs:
# Each inp is a dict
for config in itertools.product(*combined_kv):
new_inp = dict(inp)
# config is a list in the form of [(k_i, v_j), (k_p, v_q), ...]
suffix = ["%s_%s" % (p[0], str(p[1])) for p in config]
suffix = "_".join(suffix)
new_inp["testcase_name"] += "_" + suffix
for k, v in config:
new_inp[k] = v
# Remove not used keys from the new test case.
if remove_keys:
if not isinstance(remove_keys, (list, tuple)):
remove_keys = [remove_keys]
for k in remove_keys:
new_inp.pop(k, None)
logging.info("new_inp: %s", new_inp)
res.append(new_inp)
# Dedup, necessary if `remove_keys` is set.
return [dict(t) for t in {tuple(d.items()) for d in res}]
class CudnnLSTMTest(test_util.TensorFlowTestCase, parameterized.TestCase):
def _test_training_helper(self,
num_units,
input_size,
batch_size,
time,
num_layers,
dtype,
variable_seq_lengths,
time_major,
dynamic_shape_input=False,
rtol=3e-6,
atol=3e-6,
num_proj=None):
with self.session(use_gpu=True) as sess:
if num_proj is not None and num_proj != 0:
(outputs, cu_outputs, state_tuple, cu_state_tuple, inp_grad,
cu_inp_grad, state_grad, cu_state_grad, wgrad, bgrad, pwgrad, cu_wgrad,
cu_bgrad, cu_pwgrad) = RunLSTM(
sess,
num_units,
input_size,
batch_size,
time,
num_layers,
variable_seq_lengths=variable_seq_lengths,
dynamic_shape_input=dynamic_shape_input,
num_proj=num_proj)
else:
(outputs, cu_outputs, state_tuple, cu_state_tuple, inp_grad,
cu_inp_grad, state_grad, cu_state_grad, wgrad, bgrad, cu_wgrad,
cu_bgrad) = RunLSTM(
sess,
num_units,
input_size,
batch_size,
time,
num_layers,
variable_seq_lengths=variable_seq_lengths,
dynamic_shape_input=dynamic_shape_input,
num_proj=num_proj)
self.assertAllClose(outputs, cu_outputs, rtol=rtol, atol=atol)
for s, cu_s in zip(state_tuple, cu_state_tuple):
self.assertAllClose(s, cu_s, rtol=rtol, atol=atol)
for sg, cu_sg in zip(state_grad, cu_state_grad):
self.assertAllClose(sg, cu_sg, rtol=rtol, atol=atol)
self.assertAllClose(inp_grad, cu_inp_grad, rtol=rtol, atol=atol)
self.assertAllClose(bgrad, cu_bgrad, rtol=rtol, atol=atol)
self.assertAllClose(wgrad, cu_wgrad, rtol=rtol, atol=atol)
if num_proj is not None and num_proj != 0:
self.assertAllClose(pwgrad, cu_pwgrad, rtol=rtol, atol=atol)
@parameterized.named_parameters(
ExpandNamedTestCases(
NAMED_RNN_TESTCASES, **{
"variable_seq_lengths": [True, False],
"time_major": [True, False],
"dynamic_shape_input": [True, False],
"use_proj": [True, False],
}))
@test_util.run_gpu_only
def test_training(self, num_units, input_size, batch_size, time, num_layers,
variable_seq_lengths, time_major, dynamic_shape_input,
use_proj):
with compat.forward_compatibility_horizon(2019, 6, 27):
num_proj = num_units // 2
if use_proj and num_proj == 0:
self.skipTest("num_proj cannot be 0")
self._test_training_helper(
num_units,
input_size,
batch_size,
time,
num_layers,
dtypes.float32,
variable_seq_lengths=variable_seq_lengths,
time_major=time_major,
dynamic_shape_input=dynamic_shape_input,
num_proj=num_proj if use_proj else None)
@parameterized.named_parameters(
ExpandNamedTestCases(
NAMED_RNN_TESTCASES, **{
"variable_seq_lengths": [True, False],
"time_major": [True, False],
"dynamic_shape_input": [True, False],
"use_proj": [True, False],
}))
@test_util.run_gpu_only
def test_training_fp16(self, num_units, input_size, batch_size, time,
num_layers, variable_seq_lengths, time_major,
dynamic_shape_input, use_proj):
with compat.forward_compatibility_horizon(2019, 6, 27):
num_proj = num_units // 2
if use_proj and num_proj == 0:
self.skipTest("num_proj cannot be 0")
self._test_training_helper(
num_units,
input_size,
batch_size,
time,
num_layers,
dtypes.float16,
rtol=5e-3,
atol=5e-4,
variable_seq_lengths=variable_seq_lengths,
time_major=time_major,
dynamic_shape_input=dynamic_shape_input,
num_proj=num_proj if use_proj else None)
@parameterized.named_parameters(
ExpandNamedTestCases(
NAMED_RNN_TESTCASES, **{
"variable_seq_lengths": [True, False],
"time_major": [True, False],
"dynamic_shape_input": [True, False],
"use_proj": [True, False],
}))
@test_util.run_gpu_only
def test_inference(self, num_units, input_size, batch_size, time, num_layers,
variable_seq_lengths, time_major, dynamic_shape_input,
use_proj):
with compat.forward_compatibility_horizon(2019, 6, 27):
num_proj = num_units // 2
if use_proj and num_proj == 0:
self.skipTest("num_proj cannot be 0")
with self.session(use_gpu=True) as sess:
(outputs, cu_outputs, state_tuple, cu_state_tuple) = RunLSTM(
sess,
num_units,
input_size,
batch_size,
time,
num_layers,
is_training=False,
variable_seq_lengths=variable_seq_lengths,
time_major=time_major,
dynamic_shape_input=dynamic_shape_input,
num_proj=num_proj if use_proj else None)
self.assertAllClose(outputs, cu_outputs)
# h
self.assertAllClose(state_tuple.h, cu_state_tuple.h)
# c
self.assertAllClose(state_tuple.c, cu_state_tuple.c)
@parameterized.named_parameters(
ExpandNamedTestCases(
NAMED_RNN_TESTCASES, **{
"variable_seq_lengths": [True, False],
"time_major": [True, False],
"dynamic_shape_input": [True, False],
"use_proj": [True, False],
}))
@test_util.run_gpu_only
def test_inference_fp16(self, num_units, input_size, batch_size, time,
num_layers, variable_seq_lengths, time_major,
dynamic_shape_input, use_proj):
with compat.forward_compatibility_horizon(2019, 6, 27):
num_proj = num_units // 2
if use_proj and num_proj == 0:
self.skipTest("num_proj cannot be 0")
with self.session(use_gpu=True) as sess:
(outputs, cu_outputs, state_tuple, cu_state_tuple) = RunLSTM(
sess,
num_units,
input_size,
batch_size,
time,
num_layers,
is_training=False,
dtype=dtypes.float16,
variable_seq_lengths=variable_seq_lengths,
time_major=time_major,
dynamic_shape_input=dynamic_shape_input,
num_proj=num_proj if use_proj else None)
rtol, atol = 5e-3, 5e-4
self.assertAllClose(outputs, cu_outputs, rtol=rtol, atol=atol)
# h
self.assertAllClose(
state_tuple.h, cu_state_tuple.h, rtol=rtol, atol=atol)
# c
self.assertAllClose(
state_tuple.c, cu_state_tuple.c, rtol=rtol, atol=atol)
@parameterized.named_parameters(
ExpandNamedTestCases(
NAMED_RNN_TESTCASES, **{
"variable_seq_lengths": [True, False],
"time_major": [True, False],
"dynamic_shape_input": [True, False],
"use_proj": [True, False],
}))
@test_util.run_gpu_only
def test_inference_with_dropout(self, num_units, input_size, batch_size, time,
num_layers, variable_seq_lengths, time_major,
dynamic_shape_input, use_proj):
"""Validates that dropout does not affect Cudnn Rnn inference."""
with compat.forward_compatibility_horizon(2019, 6, 27):
num_proj = num_units // 2
if use_proj and num_proj == 0:
self.skipTest("num_proj cannot be 0")
# Hand-picked dropouts are used below (0. and 1.)
with ops.Graph().as_default() as g:
with self.session(use_gpu=True, graph=g) as sess:
# 1st time w/o dropout.
(_, cu_outputs, _, cu_state_tuple) = RunLSTM(
sess,
num_units,
input_size,
batch_size,
time,
num_layers,
is_training=False,
dropout=0.,
variable_seq_lengths=variable_seq_lengths,
time_major=time_major,
dynamic_shape_input=dynamic_shape_input,
num_proj=num_proj if use_proj else None)
with ops.Graph().as_default() as g:
with self.session(use_gpu=True, graph=g) as sess:
(_, cu_outputs2, _, cu_state_tuple2) = RunLSTM(
sess,
num_units,
input_size,
batch_size,
time,
num_layers,
is_training=False,
dropout=1.,
variable_seq_lengths=variable_seq_lengths,
time_major=time_major,
dynamic_shape_input=dynamic_shape_input,
num_proj=num_proj if use_proj else None)
self.assertAllClose(cu_outputs, cu_outputs2)
# h
self.assertAllClose(cu_state_tuple.h, cu_state_tuple2.h)
# c
self.assertAllClose(cu_state_tuple.c, cu_state_tuple2.c)
def RunGRU(sess,
num_units,
input_size,
batch_size,
time,
num_layers=1,
is_training=True,
variable_seq_lengths=False,
time_major=True,
dynamic_shape_input=False,
dropout=0.,
num_dirs=True,
dtype=dtypes.float32):
# TODO(jamesqin): add multi-layer tests.
# TODO(jamesqin): add multi-dir tests
assert num_layers == 1
assert num_dirs == 1
if is_training and not np.isclose(dropout, 0):
raise ValueError("dropout can not be 0. when test training.")
# set graph level random seed and numpy random seed.
random_seed.set_random_seed(0)
np.random.seed(0)
shape = ([time, batch_size, input_size]
if time_major else [batch_size, time, input_size])
inputs_np = np.random.rand(*shape).astype(dtype.as_numpy_dtype)
inputs_static = variable_scope.get_variable(
"inputs", initializer=inputs_np, dtype=dtype)
inputs_dynamic = array_ops.placeholder(
dtype, shape=[None, None, None], name="inputs")
inputs = inputs_dynamic if dynamic_shape_input else inputs_static
initial_h_op = variable_scope.get_variable(
"initial_h_op",
initializer=np.random.rand(batch_size,
num_units).astype(dtype.as_numpy_dtype),
dtype=dtype)
if variable_seq_lengths:
lengths_v = np.random.randint(low=1, high=time + 1, size=batch_size)
lengths_v[0] = time # make sure the max sequence has 'time' elems
lengths = ops.convert_to_tensor(lengths_v.astype(np.int32))
else:
lengths = None
initializer = init_ops.random_uniform_initializer(
-0.01, 0.01, dtype=dtype, seed=19980904)
with variable_scope.variable_scope("test", initializer=initializer):
gate_kernel = variable_scope.get_variable(
"rnn/cudnn_compatible_gru_cell/gates/kernel",
shape=[input_size + num_units, num_units * 2],
dtype=dtype)
gate_bias = variable_scope.get_variable(
"rnn/cudnn_compatible_gru_cell/gates/bias",
shape=[num_units * 2],
dtype=dtype)
candidate_inp_kernel = variable_scope.get_variable(
"rnn/cudnn_compatible_gru_cell/candidate/input_projection/kernel",
shape=[input_size, num_units],
dtype=dtype)
candidate_inp_bias = variable_scope.get_variable(
"rnn/cudnn_compatible_gru_cell/candidate/input_projection/bias",
shape=[num_units],
dtype=dtype)
candidate_hid_kernel = variable_scope.get_variable(
"rnn/cudnn_compatible_gru_cell/candidate/hidden_projection/kernel",
shape=[num_units, num_units],
dtype=dtype)
candidate_hid_bias = variable_scope.get_variable(
"rnn/cudnn_compatible_gru_cell/candidate/hidden_projection/bias",
shape=[num_units],
dtype=dtype)
cell = cudnn_rnn_ops.CudnnCompatibleGRUCell(num_units, reuse=True)
outputs_op, h_op = rnn.dynamic_rnn(
cell,
inputs_static,
sequence_length=lengths,
initial_state=initial_h_op,
dtype=dtype,
time_major=time_major,
scope=None)
ws = [gate_kernel, candidate_inp_kernel, candidate_hid_kernel]
bs = [gate_bias, candidate_inp_bias, candidate_hid_bias]
# Convert to cudnn opaque param.
format_converter = cudnn_rnn_ops.CudnnParamsFormatConverterGRU(
num_layers, num_units, input_size)
opaque_params = format_converter.tf_canonical_to_opaque(ws + bs)
cu_initial_h_op = array_ops.expand_dims(
initial_h_op, axis=(0 if time_major else 1))
cu_outputs_op, cu_h_op, _ = cudnn_rnn_ops._cudnn_rnn(
inputs,
cu_initial_h_op,
array_ops.zeros_like(cu_initial_h_op), # not used
opaque_params,
sequence_lengths=lengths,
time_major=time_major,
dropout=dropout,
is_training=is_training,
rnn_mode=cudnn_rnn_ops.CUDNN_GRU)
if is_training:
(inp_grad_op, hgrad_op, gk_grad_op, cik_grad_op, chk_grad_op, gb_grad_op,
cib_grad_op, chb_grad_op) = gradients_impl.gradients(
outputs_op, [inputs_static, initial_h_op] + ws + bs)
(cu_inp_grad_op, cu_hgrad_op, opaque_grad_op) = gradients_impl.gradients(
cu_outputs_op, [inputs, cu_initial_h_op, opaque_params])
# Remove the trivial 1st dimension
cu_hgrad_op = array_ops.squeeze(cu_hgrad_op, axis=0 if time_major else 1)
cu_wgrad_op, cu_bgrad_op = format_converter.opaque_to_tf_canonical(
opaque_grad_op)
(cu_gk_grad_op, cu_cik_grad_op, cu_chk_grad_op) = cu_wgrad_op
(cu_gb_grad_op, cu_cib_grad_op, cu_chb_grad_op) = cu_bgrad_op
# cudnn gru has 2 biases for reset and update gates. When converting to tf
# canonical format, the two biases are summed into one. Thus here relevant
# bias gradient should be halved before comparing with tf gru.
cu_gb_grad_op *= 0.5
init_op = variables.global_variables_initializer()
sess.run(init_op)
if is_training:
outputs, h, inp_grad, hgrad, wgrad, bgrad = sess.run([
outputs_op, h_op, inp_grad_op, hgrad_op,
(gk_grad_op, cik_grad_op, chk_grad_op),
(gb_grad_op, cib_grad_op, chb_grad_op)
])
(cu_outputs, cu_h, cu_inp_grad, cu_hgrad, cu_wgrad, cu_bgrad) = sess.run(
[
cu_outputs_op, cu_h_op, cu_inp_grad_op, cu_hgrad_op,
(cu_gk_grad_op, cu_cik_grad_op, cu_chk_grad_op),
(cu_gb_grad_op, cu_cib_grad_op, cu_chb_grad_op)
],
feed_dict={inputs: inputs_np} if dynamic_shape_input else None)
# Remove the trivial 1st dimension
cu_h = np.squeeze(cu_h, axis=0 if time_major else 1)
logging.vlog(1, "outputs: %s" % outputs)
logging.vlog(1, "cu_outputs: %s" % cu_outputs)
logging.vlog(1, "h: %s" % h)
logging.vlog(1, "cu_h: %s" % h)
logging.vlog(1, "inp_grad: %s" % inp_grad)
logging.vlog(1, "cu_inp_grad: %s" % cu_inp_grad)
logging.vlog(1, "hgrad: %s" % hgrad)
logging.vlog(1, "cu_hgrad: %s" % cu_hgrad)
logging.vlog(1, "wgrad: %s" % str(wgrad))
logging.vlog(1, "bgrad: %s" % str(bgrad))
logging.vlog(1, "cu_wgrad: %s" % str(cu_wgrad))
logging.vlog(1, "cu_bgrad: %s" % str(cu_bgrad))
return (outputs, cu_outputs, h, cu_h, inp_grad, cu_inp_grad, hgrad,
cu_hgrad, wgrad, bgrad, cu_wgrad, cu_bgrad)
else:
outputs, h = sess.run([outputs_op, h_op])
cu_outputs, cu_h = sess.run([cu_outputs_op, cu_h_op],
feed_dict=({
inputs: inputs_np
} if dynamic_shape_input else None))
# Remove the trivial 1st dimension.
cu_h = np.squeeze(cu_h, axis=0 if time_major else 1)
logging.vlog(1, "outputs: %s" % outputs)
logging.vlog(1, "cu_outputs: %s" % cu_outputs)
logging.vlog(1, "h: %s" % h)
logging.vlog(1, "cu_h: %s" % h)
return outputs, cu_outputs, h, cu_h
class CudnnGRUTest(test_util.TensorFlowTestCase, parameterized.TestCase):
def _test_training_helper(self,
num_units,
input_size,
batch_size,
time,
num_layers,
dtype,
variable_seq_lengths,
time_major,
dynamic_shape_input=False,
rtol=3e-6,
atol=3e-6):
with self.session(use_gpu=True) as sess:
(outputs, cu_outputs, h, cu_h, inp_grad, cu_inp_grad, hgrad, cu_hgrad,
wgrad, bgrad, cu_wgrad, cu_bgrad) = RunGRU(
sess,
num_units,
input_size,
batch_size,
time,
num_layers,
variable_seq_lengths=variable_seq_lengths,
time_major=time_major,
dynamic_shape_input=dynamic_shape_input)
self.assertAllClose(outputs, cu_outputs, rtol=rtol, atol=atol)
self.assertAllClose(h, cu_h, rtol=rtol, atol=atol)
self.assertAllClose(hgrad, cu_hgrad, rtol=rtol, atol=atol)
self.assertAllClose(inp_grad, cu_inp_grad, rtol=rtol, atol=atol)
for bg, cu_bg in zip(bgrad, cu_bgrad):
self.assertAllClose(bg, cu_bg, rtol=rtol, atol=atol)
for wg, cu_wg in zip(wgrad, cu_wgrad):
self.assertAllClose(wg, cu_wg, rtol=rtol, atol=atol)
@parameterized.named_parameters(
ExpandNamedTestCases(
NAMED_RNN_TESTCASES, **{
"variable_seq_lengths": [True, False],
"time_major": [True, False],
"dynamic_shape_input": [True, False],
}))
@test_util.run_gpu_only
def test_training(self, num_units, input_size, batch_size, time, num_layers,
variable_seq_lengths, time_major, dynamic_shape_input):
self._test_training_helper(
num_units,
input_size,
batch_size,
time,
num_layers,
dtypes.float32,
variable_seq_lengths=variable_seq_lengths,
time_major=time_major,
dynamic_shape_input=dynamic_shape_input)
@parameterized.named_parameters(
ExpandNamedTestCases(
NAMED_RNN_TESTCASES, **{
"variable_seq_lengths": [True, False],
"time_major": [True, False],
"dynamic_shape_input": [True, False],
}))
@test_util.run_gpu_only
def test_training_fp16(self, num_units, input_size, batch_size, time,
num_layers, variable_seq_lengths, time_major,
dynamic_shape_input):
self._test_training_helper(
num_units,
input_size,
batch_size,
time,
num_layers,
dtypes.float16,
rtol=5e-3,
atol=5e-4,
variable_seq_lengths=variable_seq_lengths,
time_major=time_major,
dynamic_shape_input=dynamic_shape_input)
@parameterized.named_parameters(
ExpandNamedTestCases(
NAMED_RNN_TESTCASES, **{
"variable_seq_lengths": [True, False],
"time_major": [True, False],
"dynamic_shape_input": [True, False],
}))
@test_util.run_gpu_only
def test_inference(self, num_units, input_size, batch_size, time, num_layers,
variable_seq_lengths, time_major, dynamic_shape_input):
with self.session(use_gpu=True) as sess:
(outputs, cu_outputs, h, cu_h) = RunGRU(
sess,
num_units,
input_size,
batch_size,
time,
num_layers,
is_training=False,
variable_seq_lengths=variable_seq_lengths,
time_major=time_major,
dynamic_shape_input=dynamic_shape_input)
self.assertAllClose(outputs, cu_outputs)
self.assertAllClose(h, cu_h)
@parameterized.named_parameters(
ExpandNamedTestCases(
NAMED_RNN_TESTCASES, **{
"variable_seq_lengths": [True, False],
"time_major": [True, False],
"dynamic_shape_input": [True, False],
}))
@test_util.run_gpu_only
def test_inference_fp16(self, num_units, input_size, batch_size, time,
num_layers, variable_seq_lengths, time_major,
dynamic_shape_input):
with self.session(use_gpu=True) as sess:
(outputs, cu_outputs, h, cu_h) = RunGRU(
sess,
num_units,
input_size,
batch_size,
time,
num_layers,
is_training=False,
dtype=dtypes.float16,
variable_seq_lengths=variable_seq_lengths,
time_major=time_major,
dynamic_shape_input=dynamic_shape_input)
rtol, atol = 5e-3, 5e-4
self.assertAllClose(outputs, cu_outputs, rtol=rtol, atol=atol)
self.assertAllClose(h, cu_h, rtol=rtol, atol=atol)
@parameterized.named_parameters(
ExpandNamedTestCases(
NAMED_RNN_TESTCASES, **{
"variable_seq_lengths": [True, False],
"time_major": [True, False],
"dynamic_shape_input": [True, False],
}))
@test_util.run_gpu_only
def test_inference_with_dropout(self, num_units, input_size, batch_size, time,
num_layers, variable_seq_lengths, time_major,
dynamic_shape_input):
"""Validates that dropout does not affect Cudnn Rnn inference."""
# Hand-picked dropouts are used below (0. and 1.)
with ops.Graph().as_default() as g:
with self.session(use_gpu=True, graph=g) as sess:
# 1st time w/o dropout.
(_, cu_outputs, _, cu_h) = RunGRU(
sess,
num_units,
input_size,
batch_size,
time,
num_layers,
is_training=False,
dropout=0.,
variable_seq_lengths=variable_seq_lengths,
time_major=time_major,
dynamic_shape_input=dynamic_shape_input)
with ops.Graph().as_default() as g:
with self.session(use_gpu=True, graph=g) as sess:
(_, cu_outputs2, _, cu_h2) = RunGRU(
sess,
num_units,
input_size,
batch_size,
time,
num_layers,
is_training=False,
dropout=1.,
variable_seq_lengths=variable_seq_lengths,
time_major=time_major,
dynamic_shape_input=dynamic_shape_input)
self.assertAllClose(cu_outputs, cu_outputs2)
self.assertAllClose(cu_h[0], cu_h2[0])
class CudnnParamsFormatConverterTest(test_util.TensorFlowTestCase,
parameterized.TestCase):
"""Class for testing various format converters."""
def _test_lstm_helper(self,
num_units,
input_size,
num_layers,
direction,
num_proj=None):
with self.session(use_gpu=True) as sess:
random_seed.set_random_seed(0)
np.random.seed(0)
num_dirs = 1 if direction == cudnn_rnn_ops.CUDNN_RNN_UNIDIRECTION else 2
format_converter = cudnn_rnn_ops.CudnnParamsFormatConverterLSTM(
num_layers,
num_units,
input_size,
direction=direction,
num_proj=num_proj if num_proj else None)
ws, bs, pws = [], [], []
for _ in range(num_layers * num_dirs):
w = constant_op.constant(
np.random.rand(input_size + (num_proj if num_proj else num_units),
4 * num_units),
dtype=dtypes.float32)
b = constant_op.constant(
np.random.rand(4 * num_units), dtype=dtypes.float32)
ws.append(w)
bs.append(b)
if num_proj:
pw = constant_op.constant(
np.random.rand(num_units, num_proj), dtype=dtypes.float32)
pws.append(pw)
if num_proj:
opaque_params = format_converter.tf_canonical_to_opaque(ws + bs, pws)
else:
opaque_params = format_converter.tf_canonical_to_opaque(ws + bs)
opaque_params_size = cudnn_rnn_ops.cudnn_rnn_opaque_params_size(
cudnn_rnn_ops.CUDNN_LSTM,
num_layers,
num_units,
input_size,
direction=direction,
num_proj=num_proj if num_proj else None)
if num_proj:
ws_r, bs_r, pws_r = format_converter.opaque_to_tf_canonical(
opaque_params)
ws, ws_r, pws, bs, bs_r, pws_r = sess.run(
[ws, ws_r, pws, bs, bs_r, pws_r])
else:
ws_r, bs_r = format_converter.opaque_to_tf_canonical(opaque_params)
ws, ws_r, bs, bs_r = sess.run([ws, ws_r, bs, bs_r])
# Test tf_canonical_to_opaque() followed by opaque_to_tf_canonical()
# returns the original input.
for w, w_r in zip(ws, ws_r):
self.assertAllClose(w, w_r)
if num_proj:
for pw, pw_r in zip(pws, pws_r):
self.assertAllClose(pw, pw_r)
for b, b_r in zip(bs, bs_r):
self.assertAllClose(b, b_r)
# Test opaque_params size lower bound
opaque_params_size_v = sess.run(opaque_params_size)
min_params_size = sum(x.size for x in ws) + np.sum(x.size for x in bs)
logging.info("min_parm_size: %d vs actual_opaque_param_size: %d",
min_params_size, opaque_params_size_v)
self.assertLessEqual(min_params_size, opaque_params_size_v)
@parameterized.named_parameters((c["testcase_name"], c["num_units"],
c["input_size"], c["num_layers"])
for c in NAMED_RNN_TESTCASES)
@test_util.run_gpu_only
def test_lstm(self, num_units, input_size, num_layers):
self._test_lstm_helper(num_units, input_size, num_layers,
cudnn_rnn_ops.CUDNN_RNN_UNIDIRECTION)
@parameterized.named_parameters(
(c["testcase_name"], c["num_units"], c["input_size"], c["num_layers"])
for c in NAMED_RNN_TESTCASES)
@test_util.run_gpu_only
def test_lstmp(self, num_units, input_size, num_layers):
with compat.forward_compatibility_horizon(2019, 6, 27):
num_proj = num_units // 2
if num_proj == 0:
self.skipTest("num_proj cannot be 0")
self._test_lstm_helper(
num_units,
input_size,
num_layers,
cudnn_rnn_ops.CUDNN_RNN_UNIDIRECTION,
num_proj=num_proj)
@parameterized.named_parameters((c["testcase_name"], c["num_units"],
c["input_size"], c["num_layers"])
for c in NAMED_RNN_TESTCASES)
@test_util.run_gpu_only
def test_lstm_bidi(self, num_units, input_size, num_layers):
self._test_lstm_helper(num_units, input_size, num_layers,
cudnn_rnn_ops.CUDNN_RNN_BIDIRECTION)
@parameterized.named_parameters(
(c["testcase_name"], c["num_units"], c["input_size"], c["num_layers"])
for c in NAMED_RNN_TESTCASES)
@test_util.run_gpu_only
def test_lstmp_bidi(self, num_units, input_size, num_layers):
with compat.forward_compatibility_horizon(2019, 6, 27):
num_proj = num_units // 2
if num_proj == 0:
self.skipTest("num_proj cannot be 0")
self._test_lstm_helper(
num_units,
input_size,
num_layers,
cudnn_rnn_ops.CUDNN_RNN_BIDIRECTION,
num_proj=num_proj)
def _test_gru_helper(self, num_units, input_size, num_layers, direction):
with self.session(use_gpu=True) as sess:
random_seed.set_random_seed(0)
np.random.seed(0)
num_dirs = 1 if direction == cudnn_rnn_ops.CUDNN_RNN_UNIDIRECTION else 2
format_converter = cudnn_rnn_ops.CudnnParamsFormatConverterGRU(
num_layers, num_units, input_size, direction=direction)
ws, bs = [], []
for _ in range(num_layers * num_dirs):
gate_kernel = constant_op.constant(
np.random.rand(input_size + num_units, num_units * 2),
dtype=dtypes.float32)
gate_bias = constant_op.constant(
np.random.rand(num_units * 2), dtype=dtypes.float32)
candidate_inp_kernel = constant_op.constant(
np.random.rand(input_size, num_units), dtype=dtypes.float32)
candidate_inp_bias = constant_op.constant(
np.random.rand(num_units), dtype=dtypes.float32)
candidate_hid_kernel = constant_op.constant(
np.random.rand(num_units, num_units), dtype=dtypes.float32)
candidate_hid_bias = constant_op.constant(
np.random.rand(num_units), dtype=dtypes.float32)
ws.extend([gate_kernel, candidate_inp_kernel, candidate_hid_kernel])
bs.extend([gate_bias, candidate_inp_bias, candidate_hid_bias])
opaque_params = format_converter.tf_canonical_to_opaque(ws + bs)
opaque_params_size = cudnn_rnn_ops.cudnn_rnn_opaque_params_size(
cudnn_rnn_ops.CUDNN_GRU,
num_layers,
num_units,
input_size,
direction=direction)
ws_r, bs_r = format_converter.opaque_to_tf_canonical(opaque_params)
# Test tf_canonical_to_opaque() followed by opaque_to_tf_canonical()
# returns the original input.
ws, ws_r, bs, bs_r = sess.run([ws, ws_r, bs, bs_r])
for w, w_r in zip(ws, ws_r):
self.assertAllClose(w, w_r)
for b, b_r in zip(bs, bs_r):
self.assertAllClose(b, b_r)
# Test opaque_params size lower bound
opaque_params_size_v = sess.run(opaque_params_size)
min_params_size = sum(x.size for x in ws) + sum(x.size for x in bs)
logging.info("min_parm_size: %d vs actual_opaque_param_size: %d",
min_params_size, opaque_params_size_v)
self.assertLessEqual(min_params_size, opaque_params_size_v)
@parameterized.named_parameters((c["testcase_name"], c["num_units"],
c["input_size"], c["num_layers"])
for c in NAMED_RNN_TESTCASES)
@test_util.run_gpu_only
def test_gru(self, num_units, input_size, num_layers):
self._test_gru_helper(num_units, input_size, num_layers,
cudnn_rnn_ops.CUDNN_RNN_UNIDIRECTION)
@parameterized.named_parameters((c["testcase_name"], c["num_units"],
c["input_size"], c["num_layers"])
for c in NAMED_RNN_TESTCASES)
@test_util.run_gpu_only
def test_gru_bidi(self, num_units, input_size, num_layers):
self._test_gru_helper(num_units, input_size, num_layers,
cudnn_rnn_ops.CUDNN_RNN_BIDIRECTION)
class CudnnRnnSaveRestoreTest(test_util.TensorFlowTestCase,
parameterized.TestCase):
"""Class for testing various Cudnn Rnn SaveableObjects."""
def _create_opaque_param(self,
rnn_mode,
num_units,
input_size,
num_layers,
direction,
name=None):
param_size_t = cudnn_rnn_ops.cudnn_rnn_opaque_params_size(
rnn_mode, num_layers, num_units, input_size, direction=direction)
init_val = random_ops.random_uniform([param_size_t])
return variable_scope.get_variable(
name or "opaque_param", initializer=init_val, validate_shape=False)
def _create_saveable(self, opaque_param, rnn_mode, num_units, input_size,
num_layers, direction):
if rnn_mode == CUDNN_LSTM:
fn = cudnn_rnn_ops.CudnnLSTMSaveable
elif rnn_mode == CUDNN_GRU:
fn = cudnn_rnn_ops.CudnnGRUSaveable
elif rnn_mode == CUDNN_RNN_TANH:
fn = cudnn_rnn_ops.CudnnRNNTanhSaveable
elif rnn_mode == CUDNN_RNN_RELU:
fn = cudnn_rnn_ops.CudnnRNNReluSaveable
saveable = fn(
opaque_param, num_layers, num_units, input_size, direction=direction)
return saveable
def _compare_weights(self, lhs, rhs):
self.assertLen(rhs, len(lhs))
for lw, rw in zip(lhs, rhs):
self.assertAllEqual(lw, rw)
def _compare_biases(self, lhs, rhs):
self.assertLen(rhs, len(lhs))
for lf, rt in zip(lhs, rhs):
self.assertAllEqual(lf, rt)
@parameterized.named_parameters(
ExpandNamedTestCases(
NAMED_RNN_TESTCASES, "time", "batch_size", **{
"rnn_mode": [
CUDNN_LSTM, CUDNN_GRU, CUDNN_RNN_RELU, CUDNN_RNN_TANH
],
"direction": [CUDNN_RNN_UNIDIRECTION, CUDNN_RNN_BIDIRECTION]
}))
@test_util.run_gpu_only
def test_save_restore_variable(self, rnn_mode, num_units, input_size,
num_layers, direction):
# Verify the restored opaque param, once converted to tf_canonical format,
# is the same as the tf canonicals of the pre-restored param.
with self.session(use_gpu=True) as sess:
opaque_param = self._create_opaque_param(rnn_mode, num_units, input_size,
num_layers, direction)
saveable = self._create_saveable(opaque_param, rnn_mode, num_units,
input_size, num_layers, direction)
ops.add_to_collection(ops.GraphKeys.SAVEABLE_OBJECTS, saveable)
weights_op, biases_op = saveable.format_converter.opaque_to_tf_canonical(
saveable._variables)
save_path = os.path.join(self.get_temp_dir(), "save_restore_var_test")
saver = saver_lib.Saver(write_version=saver_pb2.SaverDef.V2)
init_op = variables.global_variables_initializer()
reset_op = state_ops.assign(opaque_param,
array_ops.zeros_like(opaque_param))
sess.run(init_op)
self.assertEqual(save_path, saver.save(sess, save_path))
# Get the tf canonical vals before reset-restore
weights, biases = sess.run([weights_op, biases_op])
# Reset the opaque param value
sess.run(reset_op)
# Assert reset happened.
weights_z, biases_z = sess.run([weights_op, biases_op])
for w in weights_z:
self.assertAllClose(w, np.zeros_like(w))
for b in biases_z:
self.assertAllClose(b, np.zeros_like(b))
# Restore opaque param value from checkpoint.
saver.restore(sess, save_path)
weights_r, biases_r = sess.run([weights_op, biases_op])
self._compare_weights(weights, weights_r)
self._compare_biases(biases, biases_r)
@parameterized.named_parameters(
ExpandNamedTestCases(
NAMED_RNN_TESTCASES, "time", "batch_size", **{
"rnn_mode": [
CUDNN_LSTM, CUDNN_GRU, CUDNN_RNN_RELU, CUDNN_RNN_TANH
],
"direction": [CUDNN_RNN_UNIDIRECTION, CUDNN_RNN_BIDIRECTION]
}))
@test_util.run_gpu_only
def test_save_restore_multi_variables(self, rnn_mode, num_units, input_size,
num_layers, direction):
# Verify the restored opaque param, once converted to tf_canonical format,
# is the same as the tf canonicals of the pre-restored param.
with self.session(use_gpu=True) as sess:
opaque_params = []
saveables = []
num_opaque_params = 2
for i in range(num_opaque_params):
opaque_params.append(
self._create_opaque_param(
rnn_mode,
num_units,
input_size,
num_layers,
direction,
name="opaque_param_%d" % i))
saveable = self._create_saveable(opaque_params[i], rnn_mode, num_units,
input_size, num_layers, direction)
ops.add_to_collection(ops.GraphKeys.SAVEABLE_OBJECTS, saveable)
saveables.append(saveable)
weights_ops, biases_ops = [], []
for i in range(num_opaque_params):
weights_op, biases_op = (
saveables[i].format_converter.opaque_to_tf_canonical(
saveables[i]._variables))
weights_ops.append(weights_op)
biases_ops.append(biases_op)
save_path = os.path.join(self.get_temp_dir(), "save_restore_var_test")
saver = saver_lib.Saver(write_version=saver_pb2.SaverDef.V2)
init_op = variables.global_variables_initializer()
reset_ops = []
for i in range(num_opaque_params):
reset_ops.append(
state_ops.assign(opaque_params[i],
array_ops.zeros_like(opaque_params[i])))
sess.run(init_op)
self.assertEqual(save_path, saver.save(sess, save_path))
# Get the tf canonical vals before reset-restore
for i in range(num_opaque_params):
weights, biases = sess.run([weights_ops[i], biases_ops[i]])
# Reset the opaque param value
sess.run(reset_ops[i])
# Assert reset happened.
weights_z, biases_z = sess.run([weights_ops[i], biases_ops[i]])
for w in weights_z:
self.assertAllClose(w, np.zeros_like(w))
for b in biases_z:
self.assertAllClose(b, np.zeros_like(b))
# Restore opaque param value from checkpoint.
saver.restore(sess, save_path)
weights_r, biases_r = sess.run([weights_ops[i], biases_ops[i]])
self._compare_weights(weights, weights_r)
self._compare_biases(biases, biases_r)
if __name__ == "__main__":
googletest.main()
| 26,415 |
432 |
package tk.wasdennnoch.androidn_ify.systemui.notifications;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.XModuleResources;
import android.content.res.XResources;
import android.graphics.Outline;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XC_MethodReplacement;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_InitPackageResources;
import de.robv.android.xposed.callbacks.XC_LayoutInflated;
import tk.wasdennnoch.androidn_ify.R;
import tk.wasdennnoch.androidn_ify.XposedHook;
import tk.wasdennnoch.androidn_ify.extracted.systemui.AlphaOptimizedButton;
import tk.wasdennnoch.androidn_ify.extracted.systemui.AlphaOptimizedImageView;
import tk.wasdennnoch.androidn_ify.extracted.systemui.ExpandableIndicator;
import tk.wasdennnoch.androidn_ify.extracted.systemui.NonInterceptingScrollView;
import tk.wasdennnoch.androidn_ify.extracted.systemui.qs.QSAnimator;
import tk.wasdennnoch.androidn_ify.extracted.systemui.qs.QSDetail;
import tk.wasdennnoch.androidn_ify.extracted.systemui.qs.QuickQSPanel;
import tk.wasdennnoch.androidn_ify.extracted.systemui.qs.TouchAnimator;
import tk.wasdennnoch.androidn_ify.misc.SafeOnClickListener;
import tk.wasdennnoch.androidn_ify.misc.SafeRunnable;
import tk.wasdennnoch.androidn_ify.systemui.SystemUIHooks;
import tk.wasdennnoch.androidn_ify.systemui.notifications.stack.StackScrollAlgorithmHooks;
import tk.wasdennnoch.androidn_ify.systemui.qs.DetailViewManager;
import tk.wasdennnoch.androidn_ify.systemui.qs.KeyguardMonitor;
import tk.wasdennnoch.androidn_ify.systemui.qs.QSTileHostHooks;
import tk.wasdennnoch.androidn_ify.systemui.qs.QuickSettingsHooks;
import tk.wasdennnoch.androidn_ify.systemui.qs.tiles.hooks.BluetoothTileHook;
import tk.wasdennnoch.androidn_ify.systemui.qs.tiles.hooks.CellularTileHook;
import tk.wasdennnoch.androidn_ify.systemui.qs.tiles.hooks.WifiTileHook;
import tk.wasdennnoch.androidn_ify.utils.ConfigUtils;
import tk.wasdennnoch.androidn_ify.utils.ResourceUtils;
import tk.wasdennnoch.androidn_ify.utils.RomUtils;
import tk.wasdennnoch.androidn_ify.utils.ViewUtils;
@SuppressLint("StaticFieldLeak")
public class StatusBarHeaderHooks {
private static final String TAG = "StatusBarHeaderHooks";
private static final int WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT;
private static final String PACKAGE_SYSTEMUI = XposedHook.PACKAGE_SYSTEMUI;
private static final String CLASS_STATUS_BAR_HEADER_VIEW = "com.android.systemui.statusbar.phone.StatusBarHeaderView";
private static final String CLASS_LAYOUT_VALUES = CLASS_STATUS_BAR_HEADER_VIEW + "$LayoutValues";
private static final String CLASS_QS_PANEL = "com.android.systemui.qs.QSPanel";
private static final String CLASS_QS_DRAG_PANEL = "com.android.systemui.qs.QSDragPanel";
private static final String CLASS_QS_TILE = "com.android.systemui.qs.QSTile";
private static final String CLASS_QS_STATE = CLASS_QS_TILE + "$State";
private static final String CLASS_QS_TILE_VIEW = "com.android.systemui.qs.QSTileView";
private static final String CLASS_DETAIL_ADAPTER = CLASS_QS_TILE + "$DetailAdapter";
private static boolean mCollapseAfterHideDetails = false;
private static boolean mHideTunerIcon = false;
private static boolean mHideEditTiles = false;
private static boolean mHideCarrierLabel = false;
private static boolean mShowFullAlarm;
private static TouchAnimator mFirstHalfAnimator;
private static TouchAnimator mSecondHalfAnimator;
private static TouchAnimator mSettingsAlpha;
public static ViewGroup mStatusBarHeaderView;
private static View mSystemIconsSuperContainer;
private static View mDateGroup;
private static AlphaOptimizedImageView mEdit;
private static FrameLayout mMultiUserSwitch;
private static View mClock;
private static TextView mDateCollapsed;
private static TextView mDateExpanded;
private static ImageButton mSettingsButton;
private static View mSettingsContainer;
private static View mQsDetailHeader;
private static TextView mQsDetailHeaderTitle;
private static Switch mQsDetailHeaderSwitch;
private static TextView mAlarmStatus;
private static TextView mEditTileDoneText;
private static View mTunerIcon;
private static LinearLayout mWeatherContainer;
private static View mTaskManagerButton;
private static View mCustomQSEditButton;
private static View mCustomQSEditButton2;
private static View mCarrierText = null;
private static ExpandableIndicator mExpandIndicator;
private static LinearLayout mDateTimeAlarmGroup;
private static LinearLayout mDateTimeGroup;
private static LinearLayout mLeftContainer;
private static LinearLayout mRightContainer;
private static Button mAlarmStatusCollapsed;
private static QuickQSPanel mHeaderQsPanel;
public static ViewGroup mQsPanel;
public static ViewGroup mQsContainer;
public static Context mContext;
private static ResourceUtils mResUtils;
private static View mCurrentDetailView;
private static ImageView mQsRightButton;
private static boolean mHasEditPanel = false;
public static boolean mShowingDetail;
public static boolean mUseDragPanel = false;
public static boolean mExpanded;
private static float mExpansion = 0;
private static boolean mRecreatingStatusBar = false;
private static final ArrayList<String> mPreviousTiles = new ArrayList<>();
public static ArrayList<Object> mRecords;
private static final Rect mClipBounds = new Rect();
public static QSAnimator mQsAnimator;
public static QuickSettingsHooks qsHooks;
private static final XC_MethodHook onFinishInflateHook = new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
XposedHook.logD(TAG, "onFinishInflateHook called");
mStatusBarHeaderView = (ViewGroup) param.thisObject;
mContext = mStatusBarHeaderView.getContext();
mResUtils = ResourceUtils.getInstance(mContext);
ResourceUtils res = mResUtils;
ConfigUtils config = ConfigUtils.getInstance();
mShowFullAlarm = res.getResources().getBoolean(R.bool.quick_settings_show_full_alarm) || config.qs.force_old_date_position;
try {
if (!config.qs.keep_header_background) {
//noinspection deprecation
mStatusBarHeaderView.setBackgroundColor(config.qs.fix_header_space ? 0 :
mContext.getResources().getColor(mContext.getResources().getIdentifier("system_primary_color", "color", PACKAGE_SYSTEMUI)));
}
} catch (Throwable t) {
XposedHook.logE(TAG, "Couldn't change header background color", t);
}
TextView mTime;
TextView mAmPm;
TextView mEmergencyCallsOnly;
TextView mWeatherLine1 = null;
TextView mWeatherLine2 = null;
try {
mSystemIconsSuperContainer = (View) XposedHelpers.getObjectField(param.thisObject, "mSystemIconsSuperContainer");
mDateGroup = (View) XposedHelpers.getObjectField(param.thisObject, "mDateGroup");
mClock = (View) XposedHelpers.getObjectField(param.thisObject, "mClock");
mTime = (TextView) XposedHelpers.getObjectField(param.thisObject, "mTime");
mAmPm = (TextView) XposedHelpers.getObjectField(param.thisObject, "mAmPm");
mMultiUserSwitch = (FrameLayout) XposedHelpers.getObjectField(param.thisObject, "mMultiUserSwitch");
mDateCollapsed = (TextView) XposedHelpers.getObjectField(param.thisObject, "mDateCollapsed");
mDateExpanded = (TextView) XposedHelpers.getObjectField(param.thisObject, "mDateExpanded");
mSettingsButton = (ImageButton) XposedHelpers.getObjectField(param.thisObject, "mSettingsButton");
mQsDetailHeader = (View) XposedHelpers.getObjectField(param.thisObject, "mQsDetailHeader");
mQsDetailHeaderTitle = (TextView) XposedHelpers.getObjectField(param.thisObject, "mQsDetailHeaderTitle");
mQsDetailHeaderSwitch = (Switch) XposedHelpers.getObjectField(param.thisObject, "mQsDetailHeaderSwitch");
mEmergencyCallsOnly = (TextView) XposedHelpers.getObjectField(param.thisObject, "mEmergencyCallsOnly");
mAlarmStatus = (TextView) XposedHelpers.getObjectField(param.thisObject, "mAlarmStatus");
if (mHasEditPanel) {
mEditTileDoneText = (TextView) XposedHelpers.getObjectField(param.thisObject, "mEditTileDoneText");
}
} catch (Throwable t) {
XposedHook.logE(TAG, "Couldn't find required views, aborting", t);
return;
}
// Separate try-catch for settings button as some ROMs removed the container around it
try {
mSettingsContainer = (View) XposedHelpers.getObjectField(param.thisObject, "mSettingsContainer");
} catch (Throwable t) {
mSettingsContainer = mSettingsButton;
}
mTunerIcon = mSettingsContainer.findViewById(mContext.getResources().getIdentifier("tuner_icon", "id", PACKAGE_SYSTEMUI));
mHideTunerIcon = config.qs.hide_tuner_icon;
mHideEditTiles = config.qs.hide_edit_tiles;
mHideCarrierLabel = config.qs.hide_carrier_label;
// workaround for a bug where the clock would get a wrong position when opening the detail view
View dummyClock = new View(mContext);
dummyClock.setVisibility(View.GONE);
XposedHelpers.setObjectField(param.thisObject, "mClock", dummyClock);
try {
mWeatherContainer = (LinearLayout) XposedHelpers.getObjectField(param.thisObject, "mWeatherContainer");
mWeatherLine1 = (TextView) XposedHelpers.getObjectField(param.thisObject, "mWeatherLine1");
mWeatherLine2 = (TextView) XposedHelpers.getObjectField(param.thisObject, "mWeatherLine2");
} catch (Throwable ignore) {
}
try {
mCarrierText = (View) XposedHelpers.getObjectField(param.thisObject, "mCarrierText");
} catch (Throwable ignore) {
}
try {
mTaskManagerButton = (View) XposedHelpers.getObjectField(param.thisObject, "mTaskManagerButton");
} catch (Throwable ignore) {
}
try { // Sony
mCustomQSEditButton = (View) XposedHelpers.getObjectField(param.thisObject, "mSomcQuickSettings");
} catch (Throwable i) {
try { // PA
mCustomQSEditButton = (View) XposedHelpers.getObjectField(param.thisObject, "mQsAddButton");
} catch (Throwable g) {
try { // OOS2 & 3
mCustomQSEditButton = (View) XposedHelpers.getObjectField(param.thisObject, "mEditModeButton");
mCustomQSEditButton2 = (View) XposedHelpers.getObjectField(param.thisObject, "mResetButton");
XposedHelpers.setObjectField(param.thisObject, "mEditModeButton", new ImageView(mContext));
} catch (Throwable ignore) {
}
}
}
try { // PA seems to screw around a bit (the image has the bg color and overlaps the expand indicator ripple)
((View) XposedHelpers.getObjectField(param.thisObject, "mBackgroundImage")).setVisibility(View.GONE);
} catch (Throwable ignore) {
}
try {
boolean mShowTaskManager = true;
try {
mShowTaskManager = XposedHelpers.getBooleanField(param.thisObject, "mShowTaskManager");
} catch (Throwable ignore) {
}
int rippleRes = mContext.getResources().getIdentifier("ripple_drawable", "drawable", XposedHook.PACKAGE_SYSTEMUI);
int rightIconHeight = res.getDimensionPixelSize(R.dimen.right_icon_size);
int rightIconWidth = mTaskManagerButton != null && mShowTaskManager ? res.getDimensionPixelSize(R.dimen.right_icon_width_small) : rightIconHeight;
int expandIndicatorPadding = res.getDimensionPixelSize(R.dimen.expand_indicator_padding);
int headerItemsMarginTop = res.getDimensionPixelSize(R.dimen.header_items_margin_top);
int alarmStatusTextColor = mAlarmStatus.getCurrentTextColor();
int dateTimeCollapsedSize = res.getDimensionPixelSize(R.dimen.date_time_collapsed_size);
int dateTimeTextColor = mTime.getCurrentTextColor();
int dateCollapsedDrawablePadding = res.getDimensionPixelSize(R.dimen.date_collapsed_drawable_padding);
int dateTimeMarginLeft = res.getDimensionPixelSize(R.dimen.date_time_alarm_group_margin_left);
Drawable alarmSmall = mContext.getDrawable(mContext.getResources().getIdentifier("ic_access_alarms_small", "drawable", XposedHook.PACKAGE_SYSTEMUI));
((ViewGroup) mClock.getParent()).removeView(mClock);
((ViewGroup) mMultiUserSwitch.getParent()).removeView(mMultiUserSwitch);
((ViewGroup) mDateCollapsed.getParent()).removeView(mDateCollapsed);
((ViewGroup) mSettingsContainer.getParent()).removeView(mSettingsContainer);
((ViewGroup) mAlarmStatus.getParent()).removeView(mAlarmStatus);
((ViewGroup) mEmergencyCallsOnly.getParent()).removeView(mEmergencyCallsOnly);
createEditButton(rightIconHeight, rightIconWidth);
Drawable settingsIcon = res.getDrawable(R.drawable.ic_settings_20dp);
mSettingsButton.setImageDrawable(settingsIcon);
RelativeLayout.LayoutParams rightContainerLp = new RelativeLayout.LayoutParams(WRAP_CONTENT, res.getDimensionPixelSize(R.dimen.right_layout_height));
rightContainerLp.addRule(RelativeLayout.ALIGN_PARENT_END);
rightContainerLp.rightMargin = res.getDimensionPixelSize(R.dimen.right_layout_margin_right);
rightContainerLp.topMargin = res.getDimensionPixelSize(R.dimen.right_layout_margin_top);
mRightContainer = new LinearLayout(mContext);
mRightContainer.setLayoutParams(rightContainerLp);
mRightContainer.setGravity(Gravity.CENTER);
mRightContainer.setOrientation(LinearLayout.HORIZONTAL);
mRightContainer.setClipChildren(false);
LinearLayout.LayoutParams multiUserSwitchLp = new LinearLayout.LayoutParams(rightIconWidth, rightIconHeight);
mMultiUserSwitch.setLayoutParams(multiUserSwitchLp);
LinearLayout.LayoutParams settingsContainerLp = new LinearLayout.LayoutParams(rightIconWidth, rightIconHeight);
mSettingsContainer.setLayoutParams(settingsContainerLp);
LinearLayout.LayoutParams expandIndicatorLp = new LinearLayout.LayoutParams(rightIconHeight, rightIconHeight); // Requires full width
mExpandIndicator = new ExpandableIndicator(mContext);
mExpandIndicator.setLayoutParams(expandIndicatorLp);
mExpandIndicator.setPadding(expandIndicatorPadding, expandIndicatorPadding, expandIndicatorPadding, expandIndicatorPadding);
mExpandIndicator.setClickable(true);
mExpandIndicator.setFocusable(true);
mExpandIndicator.setFocusableInTouchMode(false);
mExpandIndicator.setCropToPadding(false);
mExpandIndicator.setBackgroundResource(rippleRes);
mExpandIndicator.setId(R.id.statusbar_header_expand_indicator);
RelativeLayout.LayoutParams leftContainerLp = new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
leftContainerLp.addRule(RelativeLayout.ALIGN_PARENT_START);
leftContainerLp.leftMargin = dateTimeMarginLeft;
leftContainerLp.topMargin = headerItemsMarginTop;
mLeftContainer = new LinearLayout(mContext);
mLeftContainer.setLayoutParams(leftContainerLp);
mLeftContainer.setOrientation(LinearLayout.VERTICAL);
RelativeLayout.LayoutParams emergencyCallsOnlyLp = new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
emergencyCallsOnlyLp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
mEmergencyCallsOnly.setLayoutParams(emergencyCallsOnlyLp);
mEmergencyCallsOnly.setTextSize(TypedValue.COMPLEX_UNIT_PX, res.getDimensionPixelSize(R.dimen.emergency_calls_only_text_size));
mEmergencyCallsOnly.setTextColor(alarmStatusTextColor);
mEmergencyCallsOnly.setPadding(0, 0, 0, 0);
mEmergencyCallsOnly.setVisibility(View.GONE);
RelativeLayout.LayoutParams dateTimeAlarmGroupLp = new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
dateTimeAlarmGroupLp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
dateTimeAlarmGroupLp.topMargin = res.getDimensionPixelSize(R.dimen.date_time_alarm_group_margin_top);
dateTimeAlarmGroupLp.leftMargin = dateTimeMarginLeft;
mDateTimeAlarmGroup = new LinearLayout(mContext);
mDateTimeAlarmGroup.setLayoutParams(dateTimeAlarmGroupLp);
mDateTimeAlarmGroup.setId(View.generateViewId());
mDateTimeAlarmGroup.setGravity(Gravity.START);
mDateTimeAlarmGroup.setOrientation(LinearLayout.VERTICAL);
mDateTimeAlarmGroup.setBaselineAligned(false);
mDateTimeAlarmGroup.setClipChildren(false);
mDateTimeAlarmGroup.setClipToPadding(false);
LinearLayout.LayoutParams alarmStatusLp = new LinearLayout.LayoutParams(WRAP_CONTENT, res.getDimensionPixelSize(R.dimen.alarm_status_height));
mAlarmStatus.setLayoutParams(alarmStatusLp);
mAlarmStatus.setGravity(Gravity.TOP);
mAlarmStatus.setTextSize(TypedValue.COMPLEX_UNIT_PX, dateTimeCollapsedSize);
mAlarmStatus.setPadding(0, res.getDimensionPixelSize(R.dimen.alarm_status_padding_top), 0, 0);
mAlarmStatus.setCompoundDrawablePadding(res.getDimensionPixelSize(R.dimen.alarm_status_drawable_padding));
mAlarmStatus.setCompoundDrawablesWithIntrinsicBounds(alarmSmall, null, null, null);
mAlarmStatus.setVisibility(View.GONE);
mAlarmStatus.setBackgroundResource(rippleRes);
LinearLayout.LayoutParams dateTimeGroupLp = new LinearLayout.LayoutParams(WRAP_CONTENT, res.getDimensionPixelSize(R.dimen.date_time_group_height));
mDateTimeGroup = new LinearLayout(mContext);
mDateTimeGroup.setLayoutParams(dateTimeGroupLp);
mDateTimeGroup.setId(View.generateViewId());
mDateTimeGroup.setOrientation(LinearLayout.HORIZONTAL);
mDateTimeGroup.setPivotX(0.0F);
mDateTimeGroup.setPivotY(0.0F);
mDateTimeGroup.setBaselineAligned(false);
mDateTimeGroup.setClipChildren(false);
mDateTimeGroup.setClipToPadding(false);
LinearLayout.LayoutParams clockLp = new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
mClock.setLayoutParams(clockLp);
mClock.findViewById(mContext.getResources().getIdentifier("empty_time_view", "id", XposedHook.PACKAGE_SYSTEMUI)).setVisibility(View.GONE);
mTime.setTextColor(dateTimeTextColor);
mTime.setTextSize(TypedValue.COMPLEX_UNIT_PX, dateTimeCollapsedSize);
mAmPm.setTextColor(dateTimeTextColor);
mAmPm.setTextSize(TypedValue.COMPLEX_UNIT_PX, dateTimeCollapsedSize);
mAmPm.setPadding(0, 0, dateCollapsedDrawablePadding, 0);
LinearLayout.LayoutParams dateCollapsedLp = new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
mDateCollapsed.setLayoutParams(dateCollapsedLp);
mDateCollapsed.setGravity(Gravity.TOP);
mDateCollapsed.setTextColor(dateTimeTextColor);
mDateCollapsed.setTextSize(TypedValue.COMPLEX_UNIT_PX, dateTimeCollapsedSize);
mDateCollapsed.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL));
if (mShowFullAlarm) {
mDateCollapsed.setCompoundDrawablesWithIntrinsicBounds(res.getDrawable(R.drawable.header_dot), null, null, null);
mDateCollapsed.setCompoundDrawablePadding(dateCollapsedDrawablePadding);
}
LinearLayout.LayoutParams alarmStatusCollapsedLp = new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
mAlarmStatusCollapsed = new AlphaOptimizedButton(mContext);
mAlarmStatusCollapsed.setLayoutParams(alarmStatusCollapsedLp);
mAlarmStatusCollapsed.setId(View.generateViewId());
mAlarmStatusCollapsed.setGravity(Gravity.TOP);
mAlarmStatusCollapsed.setTextColor(alarmStatusTextColor);
mAlarmStatusCollapsed.setTextSize(TypedValue.COMPLEX_UNIT_PX, dateTimeCollapsedSize);
mAlarmStatusCollapsed.setClickable(false);
mAlarmStatusCollapsed.setFocusable(false);
mAlarmStatusCollapsed.setVisibility(View.GONE);
mAlarmStatusCollapsed.setCompoundDrawablesWithIntrinsicBounds(alarmSmall, null, null, null);
mAlarmStatusCollapsed.setBackgroundResource(0);
mAlarmStatusCollapsed.setPadding(res.getDimensionPixelSize(mShowFullAlarm ? R.dimen.alarm_status_collapsed_drawable_padding
: R.dimen.alarm_status_collapsed_drawable_padding_small)
, 0, 0, 0);
RelativeLayout.LayoutParams headerQsPanelLp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, WRAP_CONTENT);
mHeaderQsPanel = new QuickQSPanel(mContext);
mHeaderQsPanel.setLayoutParams(headerQsPanelLp);
mHeaderQsPanel.setClipChildren(false);
mHeaderQsPanel.setClipToPadding(false);
if (mWeatherContainer != null && mWeatherLine1 != null && mWeatherLine2 != null) {
RelativeLayout.LayoutParams weatherContainerLp = new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
weatherContainerLp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
//weatherContainerLp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
weatherContainerLp.addRule(RelativeLayout.ALIGN_PARENT_END);
weatherContainerLp.bottomMargin = headerItemsMarginTop;
//mWeatherContainer.setOrientation(LinearLayout.HORIZONTAL); // TODO Setting the orientation completely fu**s it up?! Positioned at the parent top
mWeatherContainer.setLayoutParams(weatherContainerLp);
//mWeatherLine1.setLayoutParams(new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
//mWeatherLine2.setLayoutParams(new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
//int padding = mContext.getResources().getDimensionPixelSize(mContext.getResources().getIdentifier("status_bar_weather_padding_end", "dimen", PACKAGE_SYSTEMUI));
//mWeatherLine1.setPadding(0, 0, 0, 0);
//mWeatherLine2.setPadding(0, 0, padding, 0);
//TextView dash = new TextView(mWeatherLine2.getContext());
//dash.setText(" - ");
//mWeatherContainer.addView(dash, 1, new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
}
if (mCarrierText != null) {
((ViewGroup) mCarrierText.getParent()).removeView(mCarrierText);
RelativeLayout.LayoutParams carrierTextLp = new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
mCarrierText.setLayoutParams(carrierTextLp);
mCarrierText.setPadding(0, 0, 0, 0);
}
if (mTaskManagerButton != null) {
((ViewGroup) mTaskManagerButton.getParent()).removeView(mTaskManagerButton);
LinearLayout.LayoutParams taskManagerButtonLp = new LinearLayout.LayoutParams(rightIconWidth, rightIconHeight);
mTaskManagerButton.setLayoutParams(taskManagerButtonLp);
}
try { // OOS (and maybe more in the future)
XposedHelpers.findMethodBestMatch(mStatusBarHeaderView.getClass(), "startDateActivity");
if (mStatusBarHeaderView instanceof View.OnClickListener) {
View.OnClickListener l = (View.OnClickListener) mStatusBarHeaderView;
mDateCollapsed.setOnClickListener(l);
mDateExpanded.setOnClickListener(l);
}
} catch (Throwable ignore) {
}
if (mCarrierText != null)
mLeftContainer.addView(mCarrierText);
mLeftContainer.addView(mEmergencyCallsOnly);
if (mTaskManagerButton != null)
mRightContainer.addView(mTaskManagerButton);
mRightContainer.addView(mMultiUserSwitch);
mRightContainer.addView(mEdit);
mRightContainer.addView(mSettingsContainer);
mRightContainer.addView(mExpandIndicator);
mDateTimeGroup.addView(mClock);
if (mShowFullAlarm) {
mDateTimeGroup.addView(mDateCollapsed);
}
mDateTimeGroup.addView(mAlarmStatusCollapsed);
mDateTimeAlarmGroup.addView(mDateTimeGroup);
mDateTimeAlarmGroup.addView(mAlarmStatus); // The view HAS to be attached to a parent, otherwise it apparently gets GC -> NPE. We hide it later if necessary
if (!mShowFullAlarm)
mDateTimeAlarmGroup.addView(mDateCollapsed);
mStatusBarHeaderView.addView(mRightContainer, 0);
mStatusBarHeaderView.addView(mLeftContainer, 1);
mStatusBarHeaderView.addView(mDateTimeAlarmGroup, 2);
mStatusBarHeaderView.addView(mHeaderQsPanel, 3);
mStatusBarHeaderView.setClipChildren(false);
mStatusBarHeaderView.setClipToPadding(false);
mStatusBarHeaderView.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setRect(mClipBounds);
}
});
} catch (Throwable t) {
// :(
XposedHook.logE(TAG, "Error modifying header layout", t);
return;
}
DetailViewManager.init(mContext, mStatusBarHeaderView, mQsPanel, mHasEditPanel);
postSetupAnimators();
updateResources();
}
};
private static void createEditButton(int height, int width) {
mEdit = new AlphaOptimizedImageView(mContext);
LinearLayout.LayoutParams editLp = new LinearLayout.LayoutParams(width, height);
mEdit.setLayoutParams(editLp);
int padding = mResUtils.getDimensionPixelSize(R.dimen.qs_edit_padding);
TypedValue background = new TypedValue();
mContext.getTheme().resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, background, true);
mEdit.setId(R.id.qs_edit);
mEdit.setClickable(true);
mEdit.setFocusable(true);
mEdit.setImageDrawable(mResUtils.getDrawable(R.drawable.ic_mode_edit));
mEdit.setBackground(mContext.getDrawable(background.resourceId));
mEdit.setPadding(padding, padding, padding, padding);
mEdit.setOnClickListener(onClickListener);
}
private static final XC_MethodHook setExpansionHook = new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
float f = (float) param.args[0];
mExpanded = f > 0;
mExpansion = f;
try {
if (mSettingsAlpha != null) {
if (mShowFullAlarm) {
mFirstHalfAnimator.setPosition(f);
}
mSecondHalfAnimator.setPosition(f);
mSettingsAlpha.setPosition(f);
mQsAnimator.setPosition(f);
}
mExpandIndicator.setExpanded(f > 0.93F);
} catch (Throwable ignore) {
// Oh god, a massive spam wall coming right at you, quick, hide!
}
}
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
int mGridHeight = qsHooks.getGridHeight();
if (mGridHeight == 0)
return;
View view = (View) param.thisObject;
float height = view.getHeight();
height += (int) (mGridHeight * mExpansion);
mClipBounds.set(view.getPaddingLeft(), 0, view.getWidth() - view.getPaddingRight(), (int) height);
view.setClipBounds(mClipBounds);
view.invalidateOutline();
}
};
private static final XC_MethodHook onConfigurationChangedHook = new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
updateResources();
}
};
private static final XC_MethodHook updateVisibilitiesHook = new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
if (mSystemIconsSuperContainer != null) {
boolean mExpanded = XposedHelpers.getBooleanField(param.thisObject, "mExpanded");
mSystemIconsSuperContainer.setVisibility(View.GONE);
mDateExpanded.setVisibility(View.GONE);
mDateGroup.setVisibility(View.GONE);
updateAlarmVisibilities();
mMultiUserSwitch.setVisibility(mExpanded ? View.VISIBLE : View.INVISIBLE);
mEdit.setVisibility(ConfigUtils.qs().enable_qs_editor ? mExpanded ? View.VISIBLE : View.INVISIBLE : View.GONE);
if (!mShowFullAlarm) {
mAlarmStatus.setVisibility(View.GONE);
mDateCollapsed.setVisibility(mExpanded ? View.VISIBLE : View.INVISIBLE);
} else {
mAlarmStatus.setVisibility(mExpanded && XposedHelpers.getBooleanField(mStatusBarHeaderView, "mAlarmShowing") ? View.VISIBLE : View.INVISIBLE);
mDateCollapsed.setVisibility(View.VISIBLE);
}
mSettingsContainer.setVisibility(View.VISIBLE);
if (mHideTunerIcon && mTunerIcon != null) mTunerIcon.setVisibility(View.INVISIBLE);
if (mHideEditTiles && mCustomQSEditButton != null) {
mCustomQSEditButton.setVisibility(View.GONE);
if (mCustomQSEditButton2 != null) mCustomQSEditButton2.setVisibility(View.GONE);
}
if (mHideCarrierLabel && mCarrierText != null)
mCarrierText.setVisibility(View.GONE);
if (mWeatherContainer != null) {
try {
mWeatherContainer.setVisibility(mExpanded && XposedHelpers.getBooleanField(mStatusBarHeaderView, "mShowWeather") ? View.VISIBLE : View.INVISIBLE);
} catch (Throwable ignored) {
}
}
}
}
};
private static final XC_MethodHook setEditingHook = new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
boolean editing = (boolean) param.args[0];
boolean shouldShowViews = !editing && XposedHelpers.getBooleanField(param.thisObject, "mExpanded");
if (mDateTimeAlarmGroup != null) {
mDateTimeAlarmGroup.setVisibility(editing ? View.INVISIBLE : View.VISIBLE);
mMultiUserSwitch.setVisibility(shouldShowViews ? View.VISIBLE : View.INVISIBLE);
mSettingsContainer.setVisibility(shouldShowViews ? View.VISIBLE : View.INVISIBLE);
mExpandIndicator.setVisibility(editing ? View.INVISIBLE : View.VISIBLE);
}
}
};
private static final XC_MethodHook setTilesHook = new XC_MethodHook() {
boolean cancelled = false;
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (mHeaderQsPanel != null) { // keep
XposedHook.logD(TAG, "setTilesHook Called");
if (mRecreatingStatusBar) {
XposedHook.logD(TAG, "setTilesHook: Skipping changed check due to StatusBar recreation");
return; // Otherwise all tiles are gone after recreation
}
if (mUseDragPanel && !RomUtils.isAicp()) {
XposedHook.logD(TAG, "setTilesHook: Skipping check because mUseDragPanel && !RomUtils.isAicp()");
return; // CM has tile caching logics
}
// Only set up views if the tiles actually changed
if (param.args == null || param.args.length == 0) {
XposedHook.logD(TAG, "setTilesHook: Skipping check because param.args == null || param.args.length == 0");
return; // PA already checks itself
}
Collection tiles = (Collection) param.args[0];
ArrayList<String> newTiles = new ArrayList<>();
for (Object qstile : tiles) {
newTiles.add(qstile.getClass().getSimpleName());
}
cancelled = false;
if (mPreviousTiles.equals(newTiles)) {
cancelled = true;
XposedHook.logD(TAG, "setTilesHook: Cancelling original method because mPreviousTiles.equals(newTiles)");
param.setResult(null);
return;
}
mPreviousTiles.clear();
mPreviousTiles.addAll(newTiles);
}
}
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
if (mHeaderQsPanel != null) { // keep
try {
//noinspection unchecked
mRecords = (ArrayList<Object>) XposedHelpers.getObjectField(param.thisObject, "mRecords");
// OOS: sometimes mRecords still seems to be in the StatusBarHeaderView (but empty)
if (mRecords.size() == 0) throw new Throwable();
} catch (Throwable t) {
try { // OOS
//noinspection unchecked
mRecords = (ArrayList<Object>) XposedHelpers.getObjectField(XposedHelpers.getObjectField(param.thisObject, "mGridView"), "mRecords");
} catch (Throwable t2) {
XposedHook.logE(TAG, "No tile record field found (" + t.getClass().getSimpleName() + " and " + t2.getClass().getSimpleName() + ")", null);
return;
}
}
if (!cancelled) {
mHeaderQsPanel.setTiles(mRecords);
} else {
XposedHook.logD(TAG, "setTilesHook: Not setting tiles to header because cancelled");
}
}
}
};
private static final XC_MethodHook handleStateChangedHook = new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
// This method gets called from two different processes, so we have
// to check if we are in the right one by testing if the panel is null
if (mHeaderQsPanel != null) {
Object state = XposedHelpers.getObjectField(param.thisObject, "mState");
mHeaderQsPanel.handleStateChanged(param.thisObject, state);
NotificationPanelHooks.handleStateChanged(param.thisObject, state);
}
}
};
private static final XC_MethodHook setupViewsHook = new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
View pageIndicator = (View) XposedHelpers.getObjectField(param.thisObject, "mPageIndicator");
pageIndicator.setAlpha(0);
}
};
private static void wrapQsDetail(LinearLayout layout) {
Context context = layout.getContext();
FrameLayout content = (FrameLayout) layout.findViewById(android.R.id.content);
ViewUtils.setHeight(content, ViewGroup.LayoutParams.MATCH_PARENT);
int position = layout.indexOfChild(content);
layout.removeView(content);
LinearLayout.LayoutParams scrollViewLp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
scrollViewLp.weight = 1;
NonInterceptingScrollView scrollView = new NonInterceptingScrollView(context);
scrollView.setLayoutParams(scrollViewLp);
scrollView.addView(content);
scrollView.setFillViewport(true);
layout.addView(scrollView, position);
}
private static final XC_MethodHook handleShowDetailImplHook = new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
boolean show = (boolean) param.args[1];
Object tileRecord = param.args[0];
QSDetail qsDetail = qsHooks.getQSDetail();
if (show ? NotificationPanelHooks.isCollapsed() : mCollapseAfterHideDetails) {
param.args[2] = mQsAnimator.getTileViewX(tileRecord);
param.args[3] = 0;
if (!show) {
NotificationPanelHooks.collapseIfNecessary();
}
} else {
if (tileRecord != null) {
try {
View tileView = (View) XposedHelpers.getObjectField(tileRecord, "tileView");
param.args[2] = tileView.getLeft() + tileView.getWidth() / 2;
param.args[3] = tileView.getTop() + qsHooks.getTileLayout().getOffsetTop(tileRecord) + tileView.getHeight() / 2
+ mQsPanel.getTop();
} catch (Throwable ignore) { // OOS3
}
}
}
mCollapseAfterHideDetails = false;
if (qsDetail != null) {
qsDetail.handleShowingDetail(param.args[0], (boolean) param.args[1], (int) param.args[2], (int) param.args[3]);
}
}
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
boolean show = (boolean) param.args[1];
XposedHook.logD(TAG, "handleShowDetailImpl: " + (show ? "showing" : "hiding") + " detail; expanding: " + NotificationPanelHooks.isCollapsed() + ";");
if (show && NotificationPanelHooks.isCollapsed()) {
mCollapseAfterHideDetails = true;
NotificationPanelHooks.expandIfNecessary();
}
}
};
private static void updateResources() {
if (mDateTimeGroup == null) {
return;
}
if (mShowFullAlarm) {
mFirstHalfAnimator = new TouchAnimator.Builder()
.addFloat(mAlarmStatusCollapsed, "alpha", 1.0F, 0.0F)
.build();
}
mSecondHalfAnimator = new TouchAnimator.Builder()
.addFloat(mShowFullAlarm ? mAlarmStatus : mDateCollapsed, "alpha", 0.0F, 1.0F)
.build();
TouchAnimator.Builder settingsAlphaBuilder = new TouchAnimator.Builder()
.addFloat(mEdit, "alpha", 0.0F, 1.0F)
.addFloat(mMultiUserSwitch, "alpha", 0.0F, 1.0F)
.addFloat(mLeftContainer, "alpha", 0.0F, 1.0F);
if (mWeatherContainer != null) {
settingsAlphaBuilder
.addFloat(mWeatherContainer, "alpha", 0.0F, 1.0F);
}
if (mTaskManagerButton != null) {
settingsAlphaBuilder
.addFloat(mTaskManagerButton, "alpha", 0.0F, 1.0F);
}
mSettingsAlpha = settingsAlphaBuilder.build();
boolean rtl = (boolean) XposedHelpers.callMethod(mStatusBarHeaderView.getLayoutParams(), "isLayoutRtl");
if (rtl && mDateTimeGroup.getWidth() == 0) {
if (mDateTimeGroup.getWidth() == 0) {
mDateTimeGroup.addOnLayoutChangeListener(new android.view.View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View view, int j, int k, int l, int i1, int j1, int k1, int l1, int i2) {
mDateTimeGroup.setPivotX(mStatusBarHeaderView.getWidth());
mDateTimeGroup.removeOnLayoutChangeListener(this);
}
});
} else {
mDateTimeGroup.setPivotX(mDateTimeGroup.getWidth());
}
}
}
private static void updateAlarmVisibilities() {
boolean mAlarmShowing = XposedHelpers.getBooleanField(mStatusBarHeaderView, "mAlarmShowing");
if (mAlarmStatusCollapsed != null)
mAlarmStatusCollapsed.setVisibility(mAlarmShowing ? View.VISIBLE : View.INVISIBLE);
}
private static void showDetailAdapter(boolean show, Object adapter, int[] locationInWindow) throws Exception {
Class<?> classRecord = XposedHelpers.findClass(CLASS_QS_PANEL + "$Record", mQsPanel.getContext().getClassLoader());
int xInWindow = locationInWindow[0];
int yInWindow = locationInWindow[1];
((View) mQsPanel.getParent()).getLocationInWindow(locationInWindow);
Constructor c = classRecord.getDeclaredConstructor();
c.setAccessible(true);
Object r = c.newInstance();
XposedHelpers.setObjectField(r, "detailAdapter", adapter);
XposedHelpers.setIntField(r, "x", xInWindow - locationInWindow[0]);
XposedHelpers.setIntField(r, "y", yInWindow - locationInWindow[1]);
locationInWindow[0] = xInWindow;
locationInWindow[1] = yInWindow;
XposedHelpers.callMethod(mQsPanel, "showDetail", show, r);
}
private static void handleShowingDetail(final Object detail) {
if (ConfigUtils.qs().fix_header_space) return;
final boolean showingDetail = detail != null;
mCurrentDetailView = getCurrentDetailView();
int rightButtonVisibility = View.GONE;
DetailViewManager.DetailViewAdapter detailViewAdapter = DetailViewManager.getInstance().getDetailViewAdapter(mCurrentDetailView);
if (detailViewAdapter != null && detailViewAdapter.hasRightButton()) {
rightButtonVisibility = View.VISIBLE;
mQsRightButton.setImageDrawable(mResUtils.getDrawable(detailViewAdapter.getRightButtonResId()));
}
mQsRightButton.setVisibility(rightButtonVisibility);
// Fixes an issue with the indicator having two backgrounds when layer type is hardware
mExpandIndicator.setLayerType(View.LAYER_TYPE_NONE, null);
transition(mDateTimeAlarmGroup, !showingDetail);
transition(mRightContainer, !showingDetail);
transition(mExpandIndicator, !showingDetail);
if (mExpansion < 1)
transition(mHeaderQsPanel, !showingDetail);
if (mWeatherContainer != null) {
try {
if (XposedHelpers.getBooleanField(mStatusBarHeaderView, "mShowWeather"))
transition(mWeatherContainer, !showingDetail);
} catch (Throwable ignored) {
}
}
transition(mQsDetailHeader, showingDetail);
mShowingDetail = showingDetail;
XposedHelpers.setBooleanField(mStatusBarHeaderView, "mShowingDetail", showingDetail);
if (showingDetail) {
XposedHook.logD(TAG, "handleShowingDetail: showing detail; " + detail.getClass().getSimpleName());
try {
mQsDetailHeaderTitle.setText((int) XposedHelpers.callMethod(detail, "getTitle"));
} catch (Throwable t) {
Context context = mQsDetailHeaderTitle.getContext();
Class<?> classQSTile = XposedHelpers.findClass(CLASS_QS_TILE, context.getClassLoader());
mQsDetailHeaderTitle.setText((String) XposedHelpers.callStaticMethod(classQSTile, "getDetailAdapterTitle", context, detail));
}
final Boolean toggleState = (Boolean) XposedHelpers.callMethod(detail, "getToggleState");
if (toggleState == null) {
mQsDetailHeaderSwitch.setVisibility(View.INVISIBLE);
mQsDetailHeader.setClickable(false);
} else {
mQsDetailHeaderSwitch.setVisibility(View.VISIBLE);
mQsDetailHeaderSwitch.setChecked(toggleState);
mQsDetailHeader.setClickable(true);
mQsDetailHeader.setOnClickListener(new SafeOnClickListener(TAG, "Error in mQsDetailHeader click listener") {
@Override
public void onClickSafe(View v) {
boolean checked = !mQsDetailHeaderSwitch.isChecked();
mQsDetailHeaderSwitch.setChecked(checked);
XposedHelpers.callMethod(detail, "setToggleState", checked);
}
});
}
if (mHasEditPanel) {
if ((int) XposedHelpers.callMethod(detail, "getTitle")
== mQsDetailHeader.getResources().getIdentifier("quick_settings_edit_label", "string", PACKAGE_SYSTEMUI)) {
mEditTileDoneText.setVisibility(View.VISIBLE);
} else {
mEditTileDoneText.setVisibility(View.GONE);
}
}
} else {
XposedHook.logD(TAG, "handleShowingDetail: hiding detail; collapsing: " + mCollapseAfterHideDetails);
mQsDetailHeader.setClickable(false);
}
}
private static View getCurrentDetailView() {
Object detailRecord = XposedHelpers.getObjectField(mQsPanel, "mDetailRecord");
if (detailRecord != null) {
Object detailView = XposedHelpers.getObjectField(detailRecord, "detailView");
if (detailView != null && detailView instanceof View) {
return (View) detailView;
}
}
return null;
}
public static void transition(final View v, final boolean in) {
if (in) {
v.bringToFront();
v.setVisibility(View.VISIBLE);
}
if (v.hasOverlappingRendering()) {
v.animate().withLayer();
}
v.animate()
.alpha(in ? 1 : 0)
.withEndAction(new SafeRunnable() {
@Override
public void runSafe() {
if (!in) {
v.setVisibility(View.INVISIBLE);
}
if (!ConfigUtils.M)
XposedHelpers.setBooleanField(mStatusBarHeaderView, "mDetailTransitioning", false);
}
})
.start();
}
private static final View.OnClickListener onClickListener = new SafeOnClickListener(TAG, "Error in onClickListener") {
@Override
public void onClickSafe(View v) {
switch (v.getId()) {
case R.id.qs_right:
if (mCurrentDetailView != null && mCurrentDetailView instanceof DetailViewManager.DetailViewAdapter) {
((DetailViewManager.DetailViewAdapter) mCurrentDetailView).handleRightButtonClick();
}
break;
case R.id.qs_edit:
onClickEdit(mRightContainer.getLeft() + mEdit.getLeft() + mEdit.getWidth() / 2, mEdit.getTop() + mEdit.getHeight() / 2);
break;
}
}
};
private static void onClickEdit(int vx, int vy) {
final int x = StackScrollAlgorithmHooks.mStackScrollLayout.getLeft() + vx;
showEditDismissingKeyguard(x, vy);
}
public static void showEditDismissingKeyguard(final int x, final int y) {
SystemUIHooks.startRunnableDismissingKeyguard(new Runnable() {
@Override
public void run() {
showEdit(x, y);
}
});
}
private static void showEdit(final int x, final int y) {
mQsPanel.post(new Runnable() {
@Override
public void run() {
NotificationPanelHooks.showQsCustomizer(mRecords, x, y);
}
});
}
private static KeyguardMonitor.Callback mKeyguardCallback = new KeyguardMonitor.Callback() {
@Override
public void onKeyguardChanged() {
postSetupAnimatorsImpl();
QSTileHostHooks.mKeyguard.removeCallback(this);
}
};
public static void postSetupAnimators() {
XposedHook.logD(TAG, "postSetupAnimators called");
KeyguardMonitor keyguardMonitor = QSTileHostHooks.mKeyguard;
if (keyguardMonitor == null || !keyguardMonitor.isShowing())
postSetupAnimatorsImpl();
else
keyguardMonitor.addCallback(mKeyguardCallback);
}
private static void postSetupAnimatorsImpl() {
XposedHook.logD(TAG, "postSetupAnimatorsImpl called");
// Wait until the layout is set up
// It already works after 2 frames on my device, but just to be sure use 3
mQsPanel.post(new Runnable() {
@Override
public void run() {
mQsPanel.post(new Runnable() {
@Override
public void run() {
mQsPanel.post(new SafeRunnable() {
@Override
public void runSafe() {
if (mQsAnimator != null) {
mQsAnimator.mUpdateAnimators.run();
}
}
});
}
});
}
});
}
public static void hook(ClassLoader classLoader) {
try {
if (ConfigUtils.qs().header) {
qsHooks = QuickSettingsHooks.create(classLoader);
Class<?> classStatusBarHeaderView = XposedHelpers.findClass(CLASS_STATUS_BAR_HEADER_VIEW, classLoader);
Class<?> classLayoutValues = XposedHelpers.findClass(CLASS_LAYOUT_VALUES, classLoader);
Class<?> classQSPanel = XposedHelpers.findClass(CLASS_QS_PANEL, classLoader);
Class<?> classQSTile = XposedHelpers.findClass(CLASS_QS_TILE, classLoader);
Class<?> classQSTileView = XposedHelpers.findClass(CLASS_QS_TILE_VIEW, classLoader);
Class<?> classPhoneStatusBar = XposedHelpers.findClass("com.android.systemui.statusbar.phone.PhoneStatusBar", classLoader);
try {
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "setEditing", boolean.class, setEditingHook);
mHasEditPanel = true;
} catch (NoSuchMethodError ignore) {
mHasEditPanel = false;
}
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "onFinishInflate", onFinishInflateHook);
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "setExpansion", float.class, setExpansionHook);
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "onConfigurationChanged", Configuration.class, onConfigurationChangedHook);
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "updateVisibilities", updateVisibilitiesHook);
try {
// Every time you make a typo, the errorists win.
XposedHelpers.findAndHookMethod(classLayoutValues, "interpoloate", classLayoutValues, classLayoutValues, float.class, XC_MethodReplacement.DO_NOTHING);
} catch (Throwable ignore) { // yeah thx Bliss
XposedHelpers.findAndHookMethod(classLayoutValues, "interpolate", classLayoutValues, classLayoutValues, float.class, XC_MethodReplacement.DO_NOTHING);
}
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "requestCaptureValues", XC_MethodReplacement.DO_NOTHING);
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "applyLayoutValues", classLayoutValues, XC_MethodReplacement.DO_NOTHING);
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "captureLayoutValues", classLayoutValues, XC_MethodReplacement.DO_NOTHING);
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "updateLayoutValues", float.class, XC_MethodReplacement.DO_NOTHING);
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "updateClockCollapsedMargin", XC_MethodReplacement.DO_NOTHING);
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "updateHeights", XC_MethodReplacement.DO_NOTHING);
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "updateSignalClusterDetachment", XC_MethodReplacement.DO_NOTHING);
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "updateSystemIconsLayoutParams", XC_MethodReplacement.DO_NOTHING);
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "updateAvatarScale", XC_MethodReplacement.DO_NOTHING);
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "updateClockScale", XC_MethodReplacement.DO_NOTHING);
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "updateAmPmTranslation", XC_MethodReplacement.DO_NOTHING);
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "updateClockLp", XC_MethodReplacement.DO_NOTHING);
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "updateMultiUserSwitch", XC_MethodReplacement.DO_NOTHING);
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "setClipping", float.class, XC_MethodReplacement.DO_NOTHING);
if (!ConfigUtils.qs().keep_header_background) {
try { // AICP test
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "doUpdateStatusBarCustomHeader", Drawable.class, boolean.class, XC_MethodReplacement.DO_NOTHING);
} catch (Throwable ignore) {
}
}
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "onLayout", boolean.class, int.class, int.class, int.class, int.class, new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
mAlarmStatus.setX(0);
}
});
XposedHelpers.findAndHookMethod(classStatusBarHeaderView, "onClick", View.class, new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
Object v = param.args[0];
if (v == mClock) {
try {
XposedHelpers.callMethod(param.thisObject, "startClockActivity");
} catch (Throwable ignore) {
}
} else if (v == mDateCollapsed || v == mDateExpanded) {
try {
XposedHelpers.callMethod(param.thisObject, "startDateActivity");
} catch (Throwable ignore) {
}
}
}
});
try {
XposedHelpers.findAndHookMethod(classQSPanel, "fireShowingDetail", CLASS_DETAIL_ADAPTER, new XC_MethodReplacement() {
@Override
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
handleShowingDetail(param.args[0]);
return null;
}
});
if (ConfigUtils.qs().fix_header_space) {
XposedHelpers.findAndHookMethod(classQSPanel, "showDetailAdapter", boolean.class, CLASS_DETAIL_ADAPTER, int[].class, new XC_MethodReplacement() {
@Override
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
showDetailAdapter((boolean) param.args[0], param.args[1], (int[]) param.args[2]);
return null;
}
});
}
} catch (Throwable t) {
XposedHelpers.findAndHookMethod(classQSPanel, "showDetailAdapter", boolean.class, CLASS_DETAIL_ADAPTER, int[].class, new XC_MethodReplacement() {
@Override
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
handleShowingDetail(param.args[0]);
return null;
}
});
}
mUseDragPanel = false;
try {
Class<?> classQSDragPanel = XposedHelpers.findClass(CLASS_QS_DRAG_PANEL, classLoader);
XposedHelpers.findAndHookMethod(classQSDragPanel, "setTiles", Collection.class, setTilesHook);
XposedHelpers.findAndHookMethod(classQSDragPanel, "setupViews", setupViewsHook);
XposedBridge.hookAllMethods(classQSDragPanel, "handleShowDetailImpl", handleShowDetailImplHook);
mUseDragPanel = true;
} catch (Throwable ignore) {
XposedHelpers.findAndHookConstructor(classQSPanel, Context.class, AttributeSet.class, new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
wrapQsDetail((LinearLayout) XposedHelpers.getObjectField(param.thisObject, "mDetail"));
}
});
XposedBridge.hookAllMethods(classQSPanel, "handleShowDetailImpl", handleShowDetailImplHook);
try {
XposedHelpers.findAndHookMethod(classQSPanel, "setTiles", Collection.class, setTilesHook);
} catch (Throwable t) { // PA
XposedHelpers.findAndHookMethod(classQSPanel, "setTiles", setTilesHook);
}
}
try {
XposedHelpers.findAndHookMethod(classPhoneStatusBar, "recreateStatusBar", new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
mRecreatingStatusBar = true;
}
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
mRecreatingStatusBar = false;
}
});
} catch (Throwable ignore) {
}
QSTileHostHooks.hook(classLoader);
boolean firstRowLarge = ConfigUtils.qs().large_first_row;
if (ConfigUtils.qs().new_click_behavior) {
final WifiTileHook w = new WifiTileHook(classLoader, (!mUseDragPanel && !firstRowLarge));
final BluetoothTileHook b = new BluetoothTileHook(classLoader, (!mUseDragPanel && !firstRowLarge));
final CellularTileHook c = new CellularTileHook(classLoader);
if (ConfigUtils.L1) {
XposedHelpers.findAndHookMethod(classQSTile, "handleLongClick", new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
Object that = param.thisObject;
if (w.maybeHandleLongClick(that) || b.maybeHandleLongClick(that) || c.maybeHandleLongClick(that))
param.setResult(null);
}
});
}
}
XposedHelpers.findAndHookMethod(classQSTile, "handleStateChanged", handleStateChangedHook);
try { // OOS3
XposedHelpers.findAndHookMethod(classQSTileView, "setOverlay", CLASS_QS_TILE + "$Mode", XC_MethodReplacement.DO_NOTHING);
} catch (Throwable ignore) {
}
if (ConfigUtils.L1) {
XposedHelpers.findAndHookMethod(classQSTileView, "setIcon", ImageView.class, CLASS_QS_STATE, new XC_MethodHook() {
boolean forceAnim = false;
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
View iv = (View) param.args[0];
Object headerItem = XposedHelpers.getAdditionalInstanceField(param.thisObject, "headerTileRowItem");
forceAnim = headerItem != null && (boolean) headerItem &&
!Objects.equals(XposedHelpers.getObjectField(param.args[1], "icon"),
iv.getTag(iv.getResources().getIdentifier("qs_icon_tag", "id", PACKAGE_SYSTEMUI)));
}
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
if (forceAnim) {
View iconView = (View) XposedHelpers.getObjectField(param.thisObject, "mIcon");
if (iconView instanceof ImageView) {
Drawable icon = ((ImageView) iconView).getDrawable();
if (icon instanceof Animatable) {
if (iconView.isShown()) {
((Animatable) icon).start();
String type = (String) XposedHelpers.getAdditionalInstanceField(param.thisObject, "headerTileRowType");
XposedHook.logD(TAG, "Animating QuickQS icon: " + forceAnim + (type != null ? ("; type: " + type) : ""));
} else {
((Animatable) icon).stop();
}
}
}
}
}
});
}
if (ConfigUtils.qs().enable_qs_editor) {
XposedHelpers.findAndHookMethod(PACKAGE_SYSTEMUI + ".settings.BrightnessController", classLoader, "updateIcon", boolean.class, new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
View icon = (View) XposedHelpers.getObjectField(param.thisObject, "mIcon");
if (icon != null) icon.setVisibility(View.GONE);
}
});
}
}
} catch (Throwable t) {
XposedHook.logE(TAG, "Error in hook", t);
}
}
public static int R_string_battery_panel_title;
public static void hookResSystemui(XC_InitPackageResources.InitPackageResourcesParam resparam, String modulePath) {
try {
if (ConfigUtils.qs().header) {
XModuleResources modRes = XModuleResources.createInstance(modulePath, resparam.res);
XResources.DimensionReplacement zero = new XResources.DimensionReplacement(0, TypedValue.COMPLEX_UNIT_DIP);
R_string_battery_panel_title = resparam.res.addResource(modRes, R.string.battery_panel_title);
resparam.res.setReplacement(PACKAGE_SYSTEMUI, "dimen", "notification_panel_width", modRes.fwd(R.dimen.notification_panel_width));
resparam.res.setReplacement(PACKAGE_SYSTEMUI, "dimen", "qs_peek_height", zero);
resparam.res.setReplacement(PACKAGE_SYSTEMUI, "dimen", "status_bar_header_height", modRes.fwd(R.dimen.status_bar_header_height));
resparam.res.setReplacement(PACKAGE_SYSTEMUI, "dimen", "status_bar_header_height_expanded", modRes.fwd(R.dimen.status_bar_header_height));
resparam.res.setReplacement(PACKAGE_SYSTEMUI, "dimen", "qs_emergency_calls_only_text_size", modRes.fwd(R.dimen.emergency_calls_only_text_size));
resparam.res.setReplacement(PACKAGE_SYSTEMUI, "dimen", "qs_date_collapsed_size", modRes.fwd(R.dimen.date_time_collapsed_size));
resparam.res.setReplacement(PACKAGE_SYSTEMUI, "dimen", "multi_user_avatar_collapsed_size", modRes.fwd(R.dimen.multi_user_avatar_size));
resparam.res.setReplacement(PACKAGE_SYSTEMUI, "dimen", "qs_brightness_padding_top", modRes.fwd(R.dimen.brightness_slider_padding_top));
if (ConfigUtils.M)
resparam.res.setReplacement(PACKAGE_SYSTEMUI, "dimen", "multi_user_avatar_expanded_size", modRes.fwd(R.dimen.multi_user_avatar_size));
/*
if (!ConfigUtils.qs().large_first_row) {
try {
resparam.res.setReplacement(PACKAGE_SYSTEMUI, "dimen", "qs_dual_tile_height",
new XResources.DimensionReplacement(resparam.res.getDimensionPixelSize(
resparam.res.getIdentifier("qs_tile_height", "dimen", PACKAGE_SYSTEMUI)),
TypedValue.COMPLEX_UNIT_PX));
resparam.res.setReplacement(PACKAGE_SYSTEMUI, "dimen", "qs_tile_divider_height", zero);
} catch (Throwable t) {
XposedHook.logE(TAG, "Couldn't change qs_dual_tile_height or qs_tile_divider_height (" + t.getClass().getSimpleName() + ")", null);
}
}
*/
resparam.res.setReplacement(PACKAGE_SYSTEMUI, "color", "qs_tile_divider", 0x00000000);
resparam.res.hookLayout(PACKAGE_SYSTEMUI, "layout", "status_bar_expanded_header", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
liparam.view.setElevation(0);
liparam.view.setPadding(0, 0, 0, 0);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) liparam.view.getLayoutParams();
params.height = ResourceUtils.getInstance(liparam.view.getContext()).getDimensionPixelSize(R.dimen.status_bar_header_height);
}
});
// Motorola
try {
resparam.res.hookLayout(PACKAGE_SYSTEMUI, "layout", "zz_moto_status_bar_expanded_header", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
liparam.view.setElevation(0);
liparam.view.setPadding(0, 0, 0, 0);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) liparam.view.getLayoutParams();
params.height = ResourceUtils.getInstance(liparam.view.getContext()).getDimensionPixelSize(R.dimen.status_bar_header_height);
}
});
} catch (Throwable ignore) {
}
resparam.res.hookLayout(PACKAGE_SYSTEMUI, "layout", "qs_detail_header", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
try {
LinearLayout layout = (LinearLayout) liparam.view;
Context context = layout.getContext();
ResourceUtils res = ResourceUtils.getInstance(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int padding = context.getResources().getDimensionPixelSize(context.getResources().getIdentifier("qs_panel_padding", "dimen", PACKAGE_SYSTEMUI));
TextView title = (TextView) layout.findViewById(android.R.id.title);
title.setPadding(padding, 0, 0, 0);
mQsRightButton = (ImageView) inflater.inflate(res.getLayout(R.layout.qs_right_button), null);
mQsRightButton.setOnClickListener(onClickListener);
mQsRightButton.setVisibility(View.GONE);
layout.addView(mQsRightButton);
layout.setPadding(0, 0, padding, 0);
layout.setGravity(Gravity.CENTER);
} catch (Throwable ignore) {
}
}
});
resparam.res.hookLayout(PACKAGE_SYSTEMUI, "layout", "qs_panel", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
FrameLayout layout = (FrameLayout) liparam.view;
Context context = layout.getContext();
mQsContainer = layout;
layout.setElevation(ResourceUtils.getInstance(context).getDimensionPixelSize(R.dimen.qs_container_elevation));
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) layout.getLayoutParams();
params.setMargins(0, 0, 0, 0);
params.setMarginStart(0);
params.setMarginEnd(0);
layout.setLayoutParams(params);
mQsPanel = (ViewGroup) layout.findViewById(context.getResources().getIdentifier("quick_settings_panel", "id", PACKAGE_SYSTEMUI));
}
});
}
} catch (Throwable t) {
XposedHook.logE(TAG, "Error hooking SystemUI resources", t);
}
}
public static QuickQSPanel getHeaderQsPanel() {
return mHeaderQsPanel;
}
public static void createQsAnimator() {
mQsAnimator = new QSAnimator(mQsContainer, mHeaderQsPanel, mQsPanel);
}
public static View getSettingsButton() {
return mSettingsButton;
}
}
| 34,717 |
678 |
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/iLifeSlideshow.framework/iLifeSlideshow
*/
#import <iLifeSlideshow/MPSongManager.h>
#import <iLifeSlideshow/XXUnknownSuperclass.h>
@class NSMutableDictionary, NSString, NSRecursiveLock;
@interface MPSongManager : XXUnknownSuperclass {
NSMutableDictionary *mSongDescriptions; // 4 = 0x4
NSMutableDictionary *mSongBeats; // 8 = 0x8
NSString *mSongCacheFilePath; // 12 = 0xc
NSRecursiveLock *mSongLock; // 16 = 0x10
void *mDaFunc; // 20 = 0x14
}
+ (id)sharedManager; // 0x66f6d
+ (void)releaseSharedManager; // 0x66f41
- (id)init; // 0x66fe5
- (void)dealloc; // 0x66e95
- (id)beatsForSongAtPath:(id)path progressCallback:(/*function-pointer*/ void *)callback context:(void *)context; // 0x66fb5
@end
@interface MPSongManager (Private)
- (id)cachedBeatsForSongAtPath:(id)path; // 0x674e5
@end
@interface MPSongManager (Internal)
- (void)storeBeats:(id)beats forPath:(id)path; // 0x674b9
@end
| 389 |
5,169 |
{
"name": "PickingColors",
"version": "0.1.2",
"summary": "A versatile color-picker with sliders, hex-presentation, manual input and history.",
"description": "A versatile color-picker library, that was inspired from the pod 'Color-Picker-for-iOS'.\n\nThe features planned for version 1.0 are:\n\n- Manipulate 'hue' using tap and pan on a 1-d slider.\n- Manipulate 'saturation' and 'value' using tap and pan using a 2-d color-map.\n- Manually input hex-color using the keyboard on the device.\n- Lastly selected colors are available within the picker to easily pick them again, or to see colors side by side when chosing color.\n\nFuture features planned are:\n\n- Find complementing colors\n- Improved performance for generating the color-map when sliding the hue (The performance is not currently bad due to the fact that each color-pixel is 4x4 in size).\n- Integrate 'everlof/NameThatColor' so show a nice, textual name of a color as well.",
"homepage": "https://github.com/everlof/PickColor",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"everlof": "<EMAIL>"
},
"source": {
"git": "https://github.com/everlof/PickColor.git",
"tag": "0.1.2"
},
"platforms": {
"ios": "12.0"
},
"source_files": [
"PickColor/**/*.swift",
"PickColor/Source/Persistance/PickColorModel.xcdatamodeld",
"PickColor/Source/Persistance/PickColorModel.xcdatamodeld/*.xcdatamodel"
],
"resources": [
"PickColor/Source/Persistance/PickColorModel.xcdatamodeld",
"PickColor/Source/Persistance/PickColorModel.xcdatamodeld/*.xcdatamodel"
],
"preserve_paths": "PickColor/Source/Persistance/PickColorModel.xcdatamodeld",
"frameworks": "CoreData",
"swift_version": "4.2"
}
| 610 |
591 |
/*
* ===================== create_go_oth.h ==========================
* -- tpr --
* CREATE -- 2019.04.12
* MODIFY --
* ----------------------------------------------------------
* 通用的 辅助函数
* ---------------
*/
#ifndef TPR_CREATE_GO_OTH_H
#define TPR_CREATE_GO_OTH_H
//-------------------- CPP --------------------//
#include <string>
//-------------------- Engine --------------------//
#include "tprAssert.h"
#include "tprCast.h"
#include "IntVec.h"
#include "GameObjType.h"
#include "Density.h"
namespace gameObjs{//------------- namespace gameObjs ----------------
/* ===========================================================
* apply_isFlipOver
* -----------------------------------------------------------
* 是否左右翻转
* param: fieldWeight_ -- [-100.0, 100.0]
*/
/*
inline bool apply_isFlipOver( double fieldWeight_ ){
size_t randV = cast_2_size_t(floor(fieldWeight_ * 3.1 + 911.3));
return ((randV%10)<5);
}
*/
/* ===========================================================
* apply_isSingleTRunk
* -----------------------------------------------------------
* 树,主干是否分叉
* param: fieldWeight_ -- [-100.0, 100.0]
*/
/*
inline bool apply_isSingleTRunk( double fieldWeight_ )noexcept{
size_t randV = cast_2_size_t(floor(fieldWeight_ * 3.7 + 701.7));
return ((randV%10)<5);
}
*/
/* ===========================================================
* apply_a_oakId tmp
* -----------------------------------------------------------
* 这组方法很临时。不够好...
* param: fieldWeight_ -- [-100.0, 100.0]
*/
/*
inline size_t apply_a_simpleId( double fieldWeight_, size_t _totalNum )noexcept{
size_t randV = cast_2_size_t(floor(fieldWeight_ * 5.3 + 977.1));
return randV % _totalNum;
}
*/
/* ===========================================================
* apply_treeAge_by_density tmp
* -----------------------------------------------------------
*/
inline int apply_treeAge_by_density( Density _density )noexcept{
switch( _density.get_lvl() ){
case -3: return 3; //- tmp
case -2: return 2; //- tmp
case -1: return 1; //- tmp
case 1: return 1;
case 2: return 2;
case 3: return 3;
default:
tprAssert(0);
return 3; //- never reach
}
}
inline size_t apply_randUVal_in_range( size_t randUVal_, size_t begVal_, size_t endVal_,
bool isIncludebeg_=true,
bool isIncludeEnd_=true )noexcept{
size_t fst = isIncludebeg_ ? begVal_ : (begVal_+1); // include fst
size_t lst = isIncludeEnd_ ? endVal_ : (endVal_-1); // include lst
size_t off = lst - fst + 1; // include lst
size_t ret = ((randUVal_+25533) % off) + fst;
return ret;
}
}//------------- namespace gameObjs: end ----------------
#endif
| 1,242 |
916 |
package com.vladmihalcea.flexypool.util;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* <code>LazyJndiResolver</code> - This class permits fetching a JNDI resource lazily so that the JNDI DataSource is
* retrieved on demand as opposed to the default loading option (when FlexyPool gets initialized). This is useful in
* certain environments where both the actual DataSource and FlexyPoolDataSource are configured as JNDI resources and
* the actual DataSource is not available when the FlexyPoolDataSource is injected by the CDI mechanism.
*
* @author <NAME>
* @since 1.2
*/
public final class LazyJndiResolver implements InvocationHandler {
private final String name;
private Object target;
private LazyJndiResolver() {
throw new UnsupportedOperationException("ReflectionUtils is not instantiable!");
}
/**
* The JNDI name of the associated object
*
* @param name JNDI name of the associated object
*/
private LazyJndiResolver(String name) {
this.name = name;
}
/**
* Resolves the JNDI object upon invoking any method on the associated Proxy
*
* @param proxy proxy
* @param method method
* @param args arguments
* @return return value
* @throws Throwable in case of failures
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (target == null) {
target = JndiUtils.lookup(name);
}
return method.invoke(target, args);
}
/**
* Creates a new Proxy instance
*
* @param name JNDI name of the object to be lazily looked up
* @param objectType object type
* @param <T> typed parameter
* @return Proxy object
*/
@SuppressWarnings("unchecked")
public static <T> T newInstance(String name, Class<?> objectType) {
return (T) Proxy.newProxyInstance(
ClassLoaderUtils.getClassLoader(),
new Class[]{objectType},
new LazyJndiResolver(name));
}
}
| 775 |
970 |
[{"id":1,"label":{"name":"Testing","color":"#F0AD4E","description":null},"position":1},{"id":2,"label":{"name":"Ready","color":"#FF0000","description":null},"position":2},{"id":3,"label":{"name":"Production","color":"#FF5F00","description":null},"position":3}]
| 80 |
335 |
<reponame>Safal08/Hacktoberfest-1
{
"word": "Marry",
"definitions": [
"Join in marriage.",
"Take (someone) as one's wife or husband in marriage.",
"Enter into marriage.",
"Become a member of (a family) by marriage.",
"(of a parent or guardian) give (a son or daughter) in marriage, especially for reasons of expediency.",
"Join together; combine harmoniously.",
"Blend or combine with something.",
"Splice (rope ends) together without increasing their girth."
],
"parts-of-speech": "Verb"
}
| 216 |
764 |
{"symbol": "ELAMA","address": "0xFb444c1f2B718dDfC385cB8Fd9f2D1D776b24668","overview":{"en": ""},"email": "<EMAIL>","website": "http://elamachain.io/","state": "NORMAL","links": {"blog": "https://medium.com/@elamachain","twitter": "https://twitter.com/elamachain","telegram": "https://t.me/elamachain","github": "https://github.com/ElamaChain"}}
| 138 |
521 |
<reponame>Andrik-555/retdec<gh_stars>100-1000
/**
* @file include/retdec/loader/loader/image.h
* @brief Declaration of loadable image class.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#ifndef RETDEC_LOADER_RETDEC_LOADER_IMAGE_H
#define RETDEC_LOADER_RETDEC_LOADER_IMAGE_H
#include <memory>
#include "retdec/utils/byte_value_storage.h"
#include "retdec/fileformat/fftypes.h"
#include "retdec/fileformat/file_format/file_format.h"
#include "retdec/loader/loader/segment.h"
#include "retdec/loader/utils/name_generator.h"
namespace retdec {
namespace loader {
class Image : public retdec::utils::ByteValueStorage
{
public:
Image(const std::shared_ptr<retdec::fileformat::FileFormat>& fileFormat);
virtual ~Image();
/**
* Virtual method that should be overriden in every subclass of Image. Performs the logic of loading.
*
* @return True if loading was successful, otherwise false.
*/
virtual bool load() = 0;
virtual retdec::utils::Endianness getEndianness() const override;
virtual std::size_t getNibbleLength() const override;
virtual std::size_t getByteLength() const override;
virtual std::size_t getWordLength() const override;
virtual std::size_t getBytesPerWord() const override;
virtual std::size_t getNumberOfNibblesInByte() const override;
virtual bool hasMixedEndianForDouble() const override;
virtual bool getXByte(std::uint64_t address, std::uint64_t x, std::uint64_t& res, retdec::utils::Endianness e = retdec::utils::Endianness::UNKNOWN) const override;
virtual bool getXBytes(std::uint64_t address, std::uint64_t x, std::vector<std::uint8_t>& res) const override;
virtual bool setXByte(std::uint64_t address, std::uint64_t x, std::uint64_t val, retdec::utils::Endianness e = retdec::utils::Endianness::UNKNOWN) override;
virtual bool setXBytes(std::uint64_t address, const std::vector<std::uint8_t>& res) override;
retdec::fileformat::FileFormat* getFileFormat();
const retdec::fileformat::FileFormat* getFileFormat() const;
std::weak_ptr<retdec::fileformat::FileFormat> getFileFormatWptr() const;
std::size_t getNumberOfSegments() const;
const std::vector<std::unique_ptr<Segment>>& getSegments() const;
std::uint64_t getBaseAddress() const;
void setBaseAddress(std::uint64_t baseAddress);
bool hasDataOnAddress(std::uint64_t address) const;
bool hasDataInitializedOnAddress(std::uint64_t address) const;
bool hasReadOnlyDataOnAddress(std::uint64_t address) const;
bool hasSegmentOnAddress(std::uint64_t address) const;
bool isPointer(std::uint64_t address, std::uint64_t* pointer = nullptr) const;
Segment* getSegment(std::size_t index);
Segment* getSegment(const std::string& name);
Segment* getSegmentWithIndex(std::size_t index);
Segment* getSegmentFromAddress(std::uint64_t address);
const Segment* getSegment(std::size_t index) const;
const Segment* getSegment(const std::string& name) const;
const Segment* getSegmentWithIndex(std::size_t index) const;
const Segment* getSegmentFromAddress(std::uint64_t address) const;
const Segment* getEpSegment();
std::pair<const std::uint8_t*, std::uint64_t> getRawSegmentData(std::uint64_t address) const;
const std::string& getStatusMessage() const;
const retdec::fileformat::LoaderErrorInfo & getLoaderErrorInfo() const;
protected:
Segment* insertSegment(std::unique_ptr<Segment> segment);
void removeSegment(Segment* segment);
void nameSegment(Segment* segment);
void sortSegments();
void setStatusMessage(const std::string& message);
private:
const Segment* _getSegment(std::size_t index) const;
const Segment* _getSegment(const std::string& name) const;
const Segment* _getSegmentWithIndex(std::size_t index) const;
const Segment* _getSegmentFromAddress(std::uint64_t address) const;
std::shared_ptr<retdec::fileformat::FileFormat> _fileFormat;
std::vector<std::unique_ptr<Segment>> _segments;
std::uint64_t _baseAddress;
NameGenerator _namelessSegNameGen;
std::string _statusMessage;
};
} // namespace loader
} // namespace retdec
#endif
| 1,340 |
790 |
<filename>lib/django-1.4/django/contrib/databrowse/__init__.py
import warnings
from django.contrib.databrowse.sites import DatabrowsePlugin, ModelDatabrowse, DatabrowseSite, site
warnings.warn("The Databrowse contrib app is deprecated",
PendingDeprecationWarning)
| 95 |
17,004 |
<reponame>BillyMagarali/zulip
from zerver.lib.test_classes import WebhookTestCase
class OpenCollectiveHookTests(WebhookTestCase):
STREAM_NAME = "test"
URL_TEMPLATE = "/api/v1/external/opencollective?&api_key={api_key}&stream={stream}"
WEBHOOK_DIR_NAME = "opencollective"
# Note: Include a test function per each distinct message condition your integration supports
def test_one_time_donation(self) -> None: # test one time donation
expected_topic = "New Member"
expected_message = "@_**Λευτέρης Κυριαζάνος** donated **€1.00**! :tada:"
self.check_webhook(
"one_time_donation",
expected_topic,
expected_message,
content_type="application/x-www-form-urlencoded",
)
def test_one_time_incognito_donation(self) -> None: # test one time incognito donation
expected_topic = "New Member"
expected_message = "An **Incognito** member donated **$1.00**! :tada:"
# use fixture named helloworld_hello
self.check_webhook(
"one_time_incognito_donation",
expected_topic,
expected_message,
content_type="application/x-www-form-urlencoded",
)
| 535 |
1,473 |
<filename>test/e2e/test_input/wxWidgets/include/wx/xrc/xh_ribbon.h
/////////////////////////////////////////////////////////////////////////////
// Name: wx/xrc/xh_ribbon.h
// Purpose: XML resource handler for wxRibbon related classes
// Author: <NAME>
// Created: 2010-04-23
// Copyright: (c) 2010 <NAME>
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_XRC_XH_RIBBON_H_
#define _WX_XRC_XH_RIBBON_H_
#include "wx/xrc/xmlres.h"
#if wxUSE_XRC && wxUSE_RIBBON
class WXDLLIMPEXP_FWD_RIBBON wxRibbonControl;
class WXDLLIMPEXP_RIBBON wxRibbonXmlHandler : public wxXmlResourceHandler
{
public:
wxRibbonXmlHandler();
virtual wxObject *DoCreateResource() wxOVERRIDE;
virtual bool CanHandle(wxXmlNode *node) wxOVERRIDE;
private:
const wxClassInfo *m_isInside;
bool IsRibbonControl (wxXmlNode *node);
wxObject* Handle_buttonbar();
wxObject* Handle_button();
wxObject* Handle_control();
wxObject* Handle_page();
wxObject* Handle_gallery();
wxObject* Handle_galleryitem();
wxObject* Handle_panel();
wxObject* Handle_bar();
void Handle_RibbonArtProvider(wxRibbonControl *control);
wxDECLARE_DYNAMIC_CLASS(wxRibbonXmlHandler);
};
#endif // wxUSE_XRC && wxUSE_RIBBON
#endif // _WX_XRC_XH_RIBBON_H_
| 549 |
335 |
{
"word": "Tactician",
"definitions": [
"A person who uses a carefully planned strategy to achieve a specific end."
],
"parts-of-speech": "Noun"
}
| 66 |
937 |
<gh_stars>100-1000
{
"name": "webcomponents-polyfills",
"private": true,
"description": "Webcomponents polyfills monorepo",
"license": "BSD-3-Clause",
"author": "The Polymer Authors",
"scripts": {
"bootstrap": "lerna bootstrap --ci --reject-cycles",
"build": "lerna run build --stream",
"build:watch": "lerna run build:watch --parallel",
"format": "npm run format:eslint && npm run format:prettier",
"format:eslint": "npm run lint -- --fix",
"format:prettier": "prettier \"**/*.{cjs,html,js,json,md,ts,yml}\" --write",
"ignore-sync": "ignore-sync .",
"lint": "eslint \"**/*.{html,js,ts}\"",
"nuke": "rm -rf package-lock.json node_modules && npm install && lerna exec \"rm -f package-lock.json\" && lerna clean --yes && lerna bootstrap && lerna exec --stream -- \"test -f package-lock.json || npm install --package-lock-only\"",
"test": "npm run test:wct",
"test-pack": "lerna exec \"npm pack\"",
"test-sauce": "wct -s 'windows 10/microsoftedge@17' -s 'windows 10/microsoftedge@15' -s 'windows 8.1/internet explorer@11' -s 'macos 10.13/safari@12' -s 'macos 10.13/safari@11' -s 'os x 10.11/safari@10' -s 'os x 10.11/safari@9' -s 'Linux/chrome@41'",
"test:wct": "wct",
"test:wtr": "web-test-runner"
},
"devDependencies": {
"@gulp-sourcemaps/sources-content": "^1.0.0",
"@open-wc/testing": "^2.5.33",
"@typescript-eslint/eslint-plugin": "^4.14.0",
"@typescript-eslint/parser": "^4.14.0",
"@web/test-runner": "^0.13.4",
"@web/test-runner-mocha": "^0.7.2",
"@web/test-runner-playwright": "^0.8.5",
"babel-core": "^6.26.3",
"chokidar-cli": "^2.1.0",
"del": "^3.0.0",
"eslint": "^7.18.0",
"eslint-plugin-html": "^6.1.1",
"google-closure-compiler": "^20210202.0.0",
"gulp": "^4.0.0",
"gulp-babel": "^7.0.1",
"gulp-rename": "^1.4.0",
"gulp-rollup": "^2.16.2",
"gulp-size": "^3.0.0",
"gulp-sourcemaps": "^2.6.4",
"husky": "^4.3.8",
"ignore-sync": "^3.0.1",
"lerna": "^3.13.3",
"lint-staged": "^10.5.3",
"prettier": "2.2.1",
"prettier-plugin-package": "^1.3.0",
"rollup": "^0.62.0",
"rollup-plugin-babel": "^3.0.7",
"rollup-plugin-commonjs": "^9.2.0",
"rollup-plugin-license": "^0.8.1",
"typescript": "^4.0.3",
"wct-browser-legacy": "^1.0.2",
"web-component-tester": "^6.9.2"
},
"husky": {
"hooks": {
"pre-commit": "npm run ignore-sync && lint-staged"
}
},
"lint-staged": {
"**/*.{cjs,html,js,json,md,ts,yml}": "prettier --write",
"**/*.{js,ts}": "eslint --fix"
}
}
| 1,280 |
841 |
<reponame>brunolmfg/resteasy
package org.jboss.resteasy.test.resource.param.resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import jakarta.ws.rs.CookieParam;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import org.jboss.resteasy.annotations.Separator;
@Path("cookie")
public class MultiValuedParamDefaultParamConverterCookieResource {
//////////////////////////////////
// MultiValuedParamDefaultParamConverterConstructorClass
@Path("constructor/separator/list")
@GET
public String cookieConstructorSeparatorList(@CookieParam("c") @Separator("#") List<MultiValuedParamDefaultParamConverterConstructorClass> list) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterConstructorClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("constructor/separator/set")
@GET
public String cookieConstructorSeparatorSet(@CookieParam("c") @Separator("#") Set<MultiValuedParamDefaultParamConverterConstructorClass> set) {
List<MultiValuedParamDefaultParamConverterConstructorClass> list = new ArrayList<MultiValuedParamDefaultParamConverterConstructorClass>(set);
Collections.sort(list, MultiValuedParamDefaultParamConverterConstructorClass.COMP);
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterConstructorClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("constructor/separator/sortedset")
@GET
public String cookieConstructorSeparatorSortedSet(@CookieParam("c") @Separator("#") SortedSet<MultiValuedParamDefaultParamConverterConstructorClass> set) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterConstructorClass t : set) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("constructor/separator/array")
@GET
public String cookieConstructorSeparatorArray(@CookieParam("c") @Separator("#") MultiValuedParamDefaultParamConverterConstructorClass[] array) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterConstructorClass t : array) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("constructor/regex/list")
@GET
public String cookieConstructorRegexList(@CookieParam("c") @Separator("[#-,]") List<MultiValuedParamDefaultParamConverterConstructorClass> list) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterConstructorClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("constructor/regex/set")
@GET
public String cookieConstructorRegexSet(@CookieParam("c") @Separator("[#-,]") Set<MultiValuedParamDefaultParamConverterConstructorClass> set) {
List<MultiValuedParamDefaultParamConverterConstructorClass> list = new ArrayList<MultiValuedParamDefaultParamConverterConstructorClass>(set);
Collections.sort(list, MultiValuedParamDefaultParamConverterConstructorClass.COMP);
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterConstructorClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("constructor/regex/sortedset")
@GET
public String cookieConstructorRegexSortedSet(@CookieParam("c") @Separator("[#-,]") SortedSet<MultiValuedParamDefaultParamConverterConstructorClass> set) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterConstructorClass t : set) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("constructor/regex/array")
@GET
public String cookieConstructorRegexArray(@CookieParam("c") @Separator("[#-,]") MultiValuedParamDefaultParamConverterConstructorClass[] array) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterConstructorClass t : array) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("constructor/default/list")
@GET
public String cookieConstructorDefaultList(@CookieParam("c") @Separator List<MultiValuedParamDefaultParamConverterConstructorClass> list) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterConstructorClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("constructor/default/set")
@GET
public String cookieConstructorDefaultSet(@CookieParam("c") @Separator Set<MultiValuedParamDefaultParamConverterConstructorClass> set) {
List<MultiValuedParamDefaultParamConverterConstructorClass> list = new ArrayList<MultiValuedParamDefaultParamConverterConstructorClass>(set);
Collections.sort(list, MultiValuedParamDefaultParamConverterConstructorClass.COMP);
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterConstructorClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("constructor/default/sortedset")
@GET
public String cookieConstructorDefaultSortedSet(@CookieParam("c") @Separator SortedSet<MultiValuedParamDefaultParamConverterConstructorClass> set) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterConstructorClass t : set) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("constructor/default/array")
@GET
public String cookieConstructorDefaultArray(@CookieParam("c") @Separator MultiValuedParamDefaultParamConverterConstructorClass[] array) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterConstructorClass t : array) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
//////////////////////////////////
// MultiValuedParamDefaultParamConverterValueOfClass
@Path("valueOf/separator/list")
@GET
public String cookieValueOfSeparatorList(@CookieParam("c") @Separator("#") List<MultiValuedParamDefaultParamConverterValueOfClass> list) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterValueOfClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("valueOf/separator/set")
@GET
public String cookieValueOfSeparatorSet(@CookieParam("c") @Separator("#") Set<MultiValuedParamDefaultParamConverterValueOfClass> set) {
List<MultiValuedParamDefaultParamConverterValueOfClass> list = new ArrayList<MultiValuedParamDefaultParamConverterValueOfClass>(set);
Collections.sort(list, MultiValuedParamDefaultParamConverterValueOfClass.COMP);
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterValueOfClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("valueOf/separator/sortedset")
@GET
public String cookieValueOfSeparatorSortedSet(@CookieParam("c") @Separator("#") SortedSet<MultiValuedParamDefaultParamConverterValueOfClass> set) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterValueOfClass t : set) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("valueOf/separator/array")
@GET
public String cookieValueOfSeparatorArray(@CookieParam("c") @Separator("#") MultiValuedParamDefaultParamConverterValueOfClass[] array) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterValueOfClass t : array) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("valueOf/regex/list")
@GET
public String cookieValueOfRegexList(@CookieParam("c") @Separator("[#-,]") List<MultiValuedParamDefaultParamConverterValueOfClass> list) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterValueOfClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("valueOf/regex/set")
@GET
public String cookieValueOfRegexSet(@CookieParam("c") @Separator("[#-,]") Set<MultiValuedParamDefaultParamConverterValueOfClass> set) {
List<MultiValuedParamDefaultParamConverterValueOfClass> list = new ArrayList<MultiValuedParamDefaultParamConverterValueOfClass>(set);
Collections.sort(list, MultiValuedParamDefaultParamConverterValueOfClass.COMP);
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterValueOfClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("valueOf/regex/sortedset")
@GET
public String cookieValueOfRegexSortedSet(@CookieParam("c") @Separator("[#-,]") SortedSet<MultiValuedParamDefaultParamConverterValueOfClass> set) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterValueOfClass t : set) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("valueOf/regex/array")
@GET
public String cookieValueOfRegexArray(@CookieParam("c") @Separator("[#-,]") MultiValuedParamDefaultParamConverterValueOfClass[] array) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterValueOfClass t : array) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("valueOf/default/list")
@GET
public String cookieValueOfDefaultList(@CookieParam("c") @Separator List<MultiValuedParamDefaultParamConverterValueOfClass> list) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterValueOfClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("valueOf/default/set")
@GET
public String cookieValueOfRegexSetDefault(@CookieParam("c") @Separator Set<MultiValuedParamDefaultParamConverterValueOfClass> set) {
List<MultiValuedParamDefaultParamConverterValueOfClass> list = new ArrayList<MultiValuedParamDefaultParamConverterValueOfClass>(set);
Collections.sort(list, MultiValuedParamDefaultParamConverterValueOfClass.COMP);
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterValueOfClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("valueOf/default/sortedset")
@GET
public String cookieValueOfDefaultSortedSet(@CookieParam("c") @Separator SortedSet<MultiValuedParamDefaultParamConverterValueOfClass> set) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterValueOfClass t : set) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("valueOf/default/array")
@GET
public String cookieValueOfDefaultArray(@CookieParam("c") @Separator MultiValuedParamDefaultParamConverterValueOfClass[] array) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterValueOfClass t : array) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("fromString/separator/list")
@GET
public String cookieFromStringSeparatorList(@CookieParam("c") @Separator("#") List<MultiValuedParamDefaultParamConverterFromStringClass> list) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterFromStringClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("fromString/separator/set")
@GET
public String cookieFromStringSeparatorSet(@CookieParam("c") @Separator("#") Set<MultiValuedParamDefaultParamConverterFromStringClass> set) {
List<MultiValuedParamDefaultParamConverterFromStringClass> list = new ArrayList<MultiValuedParamDefaultParamConverterFromStringClass>(set);
Collections.sort(list, MultiValuedParamDefaultParamConverterFromStringClass.COMP);
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterFromStringClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("fromString/separator/sortedset")
@GET
public String cookieFromStringSeparatorSortedSet(@CookieParam("c") @Separator("#") SortedSet<MultiValuedParamDefaultParamConverterFromStringClass> set) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterFromStringClass t : set) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("fromString/separator/array")
@GET
public String cookieFromStringSeparatorArray(@CookieParam("c") @Separator("#") MultiValuedParamDefaultParamConverterFromStringClass[] array) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterFromStringClass t : array) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("fromString/regex/list")
@GET
public String cookieFromStringRegexList(@CookieParam("c") @Separator("[#-,]") List<MultiValuedParamDefaultParamConverterFromStringClass> list) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterFromStringClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("fromString/regex/set")
@GET
public String cookieFromStringRegexSet(@CookieParam("c") @Separator("[#-,]") Set<MultiValuedParamDefaultParamConverterFromStringClass> set) {
List<MultiValuedParamDefaultParamConverterFromStringClass> list = new ArrayList<MultiValuedParamDefaultParamConverterFromStringClass>(set);
Collections.sort(list, MultiValuedParamDefaultParamConverterFromStringClass.COMP);
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterFromStringClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("fromString/regex/sortedset")
@GET
public String cookieFromStringRegexSortedSet(@CookieParam("c") @Separator("[#-,]") SortedSet<MultiValuedParamDefaultParamConverterFromStringClass> set) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterFromStringClass t : set) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("fromString/regex/array")
@GET
public String cookieFromStringRegexArray(@CookieParam("c") @Separator("[#-,]") MultiValuedParamDefaultParamConverterFromStringClass[] array) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterFromStringClass t : array) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("fromString/default/list")
@GET
public String cookieFromStringDefaultList(@CookieParam("c") @Separator List<MultiValuedParamDefaultParamConverterFromStringClass> list) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterFromStringClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("fromString/default/set")
@GET
public String cookieFromStringDefaultSet(@CookieParam("c") @Separator Set<MultiValuedParamDefaultParamConverterFromStringClass> set) {
List<MultiValuedParamDefaultParamConverterFromStringClass> list = new ArrayList<MultiValuedParamDefaultParamConverterFromStringClass>(set);
Collections.sort(list, MultiValuedParamDefaultParamConverterFromStringClass.COMP);
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterFromStringClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("fromString/default/sortedset")
@GET
public String cookieFromStringDefaultSortedSet(@CookieParam("c") @Separator SortedSet<MultiValuedParamDefaultParamConverterFromStringClass> set) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterFromStringClass t : set) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("fromString/default/array")
@GET
public String cookieFromStringDefaultArray(@CookieParam("c") @Separator MultiValuedParamDefaultParamConverterFromStringClass[] array) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterFromStringClass t : array) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("paramConverter/separator/list")
@GET
public String cookieParamConverterSeparatorList(@CookieParam("c") @Separator("#") List<MultiValuedParamDefaultParamConverterParamConverterClass> list) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterParamConverterClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("paramConverter/separator/set")
@GET
public String cookieParamConverterSeparatorSet(@CookieParam("c") @Separator("#") Set<MultiValuedParamDefaultParamConverterParamConverterClass> set) {
List<MultiValuedParamDefaultParamConverterParamConverterClass> list = new ArrayList<MultiValuedParamDefaultParamConverterParamConverterClass>(set);
Collections.sort(list, MultiValuedParamDefaultParamConverterParamConverterClass.COMP);
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterParamConverterClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("paramConverter/separator/sortedset")
@GET
public String cookieParamConverterSeparatorSortedSet(@CookieParam("c") @Separator("#") SortedSet<MultiValuedParamDefaultParamConverterParamConverterClass> set) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterParamConverterClass t : set) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("paramConverter/separator/array")
@GET
public String cookieParamConverterSeparatorArray(@CookieParam("c") @Separator("#") MultiValuedParamDefaultParamConverterParamConverterClass[] array) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterParamConverterClass t : array) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("paramConverter/regex/list")
@GET
public String cookieParamConverterRegexList(@CookieParam("c") @Separator("[#-,]") List<MultiValuedParamDefaultParamConverterParamConverterClass> list) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterParamConverterClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("paramConverter/regex/set")
@GET
public String cookieParamConverterRegexSet(@CookieParam("c") @Separator("[#-,]") Set<MultiValuedParamDefaultParamConverterParamConverterClass> set) {
List<MultiValuedParamDefaultParamConverterParamConverterClass> list = new ArrayList<MultiValuedParamDefaultParamConverterParamConverterClass>(set);
Collections.sort(list, MultiValuedParamDefaultParamConverterParamConverterClass.COMP);
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterParamConverterClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("paramConverter/regex/sortedset")
@GET
public String cookieParamConverterRegexSortedSet(@CookieParam("c") @Separator("[#-,]") SortedSet<MultiValuedParamDefaultParamConverterParamConverterClass> set) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterParamConverterClass t : set) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("paramConverter/regex/array")
@GET
public String cookieParamConverterRegexArray(@CookieParam("c") @Separator("[#-,]") MultiValuedParamDefaultParamConverterParamConverterClass[] array) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterParamConverterClass t : array) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("paramConverter/default/list")
@GET
public String cookieParamConverterDefaultList(@CookieParam("c") @Separator List<MultiValuedParamDefaultParamConverterParamConverterClass> list) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterParamConverterClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("paramConverter/default/set")
@GET
public String cookieParamConverterDefaultSet(@CookieParam("c") @Separator Set<MultiValuedParamDefaultParamConverterParamConverterClass> set) {
List<MultiValuedParamDefaultParamConverterParamConverterClass> list = new ArrayList<MultiValuedParamDefaultParamConverterParamConverterClass>(set);
Collections.sort(list, MultiValuedParamDefaultParamConverterParamConverterClass.COMP);
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterParamConverterClass t : list) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("paramConverter/default/sortedset")
@GET
public String cookieParamConverterDefaultSortedSet(@CookieParam("c") @Separator SortedSet<MultiValuedParamDefaultParamConverterParamConverterClass> set) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterParamConverterClass t : set) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("paramConverter/default/array")
@GET
public String cookieParamConverterDefaultArray(@CookieParam("c") @Separator MultiValuedParamDefaultParamConverterParamConverterClass[] array) {
StringBuffer sb = new StringBuffer();
for (MultiValuedParamDefaultParamConverterParamConverterClass t : array) {
sb.append(t.getS()).append("|");
}
return sb.toString();
}
@Path("boolean")
@GET
public String cookieBoolean(@CookieParam("c") @Separator("#") boolean[] array) {
StringBuffer sb = new StringBuffer();
for (boolean b : array) {
sb.append(b).append("|");
}
return sb.toString();
}
@Path("byte")
@GET
public String cookieByte(@CookieParam("c") @Separator("#") byte[] array) {
StringBuffer sb = new StringBuffer();
for (byte b : array) {
sb.append(b).append("|");
}
return sb.toString();
}
@Path("char")
@GET
public String cookieChar(@CookieParam("c") @Separator("#") char[] array) {
StringBuffer sb = new StringBuffer();
for (char c : array) {
sb.append(c).append("|");
}
return sb.toString();
}
@Path("short")
@GET
public String cookieShort(@CookieParam("c") @Separator("#") short[] array) {
StringBuffer sb = new StringBuffer();
for (short b : array) {
sb.append(b).append("|");
}
return sb.toString();
}
@Path("int")
@GET
public String cookieShort(@CookieParam("c") @Separator("#") int[] array) {
StringBuffer sb = new StringBuffer();
for (int i : array) {
sb.append(i).append("|");
}
return sb.toString();
}
@Path("long")
@GET
public String cookieLong(@CookieParam("c") @Separator("#") long[] array) {
StringBuffer sb = new StringBuffer();
for (long l : array) {
sb.append(l).append("|");
}
return sb.toString();
}
@Path("float")
@GET
public String cookieFloat(@CookieParam("c") @Separator("#") float[] array) {
StringBuffer sb = new StringBuffer();
for (float f : array) {
sb.append(f).append("|");
}
return sb.toString();
}
@Path("double")
@GET
public String cookieDouble(@CookieParam("c") @Separator("#") double[] array) {
StringBuffer sb = new StringBuffer();
for (double d : array) {
sb.append(d).append("|");
}
return sb.toString();
}
}
| 9,344 |
3,156 |
from test.integration.base import DBTIntegrationTest, use_profile
import yaml
class TestGraphSelection(DBTIntegrationTest):
@property
def schema(self):
return "graph_selection_tests_007"
@property
def models(self):
return "models"
@property
def selectors_config(self):
return yaml.safe_load('''
selectors:
- name: same_intersection
definition:
intersection:
- fqn: users
- fqn:users
- name: tags_intersection
definition:
intersection:
- tag: bi
- tag: users
- name: triple_descending
definition:
intersection:
- fqn: "*"
- tag: bi
- tag: users
- name: triple_ascending
definition:
intersection:
- tag: users
- tag: bi
- fqn: "*"
- name: intersection_with_exclusion
definition:
intersection:
- method: fqn
value: users_rollup_dependency
parents: true
- method: fqn
value: users
children: true
- exclude:
- users_rollup_dependency
- name: intersection_exclude_intersection
definition:
intersection:
- tag:bi
- "@users"
- exclude:
- intersection:
- tag:bi
- method: fqn
value: users_rollup
children: true
- name: intersection_exclude_intersection_lack
definition:
intersection:
- tag:bi
- "@users"
- exclude:
- intersection:
- method: fqn
value: emails
children_parents: true
- method: fqn
value: emails_alt
children_parents: true
''')
def _verify_selected_users(self, results):
# users
self.assertEqual(len(results), 1)
created_models = self.get_models_in_schema()
self.assertIn('users', created_models)
self.assertNotIn('users_rollup', created_models)
self.assertNotIn('emails_alt', created_models)
self.assertNotIn('subdir', created_models)
self.assertNotIn('nested_users', created_models)
@use_profile('postgres')
def test__postgres__same_model_intersection(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(['run', '--models', 'users,users'])
self._verify_selected_users(results)
@use_profile('postgres')
def test__postgres__same_model_intersection_selectors(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(['run', '--selector', 'same_intersection'])
self._verify_selected_users(results)
@use_profile('postgres')
def test__postgres__tags_intersection(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(['run', '--models', 'tag:bi,tag:users'])
self._verify_selected_users(results)
@use_profile('postgres')
def test__postgres__tags_intersection_selectors(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(['run', '--selector', 'tags_intersection'])
self._verify_selected_users(results)
@use_profile('postgres')
def test__postgres__intersection_triple_descending(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(['run', '--models', '*,tag:bi,tag:users'])
self._verify_selected_users(results)
@use_profile('postgres')
def test__postgres__intersection_triple_descending_schema(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(['run', '--models', '*,tag:bi,tag:users'])
self._verify_selected_users(results)
@use_profile('postgres')
def test__postgres__intersection_triple_descending_schema_selectors(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(['run', '--selector', 'triple_descending'])
self._verify_selected_users(results)
@use_profile('postgres')
def test__postgres__intersection_triple_ascending(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(['run', '--models', 'tag:users,tag:bi,*'])
self._verify_selected_users(results)
@use_profile('postgres')
def test__postgres__intersection_triple_ascending_schema_selectors(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(['run', '--selector', 'triple_ascending'])
self._verify_selected_users(results)
def _verify_selected_users_and_rollup(self, results):
# users, users_rollup
self.assertEqual(len(results), 2)
created_models = self.get_models_in_schema()
self.assertIn('users', created_models)
self.assertIn('users_rollup', created_models)
self.assertNotIn('emails_alt', created_models)
self.assertNotIn('subdir', created_models)
self.assertNotIn('nested_users', created_models)
@use_profile('postgres')
def test__postgres__intersection_with_exclusion(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(['run', '--models', '+users_rollup_dependency,users+', '--exclude', 'users_rollup_dependency'])
self._verify_selected_users_and_rollup(results)
@use_profile('postgres')
def test__postgres__intersection_with_exclusion_selectors(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(['run', '--selector', 'intersection_with_exclusion'])
self._verify_selected_users_and_rollup(results)
@use_profile('postgres')
def test__postgres__intersection_exclude_intersection(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(
['run', '--models', 'tag:bi,@users', '--exclude',
'tag:bi,users_rollup+'])
self._verify_selected_users(results)
@use_profile('postgres')
def test__postgres__intersection_exclude_intersection_selectors(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(
['run', '--selector', 'intersection_exclude_intersection']
)
self._verify_selected_users(results)
@use_profile('postgres')
def test__postgres__intersection_exclude_intersection_lack(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(
['run', '--models', 'tag:bi,@users', '--exclude',
'@emails,@emails_alt'])
self._verify_selected_users_and_rollup(results)
@use_profile('postgres')
def test__postgres__intersection_exclude_intersection_lack_selector(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(
['run', '--selector', 'intersection_exclude_intersection_lack'])
self._verify_selected_users_and_rollup(results)
@use_profile('postgres')
def test__postgres__intersection_exclude_triple_intersection(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(
['run', '--models', 'tag:bi,@users', '--exclude',
'*,tag:bi,users_rollup'])
self._verify_selected_users(results)
@use_profile('postgres')
def test__postgres__intersection_concat(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(
['run', '--models', 'tag:bi,@users', 'emails_alt'])
# users, users_rollup, emails_alt
self.assertEqual(len(results), 3)
created_models = self.get_models_in_schema()
self.assertIn('users', created_models)
self.assertIn('users_rollup', created_models)
self.assertIn('emails_alt', created_models)
self.assertNotIn('subdir', created_models)
self.assertNotIn('nested_users', created_models)
@use_profile('postgres')
def test__postgres__intersection_concat_intersection(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(
['run', '--models', 'tag:bi,@users', '@emails_alt,emails_alt'])
# users, users_rollup, emails_alt
self.assertEqual(len(results), 3)
created_models = self.get_models_in_schema()
self.assertIn('users', created_models)
self.assertIn('users_rollup', created_models)
self.assertIn('emails_alt', created_models)
self.assertNotIn('subdir', created_models)
self.assertNotIn('nested_users', created_models)
@use_profile('postgres')
def test__postgres__intersection_concat_exclude(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(
['run', '--models', 'tag:bi,@users', 'emails_alt', '--exclude', 'users_rollup']
)
# users, emails_alt
self.assertEqual(len(results), 2)
created_models = self.get_models_in_schema()
self.assertIn('users', created_models)
self.assertIn('emails_alt', created_models)
self.assertNotIn('users_rollup', created_models)
self.assertNotIn('subdir', created_models)
self.assertNotIn('nested_users', created_models)
@use_profile('postgres')
def test__postgres__intersection_concat_exclude_concat(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(
['run', '--models', 'tag:bi,@users', 'emails_alt,@users',
'--exclude', 'users_rollup_dependency', 'users_rollup'])
# users, emails_alt
self.assertEqual(len(results), 2)
created_models = self.get_models_in_schema()
self.assertIn('users', created_models)
self.assertIn('emails_alt', created_models)
self.assertNotIn('users_rollup', created_models)
self.assertNotIn('subdir', created_models)
self.assertNotIn('nested_users', created_models)
@use_profile('postgres')
def test__postgres__intersection_concat_exclude_intersection_concat(self):
self.run_sql_file("seed.sql")
results = self.run_dbt(
['run', '--models', 'tag:bi,@users', 'emails_alt,@users',
'--exclude', '@users,users_rollup_dependency', '@users,users_rollup'])
# users, emails_alt
self.assertEqual(len(results), 2)
created_models = self.get_models_in_schema()
self.assertIn('users', created_models)
self.assertIn('emails_alt', created_models)
self.assertNotIn('users_rollup', created_models)
self.assertNotIn('subdir', created_models)
self.assertNotIn('nested_users', created_models)
| 5,191 |
347 |
<reponame>jihwahn1018/ovirt-engine<filename>backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/vdsbroker/VMInfoListReturn.java
package org.ovirt.engine.core.vdsbroker.vdsbroker;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings("unchecked")
public final class VMInfoListReturn {
private static final String STATUS = "status";
private static final String STATS_LIST = "statsList";
public Status status;
public Map<String, Object>[] infoList;
public VMInfoListReturn(Map<String, Object> innerMap) {
status = new Status((Map<String, Object>) innerMap.get(STATUS));
Object[] temp = (Object[]) innerMap.get(STATS_LIST);
if (temp != null) {
infoList = new HashMap[temp.length];
for (int i = 0; i < temp.length; i++) {
infoList[i] = (Map<String, Object>) temp[i];
}
}
}
}
| 378 |
678 |
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport
*/
#import <OfficeImport/EMSheetMapper.h>
#import <OfficeImport/EMWorksheetMapper.h>
#import <OfficeImport/OfficeImport-Structs.h>
@class ECColumnWidthConvertor, CMStyle, EDWorksheet;
__attribute__((visibility("hidden")))
@interface EMWorksheetMapper : EMSheetMapper {
@private
EDWorksheet *edWorksheet; // 8 = 0x8
CMStyle *mStyle; // 12 = 0xc
int mMaxPopulatedColumn; // 16 = 0x10
int mMaxPopulatedRow; // 20 = 0x14
double *mColumnGrid; // 24 = 0x18
double *mRowGrid; // 28 = 0x1c
int mWidth; // 32 = 0x20
int mHeight; // 36 = 0x24
ECColumnWidthConvertor *mColumnWidthConvertor; // 40 = 0x28
}
- (id)initWithEDWorksheet:(id)edworksheet parent:(id)parent; // 0xf82a1
- (void)_initWithState:(id)state; // 0xf8849
- (void)dealloc; // 0xffcd5
- (BOOL)isVisible; // 0xf9a9d
- (double *)columnGrid; // 0xfa2ad
- (int)columnCount; // 0xfa2bd
- (double *)rowGrid; // 0x10609d
- (int)maxRowNumber; // 0x106a91
- (double)defaultRowHeight; // 0x176b71
- (double)xlColumnWidthToPoints:(double)points; // 0x176b55
- (double)defaultColumnWidth; // 0x176b15
- (int)width; // 0xffa95
- (int)height; // 0xffaa5
- (void)mapAt:(id)at withState:(id)state; // 0xf9731
- (id)columnWidthConvertor; // 0xf8ff9
- (int)preprocessWidthWithState:(id)state; // 0xf84b9
- (int)preprocessHeightWithState:(id)state; // 0xf91bd
- (CGSize)preprocessDrawableSizeWithState:(id)state; // 0xf92dd
- (CGSize)preprocessSizeWithState:(id)state; // 0xf836d
@end
@interface EMWorksheetMapper (Private)
- (void)setRowGrid; // 0xf8d51
- (void)countRowsAndColumnsWithState:(id)state; // 0xf88d9
- (void)mapColumnInfosAt:(id)at withState:(id)state; // 0xf9b21
- (void)mapGridAt:(id)at; // 0xfa141
- (void)mapDrawablesAt:(id)at withState:(id)state; // 0xff96d
- (void)mapTableAt:(id)at withState:(id)state; // 0xf97d5
- (void)mapTableStyleAt:(id)at withState:(id)state; // 0xff78d
@end
| 827 |
1,700 |
<gh_stars>1000+
#include "version.h"
#if FF_API_AUDIOCONVERT
#include "channel_layout.h"
#endif
| 43 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.