text:
namespace cel {

class ValueFactory;

// StructValue represents an instance of cel::StructType.
class StructValue : public Value {
 public:
  static constexpr Kind kKind = Kind::kStruct;

  static bool Is(const Value& value) { return value.kind() == kKind; }

  using FieldId = StructType::FieldId;

  static absl::StatusOr<Persistent<StructValue>> New(
      const Persistent<const StructType>& struct_type,
      ValueFactory& value_factory);

  constexpr Kind kind() const { return kKind; }

  Persistent<const StructType> type() const;

  std::string DebugString() const;

  void HashValue(absl::HashState state) const;

  bool Equals(const Value& other) const;

  absl::Status SetField(FieldId field, const Persistent<const Value>& value);

  absl::StatusOr<Persistent<const Value>> GetField(ValueFactory& value_factory,
                                                   FieldId field) const;

  absl::StatusOr<bool> HasField(FieldId field) const;

 protected:
  absl::Status SetFieldByName(absl::string_view name,
                              const Persistent<const Value>& value);

  absl::Status SetFieldByNumber(int64_t number,
                                const Persistent<const Value>& value);

  absl::StatusOr<Persistent<const Value>> GetFieldByName(
      ValueFactory& value_factory, absl::string_view name) const;

  absl::StatusOr<Persistent<const Value>> GetFieldByNumber(
      ValueFactory& value_factory, int64_t number) const;

  absl::StatusOr<bool> HasFieldByName(absl::string_view name) const;

  absl::StatusOr<bool> HasFieldByNumber(int64_t number) const;

 private:
  struct SetFieldVisitor;
  struct GetFieldVisitor;
  struct HasFieldVisitor;

  friend struct SetFieldVisitor;
  friend struct GetFieldVisitor;
  friend struct HasFieldVisitor;
  friend internal::TypeInfo base_internal::GetStructValueTypeId(
      const StructValue& struct_value);
  friend class base_internal::PersistentValueHandle;
  friend class base_internal::LegacyStructValue;
  friend class base_internal::AbstractStructValue;

  StructValue() = default;

  // Called by base_internal::ValueHandleBase to implement Is for Transient and
  // Persistent.

  StructValue(const StructValue&) = delete;
  StructValue(StructValue&&) = delete;

  // Called by CEL_IMPLEMENT_STRUCT_VALUE() and Is() to perform type checking.
  internal::TypeInfo TypeId() const;
};

CEL_INTERNAL_VALUE_DECL(StructValue);

namespace base_internal {

// In an ideal world we would just make StructType a heap type. Unfortunately we
// have to deal with our legacy API and we do not want to unncessarily perform
// heap allocations during interop. So we have an inline variant and heap
// variant.

ABSL_ATTRIBUTE_WEAK void MessageValueHash(uintptr_t msg, uintptr_t type_info,
                                          absl::HashState state);
ABSL_ATTRIBUTE_WEAK bool MessageValueEquals(uintptr_t lhs_msg,
                                            uintptr_t lhs_type_info,
                                            const Value& rhs);
ABSL_ATTRIBUTE_WEAK absl::StatusOr<bool> MessageValueHasFieldByNumber(
    uintptr_t msg, uintptr_t type_info, int64_t number);
ABSL_ATTRIBUTE_WEAK absl::StatusOr<bool> MessageValueHasFieldByName(
    uintptr_t msg, uintptr_t type_info, absl::string_view name);
ABSL_ATTRIBUTE_WEAK absl::StatusOr<Persistent<const Value>>
MessageValueGetFieldByNumber(uintptr_t msg, uintptr_t type_info,
                             ValueFactory& value_factory, int64_t number);
ABSL_ATTRIBUTE_WEAK absl::StatusOr<Persistent<const Value>>
MessageValueGetFieldByName(uintptr_t msg, uintptr_t type_info,
                           ValueFactory& value_factory, absl::string_view name);
ABSL_ATTRIBUTE_WEAK absl::Status MessageValueSetFieldByNumber(
    uintptr_t msg, uintptr_t type_info, int64_t number,
    const Persistent<const Value>& value);
ABSL_ATTRIBUTE_WEAK absl::Status MessageValueSetFieldByName(
    uintptr_t msg, uintptr_t type_info, absl::string_view name,
    const Persistent<const Value>& value);

class LegacyStructValue final : public StructValue, public InlineData {
 public:
  static bool Is(const Value& value) {
    return value.kind() == kKind &&
           static_cast<const StructValue&>(value).TypeId() ==
               internal::TypeId<LegacyStructValue>();
  }

  Persistent<const StructType> type() const;

  std::string DebugString() const;

  void HashValue(absl::HashState state) const;

  bool Equals(const Value& other) const;

 protected:
  absl::Status SetFieldByName(absl::string_view name,
                              const Persistent<const Value>& value);

  absl::Status SetFieldByNumber(int64_t number,
                                const Persistent<const Value>& value);

  absl::StatusOr<Persistent<const Value>> GetFieldByName(
      ValueFactory& value_factory, absl::string_view name) const;

  absl::StatusOr<Persistent<const Value>> GetFieldByNumber(
      ValueFactory& value_factory, int64_t number) const;

  absl::StatusOr<bool> HasFieldByName(absl::string_view name) const;

  absl::StatusOr<bool> HasFieldByNumber(int64_t number) const;

 private:
  struct SetFieldVisitor;
  struct GetFieldVisitor;
  struct HasFieldVisitor;

  friend struct SetFieldVisitor;
  friend struct GetFieldVisitor;
  friend struct HasFieldVisitor;
  friend internal::TypeInfo base_internal::GetStructValueTypeId(
      const StructValue& struct_value);
  friend class base_internal::PersistentValueHandle;
  friend class cel::StructValue;

  static constexpr uintptr_t kMetadata =
      base_internal::kStoredInline | base_internal::kTriviallyCopyable |
      base_internal::kTriviallyDestructible |
      (static_cast<uintptr_t>(kKind) << base_internal::kKindShift);

  LegacyStructValue(uintptr_t msg, uintptr_t type_info)
      : StructValue(),
        base_internal::InlineData(kMetadata),
        msg_(msg),
        type_info_(type_info) {}

  // Called by base_internal::ValueHandleBase to implement Is for Transient and
  // Persistent.

  LegacyStructValue(const LegacyStructValue&) = delete;
  LegacyStructValue(LegacyStructValue&&) = delete;

  // Called by CEL_IMPLEMENT_STRUCT_VALUE() and Is() to perform type checking.
  internal::TypeInfo TypeId() const {
    return internal::TypeId<LegacyStructValue>();
  }

  // This is a type erased pointer to google::protobuf::Message or google::protobuf::MessageLite, it
  // is tagged.
  uintptr_t msg_;
  // This is a type erased pointer to LegacyTypeInfoProvider.
  uintptr_t type_info_;
};

class AbstractStructValue : public StructValue, public HeapData {
 public:
  static bool Is(const Value& value) {
    return value.kind() == kKind &&
           static_cast<const StructValue&>(value).TypeId() !=
               internal::TypeId<LegacyStructValue>();
  }

  Persistent<const StructType> type() const { return type_; }

  virtual std::string DebugString() const = 0;

  virtual void HashValue(absl::HashState state) const = 0;

  virtual bool Equals(const Value& other) const = 0;

 protected:
  explicit AbstractStructValue(Persistent<const StructType> type);

  virtual absl::Status SetFieldByName(absl::string_view name,
                                      const Persistent<const Value>& value) = 0;

  virtual absl::Status SetFieldByNumber(
      int64_t number, const Persistent<const Value>& value) = 0;

  virtual absl::StatusOr<Persistent<const Value>> GetFieldByName(
      ValueFactory& value_factory, absl::string_view name) const = 0;

  virtual absl::StatusOr<Persistent<const Value>> GetFieldByNumber(
      ValueFactory& value_factory, int64_t number) const = 0;

  virtual absl::StatusOr<bool> HasFieldByName(absl::string_view name) const = 0;

  virtual absl::StatusOr<bool> HasFieldByNumber(int64_t number) const = 0;

 private:
  struct SetFieldVisitor;
  struct GetFieldVisitor;
  struct HasFieldVisitor;

  friend struct SetFieldVisitor;
  friend struct GetFieldVisitor;
  friend struct HasFieldVisitor;
  friend internal::TypeInfo base_internal::GetStructValueTypeId(
      const StructValue& struct_value);
  friend class base_internal::PersistentValueHandle;
  friend class cel::StructValue;

  // Called by base_internal::ValueHandleBase to implement Is for Transient and
  // Persistent.

  AbstractStructValue(const AbstractStructValue&) = delete;
  AbstractStructValue(AbstractStructValue&&) = delete;

  // Called by CEL_IMPLEMENT_STRUCT_VALUE() and Is() to perform type checking.
  virtual internal::TypeInfo TypeId() const = 0;

  const Persistent<const StructType> type_;
};

}  // namespace base_internal

#define CEL_STRUCT_VALUE_CLASS ::cel::base_internal::AbstractStructValue

// CEL_DECLARE_STRUCT_VALUE declares `struct_value` as an struct value. It must
// be part of the class definition of `struct_value`.
//
// class MyStructValue : public CEL_STRUCT_VALUE_CLASS {
//  ...
// private:
//   CEL_DECLARE_STRUCT_VALUE(MyStructValue);
// };
#define CEL_DECLARE_STRUCT_VALUE(struct_value) \
  CEL_INTERNAL_DECLARE_VALUE(Struct, struct_value)

// CEL_IMPLEMENT_STRUCT_VALUE implements `struct_value` as an struct
// value. It must be called after the class definition of `struct_value`.
//
// class MyStructValue : public CEL_STRUCT_VALUE_CLASS {
//  ...
// private:
//   CEL_DECLARE_STRUCT_VALUE(MyStructValue);
// };
//
// CEL_IMPLEMENT_STRUCT_VALUE(MyStructValue);
#define CEL_IMPLEMENT_STRUCT_VALUE(struct_value) \
  CEL_INTERNAL_IMPLEMENT_VALUE(Struct, struct_value)

namespace base_internal {

inline internal::TypeInfo GetStructValueTypeId(
    const StructValue& struct_value) {
  return struct_value.TypeId();
}

}  // namespace base_internal

}  // namespace cel

#endif  // THIRD_PARTY_CEL_CPP_BASE_VALUES_STRUCT_VALUE_H_


text:
'use strict';

module.exports = function(Soorder) {

};

redpajama_set_name: RedPajamaGithub


text:
package com.ardic.android.smartburglaralarm.model;

/**
 * Created by murat on 02.01.2017.
 * {
 "code": null,
 "subCode": null,
 "status": "OK",
 "description": null,
 "data": {
 "deviceId": "5c:f8:a1:14:a2:8d@iotigniteagent",
 "command": "SensorData",
 "data": "[\"53\"]",
 "createDate": 1483354391674,
 "nodeId": "VirtualDemoNode",
 "sensorId": "Temperature",
 "cloudDate": 1483354389854
 },
 "ok": true
 }
 */

public class SensorData {
    private String data;
    private Long createDate;
    private Long cloudDate;

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public Long getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Long createDate) {
        this.createDate = createDate;
    }

    public Long getCloudDate() {
        return cloudDate;
    }

    public void setCloudDate(Long cloudDate) {
        this.cloudDate = cloudDate;
    }
}


text:
package me.nithanim.mmf4j.platform.linux;

import com.sun.jna.Native;
import com.sun.jna.Pointer;
import io.netty.util.CharsetUtil;
import java.io.IOException;
import me.nithanim.mmf4j.MemoryMappingException;
import static me.nithanim.mmf4j.platform.linux.ConstantsLinux.*;

public class Linux {
    public static void main(String[] args) throws IOException {
        String path = "/home/nithanim/testlinux.txt";
        int fd = CLibrary.open(path, O_RDWR | O_CREAT | O_APPEND, 0600);
        if (fd == -1) {
            throw new IOException("Unable to open file \"" + path + "\":" + CLibrary.strerror(Native.getLastError()));
        }

        int size = 20;
        CLibrary.fallocate(fd, 0, 0, size);
        Pointer p = CLibrary.mmap(Pointer.NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        if (Pointer.nativeValue(p) == -1) {
            throw new MemoryMappingException("Unable to map file: " + CLibrary.strerror(Native.getLastError()));
        }
        //p.setInt(0, 3452);
        //System.out.println(p.getInt(0));
        p.write(0, "Hallo".getBytes(CharsetUtil.UTF_8), 0, 5);

        if (CLibrary.munmap(p, size) == -1) {
            throw new MemoryMappingException("Unable to unmap file: " + CLibrary.strerror(Native.getLastError()));
        }

        CLibrary.ftruncate(fd, 5);

        CLibrary.close(fd);
    }
}


text:
#include <vdpau/vdpau.h>

#include "avcodec.h"
#include "internal.h"
#include "hevc_data.h"
#include "hevcdec.h"
#include "hwaccel.h"
#include "vdpau.h"
#include "vdpau_internal.h"

static int vdpau_hevc_start_frame(AVCodecContext *avctx,
                                  const uint8_t *buffer, uint32_t size)
{
    HEVCContext *h = avctx->priv_data;
    HEVCFrame *pic = h->ref;
    struct vdpau_picture_context *pic_ctx = pic->hwaccel_picture_private;

    VdpPictureInfoHEVC *info = &pic_ctx->info.hevc;

    const HEVCSPS *sps = h->ps.sps;
    const HEVCPPS *pps = h->ps.pps;
    const SliceHeader *sh = &h->sh;
    const ScalingList *sl = pps->scaling_list_data_present_flag ?
                            &pps->scaling_list : &sps->scaling_list;

    /* init VdpPictureInfoHEVC */

    /* SPS */
    info->chroma_format_idc = sps->chroma_format_idc;
    info->separate_colour_plane_flag = sps->separate_colour_plane_flag;
    info->pic_width_in_luma_samples = sps->width;
    info->pic_height_in_luma_samples = sps->height;
    info->bit_depth_luma_minus8 = sps->bit_depth - 8;
    info->bit_depth_chroma_minus8 = sps->bit_depth - 8;
    info->log2_max_pic_order_cnt_lsb_minus4 = sps->log2_max_poc_lsb - 4;
    /* Provide the value corresponding to the nuh_temporal_id of the frame
       to be decoded. */
    info->sps_max_dec_pic_buffering_minus1 = sps->temporal_layer[sps->max_sub_layers - 1].max_dec_pic_buffering - 1;
    info->log2_min_luma_coding_block_size_minus3 = sps->log2_min_cb_size - 3;
    info->log2_diff_max_min_luma_coding_block_size = sps->log2_diff_max_min_coding_block_size;
    info->log2_min_transform_block_size_minus2 = sps->log2_min_tb_size - 2;
    info->log2_diff_max_min_transform_block_size = sps->log2_max_trafo_size - sps->log2_min_tb_size;
    info->max_transform_hierarchy_depth_inter = sps->max_transform_hierarchy_depth_inter;
    info->max_transform_hierarchy_depth_intra = sps->max_transform_hierarchy_depth_intra;
    info->scaling_list_enabled_flag = sps->scaling_list_enable_flag;
    /* Scaling lists, in diagonal order, to be used for this frame. */
    for (size_t i = 0; i < 6; i++) {
        for (size_t j = 0; j < 16; j++) {
            /* Scaling List for 4x4 quantization matrix,
               indexed as ScalingList4x4[matrixId][i]. */
            uint8_t pos = 4 * ff_hevc_diag_scan4x4_y[j] + ff_hevc_diag_scan4x4_x[j];
            info->ScalingList4x4[i][j] = sl->sl[0][i][pos];
        }
        for (size_t j = 0; j < 64; j++) {
            uint8_t pos = 8 * ff_hevc_diag_scan8x8_y[j] + ff_hevc_diag_scan8x8_x[j];
            /* Scaling List for 8x8 quantization matrix,
               indexed as ScalingList8x8[matrixId][i]. */
            info->ScalingList8x8[i][j] = sl->sl[1][i][pos];
            /* Scaling List for 16x16 quantization matrix,
               indexed as ScalingList16x16[matrixId][i]. */
            info->ScalingList16x16[i][j] = sl->sl[2][i][pos];
            if (i < 2) {
                /* Scaling List for 32x32 quantization matrix,
                   indexed as ScalingList32x32[matrixId][i]. */
                info->ScalingList32x32[i][j] = sl->sl[3][i * 3][pos];
            }
        }
        /* Scaling List DC Coefficients for 16x16,
           indexed as ScalingListDCCoeff16x16[matrixId]. */
        info->ScalingListDCCoeff16x16[i] = sl->sl_dc[0][i];
        if (i < 2) {
            /* Scaling List DC Coefficients for 32x32,
               indexed as ScalingListDCCoeff32x32[matrixId]. */
            info->ScalingListDCCoeff32x32[i] = sl->sl_dc[1][i * 3];
        }
    }
    info->amp_enabled_flag = sps->amp_enabled_flag;
    info->sample_adaptive_offset_enabled_flag = sps->sao_enabled;
    info->pcm_enabled_flag = sps->pcm_enabled_flag;
    if (info->pcm_enabled_flag) {
        /* Only needs to be set if pcm_enabled_flag is set. Ignored otherwise. */
        info->pcm_sample_bit_depth_luma_minus1 = sps->pcm.bit_depth - 1;
        /* Only needs to be set if pcm_enabled_flag is set. Ignored otherwise. */
        info->pcm_sample_bit_depth_chroma_minus1 = sps->pcm.bit_depth_chroma - 1;
        /* Only needs to be set if pcm_enabled_flag is set. Ignored otherwise. */
        info->log2_min_pcm_luma_coding_block_size_minus3 = sps->pcm.log2_min_pcm_cb_size - 3;
        /* Only needs to be set if pcm_enabled_flag is set. Ignored otherwise. */
        info->log2_diff_max_min_pcm_luma_coding_block_size = sps->pcm.log2_max_pcm_cb_size - sps->pcm.log2_min_pcm_cb_size;
        /* Only needs to be set if pcm_enabled_flag is set. Ignored otherwise. */
        info->pcm_loop_filter_disabled_flag = sps->pcm.loop_filter_disable_flag;
    }
    /* Per spec, when zero, assume short_term_ref_pic_set_sps_flag
       is also zero. */
    info->num_short_term_ref_pic_sets = sps->nb_st_rps;
    info->long_term_ref_pics_present_flag = sps->long_term_ref_pics_present_flag;
    /* Only needed if long_term_ref_pics_present_flag is set. Ignored
       otherwise. */
    info->num_long_term_ref_pics_sps = sps->num_long_term_ref_pics_sps;
    info->sps_temporal_mvp_enabled_flag = sps->sps_temporal_mvp_enabled_flag;
    info->strong_intra_smoothing_enabled_flag = sps->sps_strong_intra_smoothing_enable_flag;

    /* Copy the HEVC Picture Parameter Set bitstream fields. */
    info->dependent_slice_segments_enabled_flag = pps->dependent_slice_segments_enabled_flag;
    info->output_flag_present_flag = pps->output_flag_present_flag;
    info->num_extra_slice_header_bits = pps->num_extra_slice_header_bits;
    info->sign_data_hiding_enabled_flag = pps->sign_data_hiding_flag;
    info->cabac_init_present_flag = pps->cabac_init_present_flag;
    info->num_ref_idx_l0_default_active_minus1 = pps->num_ref_idx_l0_default_active - 1;
    info->num_ref_idx_l1_default_active_minus1 = pps->num_ref_idx_l1_default_active - 1;
    info->init_qp_minus26 = pps->pic_init_qp_minus26;
    info->constrained_intra_pred_flag = pps->constrained_intra_pred_flag;
    info->transform_skip_enabled_flag = pps->transform_skip_enabled_flag;
    info->cu_qp_delta_enabled_flag = pps->cu_qp_delta_enabled_flag;
    /* Only needed if cu_qp_delta_enabled_flag is set. Ignored otherwise. */
    info->diff_cu_qp_delta_depth = pps->diff_cu_qp_delta_depth;
    info->pps_cb_qp_offset = pps->cb_qp_offset;
    info->pps_cr_qp_offset = pps->cr_qp_offset;
    info->pps_slice_chroma_qp_offsets_present_flag = pps->pic_slice_level_chroma_qp_offsets_present_flag;
    info->weighted_pred_flag = pps->weighted_pred_flag;
    info->weighted_bipred_flag = pps->weighted_bipred_flag;
    info->transquant_bypass_enabled_flag = pps->transquant_bypass_enable_flag;
    info->tiles_enabled_flag = pps->tiles_enabled_flag;
    info->entropy_coding_sync_enabled_flag = pps->entropy_coding_sync_enabled_flag;
    if (info->tiles_enabled_flag) {
        /* Only valid if tiles_enabled_flag is set. Ignored otherwise. */
        info->num_tile_columns_minus1 = pps->num_tile_columns - 1;
        /* Only valid if tiles_enabled_flag is set. Ignored otherwise. */
        info->num_tile_rows_minus1 = pps->num_tile_rows - 1;
        /* Only valid if tiles_enabled_flag is set. Ignored otherwise. */
        info->uniform_spacing_flag = pps->uniform_spacing_flag;
        /* Only need to set 0..num_tile_columns_minus1. The struct
           definition reserves up to the maximum of 20. Invalid values are
           ignored. */
        for (ssize_t i = 0; i < pps->num_tile_columns; i++) {
            info->column_width_minus1[i] = pps->column_width[i] - 1;
        }
        /* Only need to set 0..num_tile_rows_minus1. The struct
           definition reserves up to the maximum of 22. Invalid values are
           ignored.*/
        for (ssize_t i = 0; i < pps->num_tile_rows; i++) {
            info->row_height_minus1[i] = pps->row_height[i] - 1;
        }
        /* Only needed if tiles_enabled_flag is set. Invalid values are
           ignored. */
        info->loop_filter_across_tiles_enabled_flag = pps->loop_filter_across_tiles_enabled_flag;
    }
    info->pps_loop_filter_across_slices_enabled_flag = pps->seq_loop_filter_across_slices_enabled_flag;
    info->deblocking_filter_control_present_flag = pps->deblocking_filter_control_present_flag;
    /* Only valid if deblocking_filter_control_present_flag is set. Ignored
       otherwise. */
    info->deblocking_filter_override_enabled_flag = pps->deblocking_filter_override_enabled_flag;
    /* Only valid if deblocking_filter_control_present_flag is set. Ignored
       otherwise. */
    info->pps_deblocking_filter_disabled_flag = pps->disable_dbf;
    /* Only valid if deblocking_filter_control_present_flag is set and
       pps_deblocking_filter_disabled_flag is not set. Ignored otherwise.*/
    info->pps_beta_offset_div2 = pps->beta_offset / 2;
    /* Only valid if deblocking_filter_control_present_flag is set and
       pps_deblocking_filter_disabled_flag is not set. Ignored otherwise. */
    info->pps_tc_offset_div2 = pps->tc_offset / 2;
    info->lists_modification_present_flag = pps->lists_modification_present_flag;
    info->log2_parallel_merge_level_minus2 = pps->log2_parallel_merge_level - 2;
    info->slice_segment_header_extension_present_flag = pps->slice_header_extension_present_flag;

    /* Set to 1 if nal_unit_type is equal to IDR_W_RADL or IDR_N_LP.
       Set to zero otherwise. */
    info->IDRPicFlag = IS_IDR(h);
    /* Set to 1 if nal_unit_type in the range of BLA_W_LP to
       RSV_IRAP_VCL23, inclusive. Set to zero otherwise.*/
    info->RAPPicFlag = IS_IRAP(h);
    /* See section 7.4.7.1 of the specification. */
    info->CurrRpsIdx = sps->nb_st_rps;
    if (sh->short_term_ref_pic_set_sps_flag == 1) {
        for (size_t i = 0; i < sps->nb_st_rps; i++) {
            if (sh->short_term_rps == &sps->st_rps[i]) {
                info->CurrRpsIdx = i;
                break;
            }
        }
    }
    /* See section 7.4.7.2 of the specification. */
    info->NumPocTotalCurr = ff_hevc_frame_nb_refs(h);
    if (sh->short_term_ref_pic_set_sps_flag == 0 && sh->short_term_rps) {
        /* Corresponds to specification field, NumDeltaPocs[RefRpsIdx].
           Only applicable when short_term_ref_pic_set_sps_flag == 0.
           Implementations will ignore this value in other cases. See 7.4.8. */
        info->NumDeltaPocsOfRefRpsIdx = sh->short_term_rps->rps_idx_num_delta_pocs;
    }
    /* Section 7.6.3.1 of the H.265/HEVC Specification defines the syntax of
       the slice_segment_header. This header contains information that
       some VDPAU implementations may choose to skip. The VDPAU API
       requires client applications to track the number of bits used in the
       slice header for structures associated with short term and long term
       reference pictures. First, VDPAU requires the number of bits used by
       the short_term_ref_pic_set array in the slice_segment_header. */
    info->NumShortTermPictureSliceHeaderBits = sh->short_term_ref_pic_set_size;
    /* Second, VDPAU requires the number of bits used for long term reference
       pictures in the slice_segment_header. This is equal to the number
       of bits used for the contents of the block beginning with
       "if(long_term_ref_pics_present_flag)". */
    info->NumLongTermPictureSliceHeaderBits = sh->long_term_ref_pic_set_size;

    /* The value of PicOrderCntVal of the picture in the access unit
       containing the SEI message. The picture being decoded. */
    info->CurrPicOrderCntVal = h->poc;

    /* Slice Decoding Process - Reference Picture Sets */
    for (size_t i = 0; i < 16; i++) {
        info->RefPics[i] = VDP_INVALID_HANDLE;
        info->PicOrderCntVal[i] = 0;
        info->IsLongTerm[i] = 0;
    }
    for (size_t i = 0, j = 0; i < FF_ARRAY_ELEMS(h->DPB); i++) {
        const HEVCFrame *frame = &h->DPB[i];
        if (frame != h->ref && (frame->flags & (HEVC_FRAME_FLAG_LONG_REF |
                                                HEVC_FRAME_FLAG_SHORT_REF))) {
            if (j > 15) {
                av_log(avctx, AV_LOG_WARNING,
                     "VDPAU only supports up to 16 references in the DPB. "
                     "This frame may not be decoded correctly.\n");
                break;
            }
            /* Array of video reference surfaces.
               Set any unused positions to VDP_INVALID_HANDLE. */
            info->RefPics[j] = ff_vdpau_get_surface_id(frame->frame);
            /* Array of picture order counts. These correspond to positions
               in the RefPics array. */
            info->PicOrderCntVal[j] = frame->poc;
            /* Array used to specify whether a particular RefPic is
               a long term reference. A value of "1" indicates a long-term
               reference. */
            // XXX: Setting this caused glitches in the nvidia implementation
            // Always setting it to zero, produces correct results
            //info->IsLongTerm[j] = frame->flags & HEVC_FRAME_FLAG_LONG_REF;
            info->IsLongTerm[j] = 0;
            j++;
        }
    }
    /* Copy of specification field, see Section 8.3.2 of the
       H.265/HEVC Specification. */
    info->NumPocStCurrBefore = h->rps[ST_CURR_BEF].nb_refs;
    if (info->NumPocStCurrBefore > 8) {
        av_log(avctx, AV_LOG_WARNING,
             "VDPAU only supports up to 8 references in StCurrBefore. "
             "This frame may not be decoded correctly.\n");
        info->NumPocStCurrBefore = 8;
    }
    /* Copy of specification field, see Section 8.3.2 of the
       H.265/HEVC Specification. */
    info->NumPocStCurrAfter = h->rps[ST_CURR_AFT].nb_refs;
    if (info->NumPocStCurrAfter > 8) {
        av_log(avctx, AV_LOG_WARNING,
             "VDPAU only supports up to 8 references in StCurrAfter. "
             "This frame may not be decoded correctly.\n");
        info->NumPocStCurrAfter = 8;
    }
    /* Copy of specification field, see Section 8.3.2 of the
       H.265/HEVC Specification. */
    info->NumPocLtCurr = h->rps[LT_CURR].nb_refs;
    if (info->NumPocLtCurr > 8) {
        av_log(avctx, AV_LOG_WARNING,
             "VDPAU only supports up to 8 references in LtCurr. "
             "This frame may not be decoded correctly.\n");
        info->NumPocLtCurr = 8;
    }
    /* Reference Picture Set list, one of the short-term RPS. These
       correspond to positions in the RefPics array. */
    for (ssize_t i = 0, j = 0; i < h->rps[ST_CURR_BEF].nb_refs; i++) {
        HEVCFrame *frame = h->rps[ST_CURR_BEF].ref[i];
        if (frame) {
            uint8_t found = 0;
            uintptr_t id = ff_vdpau_get_surface_id(frame->frame);
            for (size_t k = 0; k < 16; k++) {
                if (id == info->RefPics[k]) {
                    info->RefPicSetStCurrBefore[j] = k;
                    j++;
                    found = 1;
                    break;
                }
            }
            if (!found) {
                av_log(avctx, AV_LOG_WARNING, "missing surface: %p\n",
                       (void *)id);
            }
        } else {
            av_log(avctx, AV_LOG_WARNING, "missing STR Before frame: %zd\n", i);
        }
    }
    /* Reference Picture Set list, one of the short-term RPS. These
       correspond to positions in the RefPics array. */
    for (ssize_t i = 0, j = 0; i < h->rps[ST_CURR_AFT].nb_refs; i++) {
        HEVCFrame *frame = h->rps[ST_CURR_AFT].ref[i];
        if (frame) {
            uint8_t found = 0;
            uintptr_t id = ff_vdpau_get_surface_id(frame->frame);
            for (size_t k = 0; k < 16; k++) {
                if (id == info->RefPics[k]) {
                    info->RefPicSetStCurrAfter[j] = k;
                    j++;
                    found = 1;
                    break;
                }
            }
            if (!found) {
                av_log(avctx, AV_LOG_WARNING, "missing surface: %p\n",
                       (void *)id);
            }
        } else {
            av_log(avctx, AV_LOG_WARNING, "missing STR After frame: %zd\n", i);
        }
    }
    /* Reference Picture Set list, one of the long-term RPS. These
       correspond to positions in the RefPics array. */
    for (ssize_t i = 0, j = 0; i < h->rps[LT_CURR].nb_refs; i++) {
        HEVCFrame *frame = h->rps[LT_CURR].ref[i];
        if (frame) {
            uint8_t found = 0;
            uintptr_t id = ff_vdpau_get_surface_id(frame->frame);
            for (size_t k = 0; k < 16; k++) {
                if (id == info->RefPics[k]) {
                    info->RefPicSetLtCurr[j] = k;
                    j++;
                    found = 1;
                    break;
                }
            }
            if (!found) {
                av_log(avctx, AV_LOG_WARNING, "missing surface: %p\n",
                       (void *)id);
            }
        } else {
            av_log(avctx, AV_LOG_WARNING, "missing LTR frame: %zd\n", i);
        }
    }

    return ff_vdpau_common_start_frame(pic_ctx, buffer, size);
}

static const uint8_t start_code_prefix[3] = { 0x00, 0x00, 0x01 };

static int vdpau_hevc_decode_slice(AVCodecContext *avctx,
                                   const uint8_t *buffer, uint32_t size)
{
    HEVCContext *h = avctx->priv_data;
    struct vdpau_picture_context *pic_ctx = h->ref->hwaccel_picture_private;
    int val;

    val = ff_vdpau_add_buffer(pic_ctx, start_code_prefix, 3);
    if (val)
        return val;

    val = ff_vdpau_add_buffer(pic_ctx, buffer, size);
    if (val)
        return val;

    return 0;
}

static int vdpau_hevc_end_frame(AVCodecContext *avctx)
{
    HEVCContext *h = avctx->priv_data;
    struct vdpau_picture_context *pic_ctx = h->ref->hwaccel_picture_private;
    int val;

    val = ff_vdpau_common_end_frame(avctx, h->ref->frame, pic_ctx);
    if (val < 0)
        return val;

    return 0;
}

static int vdpau_hevc_init(AVCodecContext *avctx)
{
    VdpDecoderProfile profile;
    uint32_t level = avctx->level;

    switch (avctx->profile) {
    case FF_PROFILE_HEVC_MAIN:
        profile = VDP_DECODER_PROFILE_HEVC_MAIN;
        break;
    case FF_PROFILE_HEVC_MAIN_10:
        profile = VDP_DECODER_PROFILE_HEVC_MAIN_10;
        break;
    case FF_PROFILE_HEVC_MAIN_STILL_PICTURE:
        profile = VDP_DECODER_PROFILE_HEVC_MAIN_STILL;
        break;
    default:
        return AVERROR(ENOTSUP);
    }

    return ff_vdpau_common_init(avctx, profile, level);
}

const AVHWAccel ff_hevc_vdpau_hwaccel = {
    .name           = "hevc_vdpau",
    .type           = AVMEDIA_TYPE_VIDEO,
    .id             = AV_CODEC_ID_HEVC,
    .pix_fmt        = AV_PIX_FMT_VDPAU,
    .start_frame    = vdpau_hevc_start_frame,
    .end_frame      = vdpau_hevc_end_frame,
    .decode_slice   = vdpau_hevc_decode_slice,
    .frame_priv_data_size = sizeof(struct vdpau_picture_context),
    .init           = vdpau_hevc_init,
    .uninit         = ff_vdpau_common_uninit,
    .frame_params   = ff_vdpau_common_frame_params,
    .priv_data_size = sizeof(VDPAUContext),
    .caps_internal  = HWACCEL_CAP_ASYNC_SAFE,
};


text:
import React, { Component } from 'react';

import {
  Text,
  View,
  Image,
  TouchableHighlight
} from 'react-native';
import { images, metrics } from '../../theme';
import { Scene, Router, Actions } from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/FontAwesome';
const PremiumHorse = (props) => (
    <TouchableHighlight onPress={() => {
        if (props.action == true) Actions.horseDetail()
    }}>
		  <View style={{flexDirection: 'row', height: 132,
		  marginTop: props.margin,
		  marginBottom: props.margin,
		  borderWidth: 1,
          backgroundColor: '#FFFFFF',
		  borderColor: '#D7D7D7'}}

          >

		    <View style={{flex: 132,}}>
		      <Image style={{height: 132}} source={images.horse1} />
		    </View>
		    <View style={{flex: 199,flexDirection: 'column'}}>
		      <View style={{flex:1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
    			<View style={{flex: 3, width: 20, backgroundColor: 'blue'}}>
    			 <Text style={{color: 'white', fontSize: 11}}>Lot1</Text>
    			</View>
    			<View style={{flex: 97, marginLeft: 5}}>
    			<Text style={{color: 'black', fontWeight: 'bold', fontSize: 16}}>Supercoach</Text>
    			</View>
		      </View>
		      <View style={{flex:1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
    			<View style={{flex: 2, width: 15}}>
    			 <Icon name="map-marker" size={20} color='#AFAFAF'></Icon>
    			</View>
    			<View style={{flex: 98, }}>
    			<Text style={{fontSize: 10, color: '#B9B9B9'}}>PO Box 37, Windsor, NSW, 2756 Australia</Text>
    			</View>
		      </View>
		      <View style={{flex:1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
    			<View style={{flex: 2, width: 15}}>
    			 <Icon name="usd" size={15} color='blue'></Icon>
    			</View>
    			<View style={{flex: 98,}}>
    			<Text style={{color: 'black', fontSize: 18}}>8500</Text>
    			</View>
		      </View>
		      <View style={{flex:1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
    			<View style={{flex: 2, width: 15}}>
    			 <Icon name="gavel" size={12} color='blue'></Icon>
    			</View>
    			<View style={{flex: 98}}>
    			<Text style={{fontSize: 11, color: '#B9B9B9'}}>32</Text>
    			</View>
		      </View>
		      <View style={{flex:1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
    			<View style={{flex: 2, width: 15}}>
    			 <Icon name="clock-o" size={12} color='blue'></Icon>
    			</View>
    			<View style={{flex: 80}}>
    			  <Text style={{fontSize: 11, color: '#B9B9B9'}}>12d 23h 12m 34s</Text>
    			</View>
                <View style={{flex: 18, justifyContent: 'center', alignItems: 'flex-end', paddingRight: 5}}>
                  <Icon name="heart-o" size={20} color='black'></Icon>
                </View>
		      </View>
		    </View>
		    <View style={{flex: 5, justifyContent: 'center', alignItems: 'center',
             backgroundColor: '#FED700', width: 5}}>
              <Text style={{fontSize: 9, fontWeight: 'bold', height: 10, width: 50, color: 'white', transform: [{ rotate: '90deg'}]}}>Premium</Text>
		    </View>

		  </View>
          </TouchableHighlight>
);

export default PremiumHorse;


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("mko.Euklid")]
[assembly: AssemblyDescription("mko.Euklid: Basisklassen wie Punkt und Vektor für Geometrie im euklidischen Raum;")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("www.mkoit.de")]
[assembly: AssemblyProduct("mko.Euklid")]
[assembly: AssemblyCopyright("Copyright ©  Martin Korneffel, Stuttgart 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]

// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("7773cbbb-4177-459c-b6ad-80803cf68609")]

// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
//      Hauptversion
//      Nebenversion
//      Buildnummer
//      Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.1.0")]
[assembly: AssemblyFileVersion("1.1.1.0")]


text:
layout: post
title: "[原创]Oracle12cR2_创建公用用户"
category: Oracle
tags: Oracle 12c CDB common_user
---

* content
{:toc}

[原创]Oracle12cR2_创建公用用户

在CDB模式下,公用用户(Common User)和本地用户(Local User)两个概念被引入进来,

公用用户可以在CDB和PDB中同时存在,能够连接ROOT和PDB进行操作;而本地用户则只在特定的PDB中存在,也只能在特定的PDB中执行操作;

在PDB中不能创建公用用户,而在CDB中(CDB$ROOT中)同样不能创建本地用户。

创建公有用户,公有用户名必须是以C##或者c##(大小写C和两个#)开头的用户名,但这前缀是可以更改的,通过 common_user_prefix 参数控制。

默认的前缀名称如下所示,默认CDB中,common_user_prefix 的值是 C##。

	SQL> show con_name

	CON_NAME
	------------------------------
	CDB$ROOT
	SQL> show parameter COMMON_USER_PREFIX

	NAME                                 TYPE        VALUE
	------------------------------------ ----------- ------------------------------
	common_user_prefix                   string      C##
	SQL>

演示创建一个 c##lyn 的用户,之后需要赋予相应的权限,另外需要注意使用grant语句中的container指定容器。

	SQL> show user;
	USER is "SYS"
	SQL> create user c##lyn identified by oracle;

	User created.

	SQL> show pdbs

		CON_ID CON_NAME                       OPEN MODE  RESTRICTED
	---------- ------------------------------ ---------- ----------
			 2 PDB$SEED                       READ ONLY  NO
			 3 PDB1                           READ WRITE NO
			 4 PDB3                           READ WRITE NO
			 5 PDB2                           READ ONLY  NO
	SQL>
	SQL> grant connect,resource to c##lyn;

	Grant succeeded.

	SQL> conn c##lyn/oracle@pdb1;
	ERROR:
	ORA-01045: user C##LYN lacks CREATE SESSION privilege; logon denied

	Warning: You are no longer connected to ORACLE.
	SQL> conn / as sysdba
	Connected.
	SQL> grant connect,resource to c##lyn container=all;

	Grant succeeded.

	SQL> conn c##lyn/oracle@pdb1;
	Connected.
	SQL>

当创建公用用户时,Oracle会向每个PDB中同时创建该用户,如果PDB未打开,则创建工作会以任务的方式延后。

如下所示,pdb2是read only状态,所以创建c##lyn用户时候,对pdb2是没有创建成功的。

	SQL> show con_name

	CON_NAME
	------------------------------
	CDB$ROOT
	SQL> show pdbs;

		CON_ID CON_NAME                       OPEN MODE  RESTRICTED
	---------- ------------------------------ ---------- ----------
			 2 PDB$SEED                       READ ONLY  NO
			 3 PDB1                           READ WRITE NO
			 4 PDB3                           READ WRITE NO
			 5 PDB2                           READ ONLY  NO
	SQL>
	SQL> conn c##lyn/oracle@pdb1;
	Connected.
	SQL> conn c##lyn/oracle@pdb3;
	Connected.
	SQL> conn c##lyn/oracle@pdb2;
	ERROR:
	ORA-01017: invalid username/password; logon denied

	Warning: You are no longer connected to ORACLE.
	SQL>

通过重启pdb2,之后可以用c##lyn的公共用户连接了。

	SQL> conn / as sysdba
	Connected.
	SQL>
	SQL> alter pluggable database pdb2 close immediate;

	Pluggable database altered.

	SQL> alter pluggable database pdb2 open;

	Pluggable database altered.

	SQL>
	SQL> conn c##lyn/oracle@pdb2;
	Connected.
	SQL>

从 [[原创]Oracle12cR2_通过控制文件查看cdb的结构](http://www.bigdatalyn.com/2017/09/15/Oracle12cR2_CDB_Controlfile/) 文中,

cdb/pdb数据文件的路径清晰可见。如果要创建的公有用户指定表空间的话,需要每个容器都事前存在,不然会报错。参考如下实验:

	SQL> show con_name

	CON_NAME
	------------------------------
	CDB$ROOT
	SQL> select file_name from dba_data_files;

	FILE_NAME
	------------------------------------------------------------
	/opt/oracle/oradata/PRODCDB/system01.dbf
	/opt/oracle/oradata/PRODCDB/sysaux01.dbf
	/opt/oracle/oradata/PRODCDB/undotbs01.dbf
	/opt/oracle/oradata/PRODCDB/deftbs01.dbf

	SQL> create tablespace users datafile '/opt/oracle/oradata/PRODCDB/user01.dbf' size 100m autoextend on uniform size 1m;

	Tablespace created.

	SQL> select file_name from dba_data_files;

	FILE_NAME
	------------------------------------------------------------
	/opt/oracle/oradata/PRODCDB/system01.dbf
	/opt/oracle/oradata/PRODCDB/sysaux01.dbf
	/opt/oracle/oradata/PRODCDB/undotbs01.dbf
	/opt/oracle/oradata/PRODCDB/deftbs01.dbf
	/opt/oracle/oradata/PRODCDB/user01.dbf

	SQL>
	SQL> create user c##test01 identified by oracle default tablespace users temporary tablespace temp01;
	create user c##test01 identified by oracle default tablespace users temporary tablespace temp01
	*
	ERROR at line 1:
	ORA-00959: tablespace 'TEMP01' does not exist

	SQL> create user c##test01 identified by oracle default tablespace users temporary tablespace TEMPTS1;
	create user c##test01 identified by oracle default tablespace users temporary tablespace TEMPTS1
	*
	ERROR at line 1:
	ORA-65048: error encountered when processing the current DDL statement in pluggable database PDB1
	ORA-00959: tablespace 'USERS' does not exist

	SQL>
	SQL> create user c##user01 identified by oracle default tablespace deftbs temporary tablespace TEMPTS1;

	User created.

	SQL>

> 不仅临时表空间名要注意,指定的表空间需要各个容器都需要存在,不然报: ORA-65048 的错误。

测试链接:

	SQL> grant connect,resource to c##user01;

	Grant succeeded.

	SQL>

上面赋予语句只能练剑PRODCDB,而不能链接pdb,所以赋予公有用户时候,需要注意container参数。参考如下:(container=all 赋予全部pdb相同权限)

	[oracle@databasevm ~]$ sqlplus  c##user01/oracle@127.0.0.1:1521/prodcdb;

	SQL*Plus: Release 12.2.0.1.0 Production on Fri Sep 29 17:56:51 2017

	Copyright (c) 1982, 2016, Oracle.  All rights reserved.

	Connected to:
	Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production

	SQL> conn c##user01/oracle@pdb1;
	ERROR:
	ORA-01045: user C##USER01 lacks CREATE SESSION privilege; logon denied

	Warning: You are no longer connected to ORACLE.
	SQL> conn / as sysdba
	Connected.
	SQL> grant connect,resource to c##user01 container=all;

	Grant succeeded.

	SQL> conn c##user01/oracle@pdb1;
	Connected.
	SQL>

~~~ LinHong 2017/09/15 ~~~~


text:
extern crate clap;

extern crate cursive;

mod instructions;
mod interpreter;

use clap::*;

fn main()
{
  let matches = App::new("brfk")
    .version(crate_version!())
    .author(crate_authors!())
    .about("A Brainfuck Interpreter, Compiler, Debugger, and Optimizer.\n\
           Currently only has a working interpreter, and only supports basic \
           and Extended Type I Brainfuck.")
    .arg(Arg::with_name("file")
         .short("p").long("path").value_name("FILE")
         .help("The path to the Brainfuck source code")
         .required(true).takes_value(true))
    .arg(Arg::with_name("mode")
         .long("mode")
         .value_name("MODE")
         .takes_value(true)
         .require_equals(true)
         .possible_values(&["b", "x1"])//, "x2", "x3", "bp"])
         .hide_possible_values(true)
         .help("The mode that the Brainfuck code should be parsed in.\n\
               b     Basic mode (Default)\n\
               x1    Extended Type I mode"))//\n\
//               x2    Extended Type II mode\n\
//               x3    Extended Type III mode\n\
//               bp    BrainPlus mode"))
//    .arg(Arg::with_name("ext")
//         .short("e").long("extensions")
//         .help("Enables brfk specific extensions"))
    .setting(AppSettings::ColoredHelp)
    .get_matches();

  let file = matches.value_of("file").unwrap();
  let mode = match matches.value_of("mode").unwrap_or("b")
  {
    "b"  => instructions::ParseMode::Basic,
    "x1" => instructions::ParseMode::Extended1,
    "x2" => instructions::ParseMode::Extended2,
    "x3" => instructions::ParseMode::Extended3,
    "bp" => instructions::ParseMode::BrainPlus,
    err  => panic!("Invalid mode: {}", err)
  };
  let enable_extensions = matches.is_present("ext");
  let mut program = interpreter::Program::new(
                      instructions::parse_code(
                        read_file(std::path::Path::new(file)),
                        mode, enable_extensions).unwrap());

  program.run();
}

fn read_file(file_path: &std::path::Path) -> String
{
  use std::io::Read;

  let mut file = std::fs::File::open(file_path)
    .expect(&format!("File not found: {}", file_path.to_str().unwrap()));

  let mut file_contents = String::new();
  file.read_to_string(&mut file_contents).expect("Could not read file");
  file_contents
}


text:
/**
 * 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 com.sun.org.apache.xpath.internal.functions;

import com.sun.org.apache.xml.internal.dtm.DTM;
import com.sun.org.apache.xml.internal.utils.QName;
import com.sun.org.apache.xpath.internal.NodeSetDTM;
import com.sun.org.apache.xpath.internal.XPathContext;
import com.sun.org.apache.xpath.internal.objects.XNodeSet;
import com.sun.org.apache.xpath.internal.objects.XObject;
import com.sun.org.apache.xpath.internal.res.XPATHErrorResources;
import java.util.List;
import javax.xml.transform.TransformerException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**
 * Execute the XML Signature here() function.
 *
 * @LastModified: Oct 2017
 */
public final class FuncHere extends Function {

    private static final long serialVersionUID = 4328660760070034592L;

    @Override
    public XObject execute(XPathContext xctxt) throws TransformerException {
        Node xpathOwnerNode = (Node)xctxt.getOwnerObject();
        if (xpathOwnerNode == null) {
            return null;
        }

        int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode);
        int currentNode = xctxt.getCurrentNode();
        DTM dtm = xctxt.getDTM(currentNode);
        int docContext = dtm.getDocument();

        if (docContext == DTM.NULL) {
            error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null);
        }

        // check whether currentNode and the node containing the XPath
        // expression are in the same document
        Document currentDoc = getOwnerDocument(dtm.getNode(currentNode));
        Document xpathOwnerDoc = getOwnerDocument(xpathOwnerNode);

        if (currentDoc != xpathOwnerDoc) {
            throw new TransformerException("Owner documents differ");
        }

        XNodeSet nodes = new XNodeSet(xctxt.getDTMManager());
        NodeSetDTM nodeSet = nodes.mutableNodeset();

        int hereNode = DTM.NULL;

        switch (dtm.getNodeType(xpathOwnerNodeDTM)) {

            case Node.ATTRIBUTE_NODE:
            case Node.PROCESSING_INSTRUCTION_NODE: {
                // returns a node-set containing the attribute /  processing
                // instruction node
                hereNode = xpathOwnerNodeDTM;
                nodeSet.addNode(hereNode);
                break;
            }
            case Node.TEXT_NODE : {
                // returns a node-set containing the parent element of the
                // text node that directly bears the XPath expression
                hereNode = dtm.getParent(xpathOwnerNodeDTM);
                nodeSet.addNode(hereNode);
                break;
            }
            default :
                break;
        }

        /** $todo$ Do I have to do this detach() call? */
        nodeSet.detach();

        return nodes;
    }

    private static Document getOwnerDocument(Node node) {
        if (node.getNodeType() == Node.DOCUMENT_NODE) {
            return (Document)node;
        }
        return node.getOwnerDocument();
    }

    @Override
    public void fixupVariables(List<QName> vars, int globalsSize) { }
}


text:
local PrintablePos =
{
   __tostring = function(pos)
      return "(" .. pos.x .. ", " .. pos.y .. ", " .. pos.z .. ")";
   end
};
function PrintablePos:new(pos)
   return setmetatable(pos, self);
end

local PlayerEnv =
{
   playerContexts = setmetatable({}, { __mode = "k" }),  -- weak keys

   playerFuncs =
      {
         me = function(player)
            return player;
         end,

         myname = function(player)
            return player:get_player_name();
         end,

         here = function(player)
            return PrintablePos:new(player:getpos());
         end,

         print = function(player)
            return function(...)
               local str = "";
               for _, arg in ipairs({...}) do
                  str = str .. tostring(arg);
               end
               minetest.chat_send_player(player:get_player_name(), str, false);
            end
         end
      };
};

function PlayerEnv:new(player)
   local env = {};
   self.playerContexts[env] = player;
   setmetatable(env, self);
   return env;
end
setmetatable(PlayerEnv, { __call = PlayerEnv.new });

function PlayerEnv.__index(env, key)
   local playerFunc = PlayerEnv.playerFuncs[key];
   if playerFunc then
      local player = PlayerEnv.playerContexts[env];
      return playerFunc(player);
   else
      return _G[key];
   end
end

function PlayerEnv.__newindex(env, key, value)
   if PlayerEnv.playerFuncs[key] then
      error("cannot set special '"..key.."' player variable");
   end
   rawset(env, key, value);
end

return PlayerEnv;


text:
<?php

namespace Sylius\Bundle\CoreBundle\Model;

use SplFileInfo;
use Sylius\Bundle\ResourceBundle\Model\TimestampableInterface;

interface ImageInterface extends TimestampableInterface
{
    public function getId();
    public function hasFile();
    public function getFile();
    public function setFile(SplFileInfo $file);
    public function getPath();
    public function setPath($path);
}


text:
RSpec.describe RuboCop::Cop::Style::CommandLiteral, :config do
  subject(:cop) { described_class.new(config) }

  let(:config) do
    supported_styles = {
      'SupportedStyles' => %w[backticks percent_x mixed]
    }
    RuboCop::Config.new('Style/PercentLiteralDelimiters' =>
                          percent_literal_delimiters_config,
                        'Style/CommandLiteral' =>
                          cop_config.merge(supported_styles))
  end
  let(:percent_literal_delimiters_config) do
    { 'PreferredDelimiters' => { '%x' => '()' } }
  end

  describe '%x commands with other delimiters than parentheses' do
    let(:cop_config) { { 'EnforcedStyle' => 'backticks' } }

    it 'registers an offense' do
      expect_offense(<<~RUBY)
        %x$ls$
        ^^^^^^ Use backticks around command string.
      RUBY
    end
  end

  describe 'when PercentLiteralDelimiters is configured with curly braces' do
    let(:cop_config) { { 'EnforcedStyle' => 'percent_x' } }
    let(:percent_literal_delimiters_config) do
      { 'PreferredDelimiters' => { '%x' => '[]' } }
    end

    it 'respects the configuration when auto-correcting' do
      new_source = autocorrect_source('`ls`')
      expect(new_source).to eq('%x[ls]')
    end
  end

  describe 'when PercentLiteralDelimiters only has a default' do
    let(:cop_config) { { 'EnforcedStyle' => 'percent_x' } }
    let(:percent_literal_delimiters_config) do
      { 'PreferredDelimiters' => { 'default' => '()' } }
    end

    it 'respects the configuration when auto-correcting' do
      new_source = autocorrect_source('`ls`')
      expect(new_source).to eq('%x(ls)')
    end
  end

  describe 'when PercentLiteralDelimiters is configured and a default exists' do
    let(:cop_config) { { 'EnforcedStyle' => 'percent_x' } }
    let(:percent_literal_delimiters_config) do
      { 'PreferredDelimiters' => { '%x' => '[]', 'default' => '()' } }
    end

    it 'ignores the default when auto-correcting and' do
      new_source = autocorrect_source('`ls`')
      expect(new_source).to eq('%x[ls]')
    end
  end

  describe 'heredoc commands' do
    let(:cop_config) { { 'EnforcedStyle' => 'backticks' } }

    it 'is ignored' do
      expect_no_offenses(<<~RUBY)
        <<`COMMAND`
          ls
        COMMAND
      RUBY
    end
  end

  context 'when EnforcedStyle is set to backticks' do
    let(:cop_config) { { 'EnforcedStyle' => 'backticks' } }

    describe 'a single-line ` string without backticks' do
      it 'is accepted' do
        expect_no_offenses('foo = `ls`')
      end
    end

    describe 'a single-line ` string with backticks' do
      let(:source) { 'foo = `echo \`ls\``' }

      it 'registers an offense' do
        expect_offense(<<-'RUBY'.strip_indent)
          foo = `echo \`ls\``
                ^^^^^^^^^^^^^ Use `%x` around command string.
        RUBY
      end

      it 'cannot auto-correct' do
        new_source = autocorrect_source(source)
        expect(new_source).to eq(source)
      end

      describe 'when configured to allow inner backticks' do
        before { cop_config['AllowInnerBackticks'] = true }

        it 'is accepted' do
          expect_no_offenses('foo = `echo \\`ls\\``')
        end
      end
    end

    describe 'a multi-line ` string without backticks' do
      it 'is accepted' do
        expect_no_offenses(<<~RUBY)
          foo = `
            ls
            ls -l
          `
        RUBY
      end
    end

    describe 'a multi-line ` string with backticks' do
      let(:source) do
        <<~RUBY
          foo = `
            echo \`ls\`
            echo \`ls -l\`
          `
        RUBY
      end

      it 'registers an offense' do
        expect_offense(<<-'RUBY'.strip_indent)
          foo = `
                ^ Use `%x` around command string.
            echo \`ls\`
            echo \`ls -l\`
          `
        RUBY
      end

      it 'cannot auto-correct' do
        new_source = autocorrect_source(source)
        expect(new_source).to eq(source)
      end

      describe 'when configured to allow inner backticks' do
        before { cop_config['AllowInnerBackticks'] = true }

        it 'is accepted' do
          expect_no_offenses(<<-'RUBY'.strip_indent)
            foo = `
              echo \`ls\`
              echo \`ls -l\`
            `
          RUBY
        end
      end
    end

    describe 'a single-line %x string without backticks' do
      let(:source) { 'foo = %x(ls)' }

      it 'registers an offense' do
        expect_offense(<<~RUBY)
          foo = %x(ls)
                ^^^^^^ Use backticks around command string.
        RUBY
      end

      it 'auto-corrects' do
        new_source = autocorrect_source(source)
        expect(new_source).to eq('foo = `ls`')
      end
    end

    describe 'a single-line %x string with backticks' do
      let(:source) { 'foo = %x(echo `ls`)' }

      it 'is accepted' do
        expect_no_offenses('foo = %x(echo `ls`)')
      end

      describe 'when configured to allow inner backticks' do
        before { cop_config['AllowInnerBackticks'] = true }

        it 'registers an offense' do
          expect_offense(<<~RUBY)
            foo = %x(echo `ls`)
                  ^^^^^^^^^^^^^ Use backticks around command string.
          RUBY
        end

        it 'cannot auto-correct' do
          new_source = autocorrect_source(source)
          expect(new_source).to eq(source)
        end
      end
    end

    describe 'a multi-line %x string without backticks' do
      let(:source) do
        <<~RUBY
          foo = %x(
            ls
            ls -l
          )
        RUBY
      end

      it 'registers an offense' do
        expect_offense(<<~RUBY)
          foo = %x(
                ^^^ Use backticks around command string.
            ls
            ls -l
          )
        RUBY
      end

      it 'auto-corrects' do
        new_source = autocorrect_source(source)
        expect(new_source).to eq(<<~RUBY)
          foo = `
            ls
            ls -l
          `
        RUBY
      end
    end

    describe 'a multi-line %x string with backticks' do
      let(:source) do
        <<~RUBY
          foo = %x(
            echo `ls`
            echo `ls -l`
          )
        RUBY
      end

      it 'is accepted' do
        expect_no_offenses(<<~RUBY)
          foo = %x(
            echo `ls`
            echo `ls -l`
          )
        RUBY
      end

      describe 'when configured to allow inner backticks' do
        before { cop_config['AllowInnerBackticks'] = true }

        it 'registers an offense' do
          expect_offense(<<~RUBY)
            foo = %x(
                  ^^^ Use backticks around command string.
              echo `ls`
              echo `ls -l`
            )
          RUBY
        end

        it 'cannot auto-correct' do
          new_source = autocorrect_source(source)
          expect(new_source).to eq(source)
        end
      end
    end
  end

  context 'when EnforcedStyle is set to percent_x' do
    let(:cop_config) { { 'EnforcedStyle' => 'percent_x' } }

    describe 'a single-line ` string without backticks' do
      let(:source) { 'foo = `ls`' }

      it 'registers an offense' do
        expect_offense(<<~RUBY)
          foo = `ls`
                ^^^^ Use `%x` around command string.
        RUBY
      end

      it 'auto-corrects' do
        new_source = autocorrect_source(source)
        expect(new_source).to eq('foo = %x(ls)')
      end
    end

    describe 'a single-line ` string with backticks' do
      let(:source) { 'foo = `echo \`ls\``' }

      it 'registers an offense' do
        expect_offense(<<-'RUBY'.strip_indent)
          foo = `echo \`ls\``
                ^^^^^^^^^^^^^ Use `%x` around command string.
        RUBY
      end

      it 'cannot auto-correct' do
        new_source = autocorrect_source(source)
        expect(new_source).to eq(source)
      end
    end

    describe 'a multi-line ` string without backticks' do
      let(:source) do
        <<~RUBY
          foo = `
            ls
            ls -l
          `
        RUBY
      end

      it 'registers an offense' do
        expect_offense(<<-'RUBY'.strip_indent)
          foo = `
                ^ Use `%x` around command string.
            ls
            ls -l
          `
        RUBY
      end

      it 'auto-corrects' do
        new_source = autocorrect_source(source)
        expect(new_source).to eq(<<~RUBY)
          foo = %x(
            ls
            ls -l
          )
        RUBY
      end
    end

    describe 'a multi-line ` string with backticks' do
      let(:source) do
        <<-'RUBY'.strip_indent
          foo = `
            echo \`ls\`
            echo \`ls -l\`
          `
        RUBY
      end

      it 'registers an offense' do
        expect_offense(<<-'RUBY'.strip_indent)
          foo = `
                ^ Use `%x` around command string.
            echo \`ls\`
            echo \`ls -l\`
          `
        RUBY
      end

      it 'cannot auto-correct' do
        new_source = autocorrect_source(source)
        expect(new_source).to eq(source)
      end
    end

    describe 'a single-line %x string without backticks' do
      it 'is accepted' do
        expect_no_offenses('foo = %x(ls)')
      end
    end

    describe 'a single-line %x string with backticks' do
      it 'is accepted' do
        expect_no_offenses('foo = %x(echo `ls`)')
      end
    end

    describe 'a multi-line %x string without backticks' do
      it 'is accepted' do
        expect_no_offenses(<<~RUBY)
          foo = %x(
            ls
            ls -l
          )
        RUBY
      end
    end

    describe 'a multi-line %x string with backticks' do
      it 'is accepted' do
        expect_no_offenses(<<~RUBY)
          foo = %x(
            echo `ls`
            echo `ls -l`
          )
        RUBY
      end
    end
  end

  context 'when EnforcedStyle is set to mixed' do
    let(:cop_config) { { 'EnforcedStyle' => 'mixed' } }

    describe 'a single-line ` string without backticks' do
      it 'is accepted' do
        expect_no_offenses('foo = `ls`')
      end
    end

    describe 'a single-line ` string with backticks' do
      let(:source) { 'foo = `echo \`ls\``' }

      it 'registers an offense' do
        expect_offense(<<-'RUBY'.strip_indent)
          foo = `echo \`ls\``
                ^^^^^^^^^^^^^ Use `%x` around command string.
        RUBY
      end

      it 'cannot auto-correct' do
        new_source = autocorrect_source(source)
        expect(new_source).to eq(source)
      end

      describe 'when configured to allow inner backticks' do
        before { cop_config['AllowInnerBackticks'] = true }

        it 'is accepted' do
          expect_no_offenses('foo = `echo \\`ls\\``')
        end
      end
    end

    describe 'a multi-line ` string without backticks' do
      let(:source) do
        <<-'RUBY'.strip_indent
          foo = `
            ls
            ls -l
          `
        RUBY
      end

      it 'registers an offense' do
        expect_offense(<<~RUBY)
          foo = `
                ^ Use `%x` around command string.
            ls
            ls -l
          `
        RUBY
      end

      it 'auto-corrects' do
        new_source = autocorrect_source(source)
        expect(new_source).to eq(<<~RUBY)
          foo = %x(
            ls
            ls -l
          )
        RUBY
      end
    end

    describe 'a multi-line ` string with backticks' do
      let(:source) do
        <<-'RUBY'.strip_indent
          foo = `
            echo \`ls\`
            echo \`ls -l\`
          `
        RUBY
      end

      it 'registers an offense' do
        expect_offense(<<-'RUBY'.strip_indent)
          foo = `
                ^ Use `%x` around command string.
            echo \`ls\`
            echo \`ls -l\`
          `
        RUBY
      end

      it 'cannot auto-correct' do
        new_source = autocorrect_source(source)
        expect(new_source).to eq(source)
      end
    end

    describe 'a single-line %x string without backticks' do
      let(:source) { 'foo = %x(ls)' }

      it 'registers an offense' do
        expect_offense(<<~RUBY)
          foo = %x(ls)
                ^^^^^^ Use backticks around command string.
        RUBY
      end

      it 'auto-corrects' do
        new_source = autocorrect_source(source)
        expect(new_source).to eq('foo = `ls`')
      end
    end

    describe 'a single-line %x string with backticks' do
      let(:source) { 'foo = %x(echo `ls`)' }

      it 'is accepted' do
        expect_no_offenses('foo = %x(echo `ls`)')
      end

      describe 'when configured to allow inner backticks' do
        before { cop_config['AllowInnerBackticks'] = true }

        it 'registers an offense' do
          expect_offense(<<~RUBY)
            foo = %x(echo `ls`)
                  ^^^^^^^^^^^^^ Use backticks around command string.
          RUBY
        end

        it 'cannot auto-correct' do
          new_source = autocorrect_source(source)
          expect(new_source).to eq(source)
        end
      end
    end

    describe 'a multi-line %x string without backticks' do
      it 'is accepted' do
        expect_no_offenses(<<~RUBY)
          foo = %x(
            ls
            ls -l
          )
        RUBY
      end
    end

    describe 'a multi-line %x string with backticks' do
      it 'is accepted' do
        expect_no_offenses(<<~RUBY)
          foo = %x(
            echo `ls`
            echo `ls -l`
          )
        RUBY
      end
    end
  end
end


text:
package cz.mjanys.web.layout;

import cz.mjanys.web.Constants;

/**
 * @author Martin Janys
 */
public class LayoutConstants extends Constants {

    public static final String LAYOUT_MAPPING = "/layout";

    public static final String PAGE_ADD_PAGE = "/add_page";
    public static final String PAGE_REMOVE_PAGE = "/remove_page";
    public static final String PAGE_EDIT_PAGE = "/edit_page";
    public static final String PAGE_MANAGE_PAGES = "/manage_pages";
    public static final String ACTION_SAVE_PAGE = "/save_page";
    public static final String ACTION_SAVE_ARTICLE = "/save_article";
    public static final String ACTION_DELETE_ARTICLE = "/delete_article";
    public static final String ACTION_ORDER_PAGES = "/order_pages";
    public static final String ACTION_ORDER_ARTICLES = "/order_articles";
    public static final String SERVE_PAGE_TREE = "/serve_page_tree";
    public static final String SERVE_EDIT_ARTICLE = "/serve_edit_article";

    public static final String VIEW_ADD_PAGE = "layout/view_add_page";
    public static final String VIEW_EDIT_PAGE = "layout/view_edit_page";
    public static final String VIEW_MANAGE_PAGES = "layout/view_manage_pages";
    public static final String VIEW_ARTICLE_DIALOG = "article/view_article_dialog";

    public static final String PARAM_PARENT_PAGE = "parentPage";
    public static final String PARAM_ORDER_PAGES = "orderPages";

    public static final String ATTR_CURRENT_PAGE = "currentPage";
    public static final String ATTR_PAGE_PTO = "pagePto";
    public static final String ATTR_PAGE = "page";
    public static final String ATTR_PAGES = "pages";
    public static final String ATTR_PAGE_LAYOUTS = "pageLayouts";
    public static final String ATTR_ARTICLE_LAYOUTS = "articleLayouts";
    public static final String ATTR_ROOT_PAGE = "rootPage";
    public static final String ATTR_ARTICLE = "article";
    public static final String ATTR_TREE = "tree";
    public static final String ATTR_ORDER = "order";

    public static final String ARTICLE = "article";
    public static final String ACTION = "action";
}


text:
<?php

namespace Tests;

use Illuminate\Http\Request;
use L5Swagger\Exceptions\L5SwaggerException;
use OpenApi\Analysers\TokenAnalyser;
use OpenApi\Processors\CleanUnmerged;
use Symfony\Component\Yaml\Parser;
use Symfony\Component\Yaml\Yaml;

/**
 * @testdox Generator
 */
class GeneratorTest extends TestCase
{
    /** @test **/
    public function itThrowsExceptionIfDocumentationDirIsNotWritable(): void
    {
        $this->setAnnotationsPath();

        $config = $this->configFactory->documentationConfig();
        $docs = $config['paths']['docs'];

        $this->fileSystem
            ->expects($this->once())
            ->method('exists')
            ->with($docs)
            ->willReturn(true);

        $this->fileSystem
            ->expects($this->once())
            ->method('isWritable')
            ->with($docs)
            ->willReturn(false);

        $this->expectException(L5SwaggerException::class);
        $this->expectExceptionMessage('Documentation storage directory is not writable');

        $this->makeGeneratorWithMockedFileSystem();
        $this->generator->generateDocs();
    }

    /** @test **/
    public function itWillCreateDocumentationDirIfItIsWritable(): void
    {
        $this->setAnnotationsPath();

        $config = $this->configFactory->documentationConfig();
        $docs = $config['paths']['docs'];

        $this->fileSystem
            ->expects($this->exactly(3))
            ->method('exists')
            ->with($docs)
            ->willReturnOnConsecutiveCalls(true, false, true);

        $this->fileSystem
            ->expects($this->once())
            ->method('isWritable')
            ->with($docs)
            ->willReturn(true);

        $this->fileSystem
            ->expects($this->once())
            ->method('makeDirectory')
            ->with($docs);

        mkdir($docs, 0777);

        $this->makeGeneratorWithMockedFileSystem();
        $this->generator->generateDocs();
    }

    /** @test **/
    public function itThrowsExceptionIfDocumentationDirWasNotCreated(): void
    {
        $this->setAnnotationsPath();

        $config = $this->configFactory->documentationConfig();
        $docs = $config['paths']['docs'];

        $this->fileSystem
            ->expects($this->exactly(3))
            ->method('exists')
            ->with($docs)
            ->willReturnOnConsecutiveCalls(true, false, false);

        $this->fileSystem
            ->expects($this->once())
            ->method('isWritable')
            ->with($docs)
            ->willReturn(true);

        $this->fileSystem
            ->expects($this->once())
            ->method('makeDirectory')
            ->with($docs);

        $this->expectException(L5SwaggerException::class);
        $this->expectExceptionMessage('Documentation storage directory could not be created');

        $this->makeGeneratorWithMockedFileSystem();
        $this->generator->generateDocs();
    }

    /** @test */
    public function canGenerateApiJsonFile(): void
    {
        $this->setAnnotationsPath();

        $this->generator->generateDocs();

        $this->assertTrue(file_exists($this->jsonDocsFile()));
        $this->assertTrue(file_exists($this->yamlDocsFile()));

        $this->get(route('l5-swagger.default.docs'))
            ->assertSee('L5 Swagger')
            ->assertSee('my-default-host.com')
            ->assertSee('getProjectsList')
            ->assertSee('getProductsList')
            ->assertSee('getClientsList')
            ->assertStatus(200);

        $config = $this->configFactory->documentationConfig();
        $jsonFile = $config['paths']['docs_yaml'];
        $this->get(route('l5-swagger.default.docs', ['jsonFile' => $jsonFile]))
            ->assertSee('L5 Swagger')
            ->assertSee('my-default-host.com')
            ->assertSee('getProjectsList')
            ->assertSee('getProductsList')
            ->assertSee('getClientsList')
            ->assertStatus(200);
    }

    /** @test */
    public function canGenerateWithLegacyExcludedDirectories(): void
    {
        $this->setAnnotationsPath();

        $cfg = config('l5-swagger.documentations.default');
        $cfg['paths']['excludes'] = [
            __DIR__.'/storage/annotations/OpenApi/Clients',
        ];
        config(['l5-swagger' => [
            'default' => 'default',
            'documentations' => [
                'default' => $cfg,
            ],
            'defaults' => config('l5-swagger.defaults'),
        ]]);

        $this->generator->generateDocs();

        $this->assertTrue(file_exists($this->jsonDocsFile()));

        $this->get(route('l5-swagger.default.docs'))
            ->assertSee('L5 Swagger')
            ->assertSee('my-default-host.com')
            ->assertSee('getProjectsList')
            ->assertSee('getProductsList')
            ->assertDontSee('getClientsList')
            ->assertStatus(200);
    }

    /** @test */
    public function canGenerateWithScanOptions(): void
    {
        $cfg = config('l5-swagger.documentations.default');

        $cfg['scanOptions']['exclude'] = [
            __DIR__.'/storage/annotations/OpenApi/Clients',
        ];

        $cfg['scanOptions']['pattern'] = 'L5SwaggerAnnotationsExample*.*';
        $cfg['scanOptions']['analyser'] = new TokenAnalyser;
        $cfg['scanOptions']['open_api_spec_version'] = '3.1.0';
        $cfg['scanOptions']['processors'] = [
            new CleanUnmerged,
        ];

        config(['l5-swagger' => [
            'default' => 'default',
            'documentations' => [
                'default' => $cfg,
            ],
            'defaults' => config('l5-swagger.defaults'),
        ]]);

        $this->setAnnotationsPath();

        $this->generator->generateDocs();

        $this->assertTrue(file_exists($this->jsonDocsFile()));

        $response = $this->get(route('l5-swagger.default.docs'));

        $response->assertSee('L5 Swagger')
            ->assertSee('3.1.0')
            ->assertSee('my-default-host.com')
            ->assertSee('getProjectsList')
            ->assertSee('getProductsList')
            ->assertDontSee('getClientsList')
            ->assertStatus(200);
    }

    /** @test */
    public function canGenerateApiJsonFileWithChangedBaseServer(): void
    {
        $this->setAnnotationsPath();

        $cfg = config('l5-swagger.documentations.default');
        $cfg['paths']['base'] = 'https://test-server.url';
        config(['l5-swagger' => [
            'default' => 'default',
            'documentations' => [
                'default' => $cfg,
            ],
            'defaults' => config('l5-swagger.defaults'),
        ]]);

        $this->generator->generateDocs();

        $this->assertTrue(file_exists($this->jsonDocsFile()));

        $this->get(route('l5-swagger.default.docs'))
            ->assertSee('https://test-server.url')
            ->assertSee('https://projects.dev/api/v1')
            ->assertDontSee('basePath')
            ->assertStatus(200);

        $config = $this->configFactory->documentationConfig();
        $jsonFile = $config['paths']['docs_yaml'];
        $this->get(route('l5-swagger.default.docs', ['jsonFile' => $jsonFile]))
            ->assertSee('https://test-server.url')
            ->assertSee('https://projects.dev/api/v1')
            ->assertDontSee('basePath')
            ->assertStatus(200);
    }

    /** @test */
    public function canSetProxy(): void
    {
        $this->setAnnotationsPath();

        $cfg = config('l5-swagger.documentations.default');
        $proxy = '99.56.62.66';
        $cfg['proxy'] = $proxy;
        config(['l5-swagger' => [
            'default' => 'default',
            'documentations' => [
                'default' => $cfg,
            ],
            'defaults' => config('l5-swagger.defaults'),
        ]]);

        $this->get(route('l5-swagger.default.api'))
            ->assertStatus(200);

        $this->assertEquals(Request::getTrustedProxies()[0], $proxy);

        $this->get(route('l5-swagger.default.docs'))
            ->assertStatus(200);

        $this->assertTrue(file_exists($this->jsonDocsFile()));
        $this->assertTrue(file_exists($this->yamlDocsFile()));
    }

    /** @test */
    public function canSetValidatorUrl(): void
    {
        $this->setAnnotationsPath();

        $cfg = config('l5-swagger.documentations.default');
        $cfg['validator_url'] = 'http://validator-url.dev';
        config(['l5-swagger' => [
            'default' => 'default',
            'documentations' => [
                'default' => $cfg,
            ],
            'defaults' => config('l5-swagger.defaults'),
        ]]);

        $this->get(route('l5-swagger.default.api'))
            ->assertSee('validator-url.dev')
            ->assertStatus(200);

        $config = $this->configFactory->documentationConfig();
        $jsonFile = $config['paths']['docs_yaml'];
        $this->get(route('l5-swagger.default.api', ['jsonFile' => $jsonFile]))
            ->assertSee('validator-url.dev')
            ->assertStatus(200);

        $this->get(route('l5-swagger.default.docs'))
            ->assertStatus(200);

        $this->assertTrue(file_exists($this->jsonDocsFile()));
        $this->assertTrue(file_exists($this->yamlDocsFile()));
    }

    /** @test */
    public function canAppropriateYamlType(): void
    {
        $this->setAnnotationsPath();

        $this->generator->generateDocs();

        $objects = (new Parser())->parse(file_get_contents($this->yamlDocsFile()), Yaml::PARSE_OBJECT_FOR_MAP);

        $actual = $objects->paths->{'/projects'}->get->security[0]->api_key_security_example;
        $this->assertIsArray($actual);
    }
}


text:
<?php
namespace test\util\validator;
use metadigit\core\util\validator\ClassParser;

class ClassParserTest extends \PHPUnit\Framework\TestCase {

	function testParse() {
		$metadata = (new ClassParser)->parse('mock\util\validator\Class1');
		$this->assertCount(3, $metadata);
		// check properties constraints
		$props = $metadata['properties'];
		$this->assertArrayHasKey('id', $props);
		$this->assertEquals(['min'=>5, 'max'=>15], $props['id']);
		$this->assertArrayHasKey('active', $props);
		$this->assertEquals(['true'=>true], $props['active']);
		// check null
		$nulls = $metadata['null'];
		$this->assertContains('email2', $nulls);
	}
}


text:
"""
Functions to generate Theano update dictionaries for training.
"""

import numpy as np

import theano
import theano.tensor as T

def sgd(loss, all_params, learning_rate):
    all_grads = theano.grad(loss, all_params)
    updates = []

    for param_i, grad_i in zip(all_params, all_grads):
        updates.append((param_i, param_i - learning_rate * grad_i))

    return updates

def momentum(loss, all_params, learning_rate, momentum=0.9):
    all_grads = theano.grad(loss, all_params)
    updates = []

    for param_i, grad_i in zip(all_params, all_grads):
        mparam_i = theano.shared(np.zeros(param_i.get_value().shape,
                                          dtype=theano.config.floatX))
        v = momentum * mparam_i - learning_rate * grad_i
        updates.append((mparam_i, v))
        updates.append((param_i, param_i + v))

    return updates

# using the alternative formulation of nesterov momentum described at
# https://github.com/lisa-lab/pylearn2/pull/136
# such that the gradient can be evaluated at the current parameters.
def nesterov_momentum(loss, all_params, learning_rate, momentum=0.9):
    all_grads = theano.grad(loss, all_params)
    updates = []

    for param_i, grad_i in zip(all_params, all_grads):
        mparam_i = theano.shared(np.zeros(param_i.get_value().shape,
                                          dtype=theano.config.floatX))
        v = momentum * mparam_i - learning_rate * grad_i  # new momemtum
        w = param_i + momentum * v - learning_rate * grad_i  # new param values
        updates.append((mparam_i, v))
        updates.append((param_i, w))

    return updates

def adagrad(loss, all_params, learning_rate=1.0, epsilon=1e-6):
    """
    epsilon is not included in the typical formula,
    See "Notes on AdaGrad" by Chris Dyer for more info.
    """
    all_grads = theano.grad(loss, all_params)
    all_accumulators = [theano.shared(np.zeros(param.get_value().shape,
                                               dtype=theano.config.floatX))
                        for param in all_params]

    updates = []
    for param_i, grad_i, acc_i in zip(all_params, all_grads, all_accumulators):
        acc_i_new = acc_i + grad_i**2
        updates.append((acc_i, acc_i_new))
        updates.append((param_i, (param_i - learning_rate * grad_i /
                                  T.sqrt(acc_i_new + epsilon))))

    return updates

def rmsprop(loss, all_params, learning_rate=1.0, rho=0.9, epsilon=1e-6):
    """
    epsilon is not included in the description in Hinton's video,
    but to prevent problems with relus repeatedly having 0 gradients,
    it is included here.

    Watch this video for more info: http://www.youtube.com/watch?v=O3sxAc4hxZU
    (formula at 5:20)
    also check http://climin.readthedocs.org/en/latest/rmsprop.html
    """
    all_grads = theano.grad(loss, all_params)
    all_accumulators = [theano.shared(np.zeros(param.get_value().shape,
                                               dtype=theano.config.floatX))
                        for param in all_params]

    updates = []
    for param_i, grad_i, acc_i in zip(all_params, all_grads, all_accumulators):
        acc_i_new = rho * acc_i + (1 - rho) * grad_i**2
        updates.append((acc_i, acc_i_new))
        updates.append((param_i, (param_i - learning_rate * grad_i /
                                  T.sqrt(acc_i_new + epsilon))))

    return updates

def adadelta(loss, all_params, learning_rate=1.0, rho=0.95, epsilon=1e-6):
    """
    in the paper, no learning rate is considered (so learning_rate=1.0).
    Probably best to keep it at this value.
    epsilon is important for the very first update (so the numerator does
    not become 0).

    rho = 0.95 and epsilon=1e-6 are suggested in the paper and reported to
    work for multiple datasets (MNIST, speech).

    see "Adadelta: an adaptive learning rate method" by Matthew Zeiler
    for more info.
    """
    all_grads = theano.grad(loss, all_params)
    all_accumulators = [theano.shared(np.zeros(param.get_value().shape,
                                               dtype=theano.config.floatX))
                        for param in all_params]

    all_delta_accumulators = [
        theano.shared(np.zeros(param.get_value().shape,
                               dtype=theano.config.floatX))
        for param in all_params
    ]

    # all_accumulators: accumulate gradient magnitudes
    # all_delta_accumulators: accumulate update magnitudes (recursive!)

    updates = []
    for param_i, grad_i, acc_i, acc_delta_i in zip(all_params,
                                                   all_grads,
                                                   all_accumulators,
                                                   all_delta_accumulators):
        acc_i_new = rho * acc_i + (1 - rho) * grad_i**2
        updates.append((acc_i, acc_i_new))

        update_i = (grad_i * T.sqrt(acc_delta_i + epsilon) /
                    T.sqrt(acc_i_new + epsilon))  # use the 'old' acc_delta here
        updates.append((param_i, param_i - learning_rate * update_i))

        acc_delta_i_new = rho * acc_delta_i + (1 - rho) * update_i**2
        updates.append((acc_delta_i, acc_delta_i_new))

    return updates

def norm_constraint(tensor_var, max_norm, norm_axes=None, epsilon=1e-7):
    """
    Max weight norm constraints and gradient clipping

    This takes a TensorVariable and rescales it so that incoming weight
    norms are below a specified constraint value. Vectors violating the
    constraint are rescaled so that they are within the allowed range.

    :parameters:
        - tensor_var : TensorVariable
            Theano expression for update, gradient, or other quantity.
        - max_norm : scalar
            This value sets the maximum allowed value of any norm in
            `tensor_var`.
        - norm_axes : sequence (list or tuple)
            The axes over which to compute the norm.  This overrides the
            default norm axes defined for the number of dimensions
            in `tensor_var`. When this is not specified and `tensor_var` is a
            matrix (2D), this is set to `(0,)`. If `tensor_var` is a 3D, 4D or
            5D tensor, it is set to a tuple listing all axes but axis 0. The
            former default is useful for working with dense layers, the latter
            is useful for 1D, 2D and 3D convolutional layers.
            (Optional)
        - epsilon : scalar
            Value used to prevent numerical instability when dividing by
            very small or zero norms.
            (Optional)

    :returns:
        - constrained_output : TensorVariable
            Input `tensor_var` with rescaling applied to weight vectors
            that violate the specified constraints.

    :usage:
        >>> param = theano.shared(
        ...     np.random.randn(100, 200).astype(theano.config.floatX))
        >>> update = param + 100
        >>> update = norm_constraint(update, 10)
        >>> func = theano.function([], [], updates=[(param, update)])
        >>> # Apply constrained update
        >>> _ = func()
        >>> from lasagne.utils import compute_norms
        >>> norms = compute_norms(param.get_value())
        >>> np.isclose(np.max(norms), 10)
        True

    :note:
        When `norm_axes` is not specified, the axes over which the norm is
        computed depend on the dimensionality of the input variable. If it is
        2D, it is assumed to come from a dense layer, and the norm is computed
        over axis 0. If it is 3D, 4D or 5D, it is assumed to come from a
        convolutional layer and the norm is computed over all trailing axes
        beyond axis 0. For other uses, you should explicitly specify the axes
        over which to compute the norm using `norm_axes`.
    """
    ndim = tensor_var.ndim

    if norm_axes is not None:
        sum_over = tuple(norm_axes)
    elif ndim == 2:  # DenseLayer
        sum_over = (0,)
    elif ndim in [3, 4, 5]:  # Conv{1,2,3}DLayer
        sum_over = tuple(range(1, ndim))
    else:
        raise ValueError(
            "Unsupported tensor dimensionality {}."
            "Must specify `norm_axes`".format(ndim)
        )

    dtype = np.dtype(theano.config.floatX).type
    norms = T.sqrt(T.sum(T.sqr(tensor_var), axis=sum_over, keepdims=True))
    target_norms = T.clip(norms, 0, dtype(max_norm))
    constrained_output = \
        (tensor_var * (target_norms / (dtype(epsilon) + norms)))

    return constrained_output


text:
The tracking issue for this feature is: [#70401](https://github.com/rust-lang/rust/issues/70401).

------------------------

The `-Z src-hash-algorithm` compiler flag controls which algorithm is used when hashing each source file. The hash is stored in the debug info and can be used by a debugger to verify the source code matches the executable.

Supported hash algorithms are: `md5`, `sha1`, and `sha256`. Note that not all hash algorithms are supported by all debug info formats.

By default, the compiler chooses the hash algorithm based on the target specification.


text:
package com.silverforge.elasticsearchrawclient.queryDSL.operators;

public enum DistanceTypeOperator {

    SLOPPY_ARC("sloppy_arc"),
    ARC("arc"),
    PLANE("plane");

    private String value;

    DistanceTypeOperator(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return value;
    }
}


text:
package rtypes

import (
	"github.com/robloxapi/types"
)

const T_Variant = "Variant"

const T_Array = "Array"

// Array is a list of types.Values that itself implements types.Value. It
// corresponds to the Array type in Roblox.
type Array []types.Value

// Type returns a string identifying the type of the value.
func (Array) Type() string {
	return T_Array
}

const T_Dictionary = "Dictionary"

// Dictionary is a collection of strings mapping to types.Values, that itself
// implements a types.Value. It corresponds to the Dictionary type in Roblox.
type Dictionary map[string]types.Value

// Type returns a string identifying the type of the value.
func (Dictionary) Type() string {
	return T_Dictionary
}

const T_Tuple = "Tuple"

// Tuple is a sequence of types.Values that itself implements types.Value. It
// corresponds to the Tuple type in Roblox.
type Tuple []types.Value

// Type returns a string identifying the type of the value.
func (Tuple) Type() string {
	return T_Tuple
}

const T_Objects = "Objects"

// Objects is a list of Instances that implements types.Value. It corresponds to
// the Objects type in Roblox.
type Objects []*Instance

// Type returns a string identifying the type of the value.
func (Objects) Type() string {
	return T_Objects
}


text:
package org.jfree.chart.needle.junit;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.jfree.chart.needle.MiddlePinNeedle;

/**
 * Tests for the {@link MiddlePinNeedle} class.
 */
public class MiddlePinNeedleTests extends TestCase {

    /**
     * Returns the tests as a test suite.
     *
     * @return The test suite.
     */
    public static Test suite() {
        return new TestSuite(MiddlePinNeedleTests.class);
    }

    /**
     * Constructs a new set of tests.
     *
     * @param name  the name of the tests.
     */
    public MiddlePinNeedleTests(String name) {
        super(name);
    }

    /**
     * Check that the equals() method can distinguish all fields.
     */
    public void testEquals() {
       MiddlePinNeedle n1 = new MiddlePinNeedle();
       MiddlePinNeedle n2 = new MiddlePinNeedle();
       assertTrue(n1.equals(n2));
       assertTrue(n2.equals(n1));
    }

    /**
     * Check that cloning works.
     */
    public void testCloning() {
        MiddlePinNeedle n1 = new MiddlePinNeedle();
        MiddlePinNeedle n2 = null;
        try {
            n2 = (MiddlePinNeedle) n1.clone();
        }
        catch (CloneNotSupportedException e) {
            e.printStackTrace();
            System.err.println("Failed to clone.");
        }
        assertTrue(n1 != n2);
        assertTrue(n1.getClass() == n2.getClass());
        assertTrue(n1.equals(n2));
    }

    /**
     * Serialize an instance, restore it, and check for equality.
     */
    public void testSerialization() {
        MiddlePinNeedle n1 = new MiddlePinNeedle();
        MiddlePinNeedle n2 = null;
        try {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            ObjectOutput out = new ObjectOutputStream(buffer);
            out.writeObject(n1);
            out.close();
            ObjectInput in = new ObjectInputStream(
                new ByteArrayInputStream(buffer.toByteArray())
            );
            n2 = (MiddlePinNeedle) in.readObject();
            in.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        assertTrue(n1.equals(n2));
    }

}