text:
namespace v8 {
namespace internal {

// ES6 6.1.7.1
enum PropertyAttributes {
  NONE = ::v8::None,
  READ_ONLY = ::v8::ReadOnly,
  DONT_ENUM = ::v8::DontEnum,
  DONT_DELETE = ::v8::DontDelete,

  ALL_ATTRIBUTES_MASK = READ_ONLY | DONT_ENUM | DONT_DELETE,

  SEALED = DONT_DELETE,
  FROZEN = SEALED | READ_ONLY,

  ABSENT = 64,  // Used in runtime to indicate a property is absent.
  // ABSENT can never be stored in or returned from a descriptor's attributes
  // bitfield.  It is only used as a return value meaning the attributes of
  // a non-existent property.
};

enum PropertyFilter {
  ALL_PROPERTIES = 0,
  ONLY_WRITABLE = 1,
  ONLY_ENUMERABLE = 2,
  ONLY_CONFIGURABLE = 4,
  SKIP_STRINGS = 8,
  SKIP_SYMBOLS = 16,
  ONLY_ALL_CAN_READ = 32,
  PRIVATE_NAMES_ONLY = 64,
  ENUMERABLE_STRINGS = ONLY_ENUMERABLE | SKIP_SYMBOLS,
};
// Enable fast comparisons of PropertyAttributes against PropertyFilters.
STATIC_ASSERT(ALL_PROPERTIES == static_cast<PropertyFilter>(NONE));
STATIC_ASSERT(ONLY_WRITABLE == static_cast<PropertyFilter>(READ_ONLY));
STATIC_ASSERT(ONLY_ENUMERABLE == static_cast<PropertyFilter>(DONT_ENUM));
STATIC_ASSERT(ONLY_CONFIGURABLE == static_cast<PropertyFilter>(DONT_DELETE));
STATIC_ASSERT(((SKIP_STRINGS | SKIP_SYMBOLS | ONLY_ALL_CAN_READ) &
               ALL_ATTRIBUTES_MASK) == 0);
STATIC_ASSERT(ALL_PROPERTIES ==
              static_cast<PropertyFilter>(v8::PropertyFilter::ALL_PROPERTIES));
STATIC_ASSERT(ONLY_WRITABLE ==
              static_cast<PropertyFilter>(v8::PropertyFilter::ONLY_WRITABLE));
STATIC_ASSERT(ONLY_ENUMERABLE ==
              static_cast<PropertyFilter>(v8::PropertyFilter::ONLY_ENUMERABLE));
STATIC_ASSERT(ONLY_CONFIGURABLE == static_cast<PropertyFilter>(
                                       v8::PropertyFilter::ONLY_CONFIGURABLE));
STATIC_ASSERT(SKIP_STRINGS ==
              static_cast<PropertyFilter>(v8::PropertyFilter::SKIP_STRINGS));
STATIC_ASSERT(SKIP_SYMBOLS ==
              static_cast<PropertyFilter>(v8::PropertyFilter::SKIP_SYMBOLS));

class Smi;
class TypeInfo;

// Order of kinds is significant.
// Must fit in the BitField PropertyDetails::KindField.
enum PropertyKind { kData = 0, kAccessor = 1 };

// Order of modes is significant.
// Must fit in the BitField PropertyDetails::LocationField.
enum PropertyLocation { kField = 0, kDescriptor = 1 };

// Order of modes is significant.
// Must fit in the BitField PropertyDetails::ConstnessField.
enum class PropertyConstness { kMutable = 0, kConst = 1 };

class Representation {
 public:
  enum Kind { kNone, kSmi, kDouble, kHeapObject, kTagged, kNumRepresentations };

  Representation() : kind_(kNone) {}

  static Representation None() { return Representation(kNone); }
  static Representation Tagged() { return Representation(kTagged); }
  static Representation Smi() { return Representation(kSmi); }
  static Representation Double() { return Representation(kDouble); }
  static Representation HeapObject() { return Representation(kHeapObject); }

  static Representation FromKind(Kind kind) { return Representation(kind); }

  bool Equals(const Representation& other) const {
    return kind_ == other.kind_;
  }

  bool IsCompatibleForLoad(const Representation& other) const {
    return IsDouble() == other.IsDouble();
  }

  bool IsCompatibleForStore(const Representation& other) const {
    return Equals(other);
  }

  bool CanBeInPlaceChangedTo(const Representation& other) const {
    // If it's just a representation generalization case (i.e. property kind and
    // attributes stays unchanged) it's fine to transition from None to anything
    // but double without any modification to the object, because the default
    // uninitialized value for representation None can be overwritten by both
    // smi and tagged values. Doubles, however, would require a box allocation.
    if (IsNone()) return !other.IsDouble();
    if (!FLAG_modify_field_representation_inplace) return false;
    return (IsSmi() || (!FLAG_unbox_double_fields && IsDouble()) ||
            IsHeapObject()) &&
           other.IsTagged();
  }

  // Return the most generic representation that this representation can be
  // changed to in-place. If in-place representation changes are disabled, then
  // this will return the current representation.
  Representation MostGenericInPlaceChange() const {
    if (!FLAG_modify_field_representation_inplace) return *this;
    // Everything but unboxed doubles can be in-place changed to Tagged.
    if (FLAG_unbox_double_fields && IsDouble()) return Representation::Double();
    return Representation::Tagged();
  }

  bool is_more_general_than(const Representation& other) const {
    if (IsHeapObject()) return other.IsNone();
    return kind_ > other.kind_;
  }

  bool fits_into(const Representation& other) const {
    return other.is_more_general_than(*this) || other.Equals(*this);
  }

  Representation generalize(Representation other) {
    if (other.fits_into(*this)) return *this;
    if (other.is_more_general_than(*this)) return other;
    return Representation::Tagged();
  }

  int size() const {
    DCHECK(!IsNone());
    if (IsDouble()) return kDoubleSize;
    DCHECK(IsTagged() || IsSmi() || IsHeapObject());
    return kTaggedSize;
  }

  Kind kind() const { return static_cast<Kind>(kind_); }
  bool IsNone() const { return kind_ == kNone; }
  bool IsTagged() const { return kind_ == kTagged; }
  bool IsSmi() const { return kind_ == kSmi; }
  bool IsSmiOrTagged() const { return IsSmi() || IsTagged(); }
  bool IsDouble() const { return kind_ == kDouble; }
  bool IsHeapObject() const { return kind_ == kHeapObject; }

  const char* Mnemonic() const {
    switch (kind_) {
      case kNone:
        return "v";
      case kTagged:
        return "t";
      case kSmi:
        return "s";
      case kDouble:
        return "d";
      case kHeapObject:
        return "h";
    }
    UNREACHABLE();
  }

 private:
  explicit Representation(Kind k) : kind_(k) {}

  // Make sure kind fits in int8.
  STATIC_ASSERT(kNumRepresentations <= (1 << kBitsPerByte));

  int8_t kind_;
};

static const int kDescriptorIndexBitCount = 10;
static const int kFirstInobjectPropertyOffsetBitCount = 7;
// The maximum number of descriptors we want in a descriptor array.  It should
// fit in a page and also the following should hold:
// kMaxNumberOfDescriptors + kFieldsAdded <= PropertyArray::kMaxLength.
static const int kMaxNumberOfDescriptors = (1 << kDescriptorIndexBitCount) - 4;
static const int kInvalidEnumCacheSentinel =
    (1 << kDescriptorIndexBitCount) - 1;

enum class PropertyCellType {
  // Meaningful when a property cell does not contain the hole.
  kUndefined,     // The PREMONOMORPHIC of property cells.
  kConstant,      // Cell has been assigned only once.
  kConstantType,  // Cell has been assigned only one type.
  kMutable,       // Cell will no longer be tracked as constant.

  // Meaningful when a property cell contains the hole.
  kUninitialized = kUndefined,  // Cell has never been initialized.
  kInvalidated = kConstant,     // Cell has been deleted, invalidated or never
                                // existed.

  // For dictionaries not holding cells.
  kNoCell = kMutable,
};

enum class PropertyCellConstantType {
  kSmi,
  kStableMap,
};

// PropertyDetails captures type and attributes for a property.
// They are used both in property dictionaries and instance descriptors.
class PropertyDetails {
 public:
  // Property details for dictionary mode properties/elements.
  PropertyDetails(PropertyKind kind, PropertyAttributes attributes,
                  PropertyCellType cell_type, int dictionary_index = 0) {
    value_ = KindField::encode(kind) | LocationField::encode(kField) |
             AttributesField::encode(attributes) |
             DictionaryStorageField::encode(dictionary_index) |
             PropertyCellTypeField::encode(cell_type);
  }

  // Property details for fast mode properties.
  PropertyDetails(PropertyKind kind, PropertyAttributes attributes,
                  PropertyLocation location, PropertyConstness constness,
                  Representation representation, int field_index = 0) {
    value_ = KindField::encode(kind) | AttributesField::encode(attributes) |
             LocationField::encode(location) |
             ConstnessField::encode(constness) |
             RepresentationField::encode(EncodeRepresentation(representation)) |
             FieldIndexField::encode(field_index);
  }

  static PropertyDetails Empty(
      PropertyCellType cell_type = PropertyCellType::kNoCell) {
    return PropertyDetails(kData, NONE, cell_type);
  }

  int pointer() const { return DescriptorPointer::decode(value_); }

  PropertyDetails set_pointer(int i) const {
    return PropertyDetails(value_, i);
  }

  PropertyDetails set_cell_type(PropertyCellType type) const {
    PropertyDetails details = *this;
    details.value_ = PropertyCellTypeField::update(details.value_, type);
    return details;
  }

  PropertyDetails set_index(int index) const {
    PropertyDetails details = *this;
    details.value_ = DictionaryStorageField::update(details.value_, index);
    return details;
  }

  PropertyDetails CopyWithRepresentation(Representation representation) const {
    return PropertyDetails(value_, representation);
  }
  PropertyDetails CopyWithConstness(PropertyConstness constness) const {
    return PropertyDetails(value_, constness);
  }
  PropertyDetails CopyAddAttributes(PropertyAttributes new_attributes) const {
    new_attributes =
        static_cast<PropertyAttributes>(attributes() | new_attributes);
    return PropertyDetails(value_, new_attributes);
  }

  // Conversion for storing details as Object.
  explicit inline PropertyDetails(Smi smi);
  inline Smi AsSmi() const;

  static uint8_t EncodeRepresentation(Representation representation) {
    return representation.kind();
  }

  static Representation DecodeRepresentation(uint32_t bits) {
    return Representation::FromKind(static_cast<Representation::Kind>(bits));
  }

  PropertyKind kind() const { return KindField::decode(value_); }
  PropertyLocation location() const { return LocationField::decode(value_); }
  PropertyConstness constness() const { return ConstnessField::decode(value_); }

  PropertyAttributes attributes() const {
    return AttributesField::decode(value_);
  }

  bool HasKindAndAttributes(PropertyKind kind, PropertyAttributes attributes) {
    return (value_ & (KindField::kMask | AttributesField::kMask)) ==
           (KindField::encode(kind) | AttributesField::encode(attributes));
  }

  int dictionary_index() const {
    return DictionaryStorageField::decode(value_);
  }

  Representation representation() const {
    return DecodeRepresentation(RepresentationField::decode(value_));
  }

  int field_index() const { return FieldIndexField::decode(value_); }

  inline int field_width_in_words() const;

  static bool IsValidIndex(int index) {
    return DictionaryStorageField::is_valid(index);
  }

  bool IsReadOnly() const { return (attributes() & READ_ONLY) != 0; }
  bool IsConfigurable() const { return (attributes() & DONT_DELETE) == 0; }
  bool IsDontEnum() const { return (attributes() & DONT_ENUM) != 0; }
  bool IsEnumerable() const { return !IsDontEnum(); }
  PropertyCellType cell_type() const {
    return PropertyCellTypeField::decode(value_);
  }

  // Bit fields in value_ (type, shift, size). Must be public so the
  // constants can be embedded in generated code.
  using KindField = BitField<PropertyKind, 0, 1>;
  using LocationField = KindField::Next<PropertyLocation, 1>;
  using ConstnessField = LocationField::Next<PropertyConstness, 1>;
  using AttributesField = ConstnessField::Next<PropertyAttributes, 3>;
  static const int kAttributesReadOnlyMask =
      (READ_ONLY << AttributesField::kShift);
  static const int kAttributesDontDeleteMask =
      (DONT_DELETE << AttributesField::kShift);
  static const int kAttributesDontEnumMask =
      (DONT_ENUM << AttributesField::kShift);

  // Bit fields for normalized objects.
  using PropertyCellTypeField = AttributesField::Next<PropertyCellType, 2>;
  using DictionaryStorageField = PropertyCellTypeField::Next<uint32_t, 23>;

  // Bit fields for fast objects.
  using RepresentationField = AttributesField::Next<uint32_t, 3>;
  using DescriptorPointer =
      RepresentationField::Next<uint32_t, kDescriptorIndexBitCount>;
  using FieldIndexField =
      DescriptorPointer::Next<uint32_t, kDescriptorIndexBitCount>;

  // All bits for both fast and slow objects must fit in a smi.
  STATIC_ASSERT(DictionaryStorageField::kLastUsedBit < 31);
  STATIC_ASSERT(FieldIndexField::kLastUsedBit < 31);

  static const int kInitialIndex = 1;

#ifdef OBJECT_PRINT
  // For our gdb macros, we should perhaps change these in the future.
  void Print(bool dictionary_mode);
#endif

  enum PrintMode {
    kPrintAttributes = 1 << 0,
    kPrintFieldIndex = 1 << 1,
    kPrintRepresentation = 1 << 2,
    kPrintPointer = 1 << 3,

    kForProperties = kPrintFieldIndex,
    kForTransitions = kPrintAttributes,
    kPrintFull = -1,
  };
  void PrintAsSlowTo(std::ostream& out);
  void PrintAsFastTo(std::ostream& out, PrintMode mode = kPrintFull);

 private:
  PropertyDetails(int value, int pointer) {
    value_ = DescriptorPointer::update(value, pointer);
  }
  PropertyDetails(int value, Representation representation) {
    value_ = RepresentationField::update(value,
                                         EncodeRepresentation(representation));
  }
  PropertyDetails(int value, PropertyConstness constness) {
    value_ = ConstnessField::update(value, constness);
  }
  PropertyDetails(int value, PropertyAttributes attributes) {
    value_ = AttributesField::update(value, attributes);
  }

  uint32_t value_;
};

// kField location is more general than kDescriptor, kDescriptor generalizes
// only to itself.
inline bool IsGeneralizableTo(PropertyLocation a, PropertyLocation b) {
  return b == kField || a == kDescriptor;
}

// PropertyConstness::kMutable constness is more general than
// VariableMode::kConst, VariableMode::kConst generalizes only to itself.
inline bool IsGeneralizableTo(PropertyConstness a, PropertyConstness b) {
  return b == PropertyConstness::kMutable || a == PropertyConstness::kConst;
}

inline PropertyConstness GeneralizeConstness(PropertyConstness a,
                                             PropertyConstness b) {
  return a == PropertyConstness::kMutable ? PropertyConstness::kMutable : b;
}

V8_EXPORT_PRIVATE std::ostream& operator<<(
    std::ostream& os, const PropertyAttributes& attributes);
V8_EXPORT_PRIVATE std::ostream& operator<<(std::ostream& os,
                                           PropertyConstness constness);
}  // namespace internal
}  // namespace v8

#endif  // V8_OBJECTS_PROPERTY_DETAILS_H_


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>gameshop.advance.exceptions.sales</title>
<meta name="date" content="2015-02-13">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

gameshop.advance.exceptions.sales

Exceptions

AlreadyPartialPayedException

AlreadyPayedException

ClientNotFoundException

InvalidSaleState

redpajama_set_name: RedPajamaGithub


text:
{% include charts_intro.md %}

{% include charts_links.md %}


text:
using System;
using Android.Content;
using Android.OS;
using Android.Provider;
using Android.Database;
using Java.IO;
using Android.Webkit;

namespace Plugin.FilePicker
{
    public class IOUtil
    {

        public static string getPath (Context context, Android.Net.Uri uri)
        {
            bool isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

            // DocumentProvider
            if (isKitKat && DocumentsContract.IsDocumentUri (context, uri)) {
                // ExternalStorageProvider
                if (isExternalStorageDocument (uri)) {
                    var docId = DocumentsContract.GetDocumentId (uri);
                    string [] split = docId.Split (':');
                    var type = split [0];

                    if ("primary".Equals (type, StringComparison.OrdinalIgnoreCase)) {
                        return Android.OS.Environment.ExternalStorageDirectory + "/" + split [1];
                    }

                    // TODO handle non-primary volumes
                }
                // DownloadsProvider
                else if (isDownloadsDocument (uri)) {

                    string id = DocumentsContract.GetDocumentId (uri);
                    Android.Net.Uri contentUri = ContentUris.WithAppendedId (
                            Android.Net.Uri.Parse ("content://downloads/public_downloads"), long.Parse (id));

                    return getDataColumn (context, contentUri, null, null);
                }
                // MediaProvider
                else if (isMediaDocument (uri)) {
                    var docId = DocumentsContract.GetDocumentId (uri);
                    string [] split = docId.Split (':');
                    var type = split [0];

                    Android.Net.Uri contentUri = null;
                    if ("image".Equals (type)) {
                        contentUri = MediaStore.Images.Media.ExternalContentUri;
                    } else if ("video".Equals (type)) {
                        contentUri = MediaStore.Video.Media.ExternalContentUri;
                    } else if ("audio".Equals (type)) {
                        contentUri = MediaStore.Audio.Media.ExternalContentUri;
                    }

                    var selection = "_id=?";
                    var selectionArgs = new string [] {
                        split[1]
                    };

                    return getDataColumn (context, contentUri, selection, selectionArgs);
                }
            }
            // MediaStore (and general)
            else if ("content".Equals (uri.Scheme, StringComparison.OrdinalIgnoreCase)) {
                return getDataColumn (context, uri, null, null);
            }
            // File
            else if ("file".Equals (uri.Scheme, StringComparison.OrdinalIgnoreCase)) {
                return uri.Path;
            }

            return null;
        }

        public static string getDataColumn (Context context, Android.Net.Uri uri, string selection,
        string [] selectionArgs)
        {

            ICursor cursor = null;
            var column = "_data";
            string [] projection = {
                column
            };

            try {
                cursor = context.ContentResolver.Query (uri, projection, selection, selectionArgs,
                        null);
                if (cursor != null && cursor.MoveToFirst ()) {
                    int column_index = cursor.GetColumnIndexOrThrow (column);
                    return cursor.GetString (column_index);
                }
            } finally {
                if (cursor != null)
                    cursor.Close ();
            }
            return null;
        }

        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is ExternalStorageProvider.
         */
        public static bool isExternalStorageDocument (Android.Net.Uri uri)
        {
            return "com.android.externalstorage.documents".Equals (uri.Authority);
        }

        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is DownloadsProvider.
         */
        public static bool isDownloadsDocument (Android.Net.Uri uri)
        {
            return "com.android.providers.downloads.documents".Equals (uri.Authority);
        }

        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is MediaProvider.
         */
        public static bool isMediaDocument (Android.Net.Uri uri)
        {
            return "com.android.providers.media.documents".Equals (uri.Authority);
        }

        public static byte [] readFile (string file)
        {
            try {
                return readFile (new File (file));
            } catch (Exception ex) {
                System.Diagnostics.Debug.Write (ex);
                return new byte [0];
            }
        }

        public static byte [] readFile (File file)
        {
            // Open file
            var f = new RandomAccessFile (file, "r");

            try {
                // Get and check length
                long longlength = f.Length ();
                var length = (int)longlength;

                if (length != longlength)
                    throw new IOException ("Filesize exceeds allowed size");
                // Read file and return data
                byte [] data = new byte [length];
                f.ReadFully (data);
                return data;
            } catch (Exception ex) {
                System.Diagnostics.Debug.Write (ex);
                return new byte [0];
            } finally {
                f.Close ();
            }
        }

        public static string GetMimeType (string url)
        {
            string type = null;
            var extension = MimeTypeMap.GetFileExtensionFromUrl (url);

            if (extension != null) {
                type = MimeTypeMap.Singleton.GetMimeTypeFromExtension (extension);
            }

            return type;
        }
    }
}


text:
require_relative "associative"

module Administrate
  module Field
    class BelongsTo < Associative
      def self.permitted_attribute(attr, _options = nil)
        :"#{attr}_id"
      end

      def permitted_attribute
        foreign_key
      end

      def associated_resource_options
        [nil] + candidate_resources.map do |resource|
          [display_candidate_resource(resource), resource.send(primary_key)]
        end
      end

      def selected_option
        data && data.send(primary_key)
      end

      private

      def candidate_resources
        order = options.delete(:order)
        order ? associated_class.order(order) : associated_class.all
      end

      def display_candidate_resource(resource)
        associated_dashboard.display_resource(resource)
      end
    end
  end
end


text:
<?xml version="1.0" ?>
<tei xml:space="preserve">
	<teiHeader>
		<fileDesc xml:id="900043v1"/>
	</teiHeader>
	<text xml:lang="en">
		<front>
<lb/>

	Title:
	<docTitle>
	<titlePart>Physiotherapist and Podiatrist Independent Prescribing in the United Kingdom: A quasi<lb/> experimental study<lb/></titlePart>
	</docTitle>

	Short title: Physiotherapist and Podiatrist Independent Prescribing in the United Kingdom<lb/>

	<byline>
	<docAuthor>Nicola Carey, PhD,</docAuthor>
	</byline>

	<byline>
	<affiliation>Reader, School of Health Sciences, University of Surrey,</affiliation>
	</byline>

	<address>UK<lb/></address>

	<byline>
	<docAuthor>Judith Edwards, MSc,</docAuthor>
	</byline>

	<byline>
	<affiliation>Research Fellow, School of Health Sciences, University of Surrey,</affiliation>
	</byline>

	<address>UK<lb/></address>

	<byline>
	<docAuthor>Simon Otter, PhD,</docAuthor>
	</byline>

	<byline>
	<affiliation>Principal Lecturer, School of Health Science, University of Brighton,</affiliation>
	</byline>

	<address>UK<lb/></address>

	<byline>
	<docAuthor>Heather Gage, PhD,</docAuthor>
	</byline>

	<byline>
	<affiliation>Professor of Health Economics, University of Surrey,</affiliation>
	</byline>

	<address>UK<lb/></address>

	<byline>
	<docAuthor>Peter Williams, MSc, Medical Statistician,</docAuthor>
	</byline>

	<byline>
	<affiliation>University of Surrey,</affiliation>
	</byline>

	<address>UK<lb/></address>

	<byline>
	<docAuthor>Molly Courtenay, PhD, Professor,</docAuthor>
	</byline>

	<byline>
	<affiliation>School of Healthcare Sciences, Cardiff University,</affiliation>
	</byline>

	<address>UK<lb/></address>

	<byline>
	<docAuthor>Ann Moore PhD, FCSP, FMACP, Cert Ed, Dip.TP, Emeritus Professor,</docAuthor>
	</byline>

	<byline>
	<affiliation>Centre for Health<lb/> Research, School of Health Sciences, University of Brighton,</affiliation>
	</byline>

	<address>UK<lb/></address>

	<byline>
	<docAuthor>Karen Stenner, PhD, Lecturer</docAuthor>
	</byline>

	in

	<byline>
	<affiliation>Health Services Research, School of Health Sciences,<lb/> University of Surrey,</affiliation>
	</byline>

	<address>UK<lb/></address>

	Keywords:
	<keyword>physiotherapy, podiatry, independent prescribing, quasi experiment<lb/></keyword>

	Short title: Physiotherapist and Podiatrist Independent Prescribing in the UK<lb/> Words: 5358<lb/> Tables: 8<lb/> Corresponding author:
	<byline>
	<docAuthor>Nicola Carey,</docAuthor>
	</byline>

	<byline>
	<affiliation>School of Health Sciences,</affiliation>
	</byline>

	<address>Kate Granger Building,<lb/></address>

	<byline>
	<affiliation>University of Surrey,</affiliation>
	</byline>

	<address>Guildford, GU2 7YH, UK<lb/></address>

	Email:
	<email>n.carey@surrey.ac.uk</email>

		</front>
	</text>
</tei>


text:
#ifndef _PDF_XREF_STREAM_PARSER_OBJECT_H_
#  define _PDF_XREF_STREAM_PARSER_OBJECT_H_
#  include "PdfDefines.h"
#  include "PdfParserObject.h"
#  define W_ARRAY_SIZE	3
#  define W_MAX_BYTES	4
namespace PoDoFo
{
/**
 * A utility class for PdfParser that can parse
 * an XRef stream object.
 *
 * It is mainly here to make PdfParser more modular.
 * This is only marked PODOFO_API for the benefit of the tests,
 * the class is for internal use only. It is deprecated, so
 * don't ever rely on it (i.e. externally or in PoDoFo tools).
 */
  class PODOFO_DEPRECATED PODOFO_API PdfXRefStreamParserObject : public PdfParserObject
  {
  public:
    /** Parse the object data from the given file handle starting at
     *  the current position.
     *  \param pCreator pointer to a PdfVecObjects to resolve object references
     *  \param rDevice an open reference counted input device which is positioned in
     *                 front of the object which is going to be parsed.
     *  \param rBuffer buffer to use for parsing to avoid reallocations
     *  \param pOffsets XRef entries are stored into this array
     */
    PdfXRefStreamParserObject(PdfVecObjects* pCreator, const PdfRefCountedInputDevice& rDevice, const PdfRefCountedBuffer& rBuffer, PdfParser::TVecOffsets* pOffsets);
    ~PdfXRefStreamParserObject();
    void Parse();
    void ReadXRefTable();
    /**
     * \returns true if there is a previous XRefStream
     */
    inline bool HasPrevious();
    /**
     * \returns the offset of the previous XRef table
     */
    inline pdf_long GetPreviousOffset();
  private:
    /**
     * Read the /Index key from the current dictionary
     * and write uit to a vector.
     *
     * \param rvecIndeces store the indeces hare
     * \param size default value from /Size key
     */
    void GetIndeces(std::vector<pdf_int64>& rvecIndeces, pdf_int64 size);
    /**
     * Parse the stream contents
     *
     * \param nW /W key
     * \param rvecIndeces indeces as filled by GetIndeces
     *
     * \see GetIndeces
     */
    void ParseStream(const pdf_int64 nW[W_ARRAY_SIZE], const std::vector<pdf_int64>& rvecIndeces);
    void ReadXRefStreamEntry(char* pBuffer, pdf_long, const pdf_int64 lW[W_ARRAY_SIZE], int nObjNo);
    pdf_long m_lNextOffset;
    PdfParser::TVecOffsets* m_pOffsets;
  };
// -----------------------------------------------------
//
// -----------------------------------------------------
  inline bool PdfXRefStreamParserObject::HasPrevious()
  {
    return (m_lNextOffset != -1);
  }
// -----------------------------------------------------
//
// -----------------------------------------------------
  inline pdf_long PdfXRefStreamParserObject::GetPreviousOffset()
  {
    return m_lNextOffset;
  }
}
#endif


text:
'use strict';

var test = require('tape');

var glsl = require('../index');

module.exports = function (Common) {
	test('mod.remove', function(t) {
		var source = '#include source2;\n';

		var ast;
		t.doesNotThrow(function() {
			ast = glsl.parse(source);
		}, 'Parsing OK');

		var includeNode = ast.statements[0];
		t.doesNotThrow(function() {
			glsl.mod.remove(includeNode);
		}, 'Remove');

		t.equal(glsl.string(ast), '');
		t.end();
	});

	test('mod.replace', function(t) {
		var source = '#include source2;\n';
		var source2 = 'void add(float x) {\n\treturn x + y;\n}\n';

		var ast;
		var ast2;
		t.doesNotThrow(function() {
			ast = glsl.parse(source);
			ast2 = glsl.parse(source2);
		}, 'Parsing OK');

		var includeNode = ast.statements[0];
		t.doesNotThrow(function() {
			glsl.mod.replace(includeNode, ast2);
		}, 'Replace');

		t.equal(glsl.string(ast), source2);
		t.end();
	});

	test('mod.add', function(t) {
		var source = '#include source2;\n';
		var source2 = 'uniform mat4 view;\n';

		var ast;
		var ast2;
		t.doesNotThrow(function() {
			ast = glsl.parse(source);
			ast2 = glsl.parse(source2);
		}, 'Parsing OK');

		var includeNode = ast.statements[0];
		t.doesNotThrow(function() {
			glsl.mod.addBefore(includeNode, ast2);
		}, 'Add before');

		t.doesNotThrow(function() {
			glsl.mod.addAfter(includeNode, ast2);
		}, 'Add after');

		t.equal(glsl.string(ast), source2 + source + source2);
		t.end();
	});
};


text:
class Actor:

    def __init__(self, name):
        self.name = name

    def __lt__(self, other):
        return self.name < other

    def __gt__(self, other):
        return self.name > other

    def __eq__(self, other):
        return self.name == other

    def __hash__(self):
        return hash(self.name)

    def __str__(self):
        return self.name

    def __repr__(self):
        return 'Actor({:s})'.format(self.name)

class Movie:

    def __init__(self, title, year):
        self.title = title
        self.year = year

    def get_weight(self):
        return 1 + (2015 - self.year)

    def __lt__(self, other):
        if self.title < other.title:
            return True
        elif self.title == other.title and self.year < other.year:
            return True
        else:
            return False

    def __gt__(self, other):
        if self.title > other.title:
            return True
        elif self.title == other.title and self.year > other.year:
            return True
        else:
            return False

    def __eq__(self, other):
        return self.title == other.title and self.year == other.year

    def __hash__(self):
        return hash((self.title, self.year))

    def __str__(self):
        return '{:s}#@{:s}'.format(self.title, str(self.year))

    def __repr__(self):
        return 'Movie({:s}, {:s})'.format(self.title, repr(self.year))


text:
<?php

class topMenu{

	var $db;

	function topMenu($db){
		$this->db = $db;

		$querystatement = "
			SELECT
				`id`,
				`name`,
				`link`,
				`uuid`,
				`roleid`
			FROM
				`menu`
			WHERE
				`parentid` = ''
				OR
				`parentid` IS NULL
			ORDER BY
				`displayorder`;
			";

		$this->menuresult = $this->db->query($querystatement);

	}

	function getSubItems($parentid){
		$querystatement = "
			SELECT
				`id`,
				`name`,
				`link`,
				`roleid`
			FROM
				`menu`
			WHERE
				`parentid` = '".$parentid."'
			ORDER BY
				`displayorder`;
			";

		$queryresult = $this->db->query($querystatement);

		if ($this->db->numRows($queryresult)<1) return false; else return $queryresult;
	}

	function display(){

?>

<a href="<?php echo APP_PATH.DEFAULT_LOAD_PAGE ?>" title="<?php echo htmlQuotes(APPLICATION_NAME);?>" name="toptop"><?php echo APPLICATION_NAME;?>

<?php echo htmlQuotes(trim($_SESSION["userinfo"]["firstname"]." ".$_SESSION["userinfo"]["lastname"]))?>

	<?php
		$submenustring="";

		while($menurecord = $this->db->fetchArray($this->menuresult)){

			if(hasRights($menurecord["roleid"])){
				if($menurecord["link"]) {
					if(strpos($menurecord["link"],"http")!==0 && strpos($menurecord["link"],"javascript")!==0)
						$menurecord["link"]=APP_PATH.$menurecord["link"];
					?>
<a href="<?php echo $menurecord["link"]?>"><?php echo $menurecord["name"]?>
<?php
				} else {

				?>
<a href="#toptop" class="topMenus" id="menu<?php echo $menurecord["id"]?>"><?php echo $menurecord["name"]; ?>

<ul class="submenuitems" id="submenu<?php echo $menurecord["id"]?>"><?php

					$subitemsquery = $this->getSubItems($menurecord["uuid"]);

					if($subitemsquery){
						$sep=false;

						while($subrecord=$this->db->fetchArray($subitemsquery)){
							if($subrecord["name"]=="----")
								$sep=true;
							else{
								if(hasRights($subrecord["roleid"])){
									if(strpos($subrecord["link"],"http")!==0 && strpos($subrecord["link"],"javascript")!==0)
										$subrecord["link"]=APP_PATH.$subrecord["link"];
									if(strpos($subrecord["link"],"javascript")===0)
										$subrecord["link"]="#\" onclick=\"".str_replace("javascript:","",$subrecord["link"]);
								?><li <?php if($sep) echo " class=\"menuSep\" "?>><a href="<?php echo $subrecord["link"]?>"> <?php echo $subrecord["name"] ?>
<?php
									$sep=false;
								}//end if
							}//end if
						}//end while

					}//end if
					?>

<?php ;

				}//end if

			}//end if

		}//end while
	?>

<?php

	}//end method
}// end class

?>


text:
/*
 | PC-LISP (C) 1984-1989 Peter J.Ashwood-Smith
 */
#include <stdio.h>
#include <math.h>
#include "lisp.h"

/*************************************************************************
 ** buatom : This is the 'atom' predicate which if given an atom as a   **
 ** parameter will return the atom 't', otherwise it will return the    **
 ** atom 'nil'. For example : (atom x) is 't' but (atom (x)) is 'nil'   **
 ** Also note that (atom ()) is 't because () is equivalent to 'nil.    **
 *************************************************************************/
struct conscell *buatom(form)
struct conscell *form;
{      if ((form != NULL)&&(form->cdrp == NULL))
       {  if (form->carp != NULL)
          {   if ((form->carp->celltype == CONSCELL)||
                  (form->carp->celltype == HUNKATOM))
                  return(NULL);
          };
          return(LIST(thold));
       };
       ierror("atom");  /*  doesn't return  */
       return NULL;   /*  keep compiler happy  */
}


text:
//Class for making TimePicker preference view
//Version 1.0. Last update: never.
//This code was taken from an external source (website) and not changed

package ru.nim579.nixieclock;

import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TimePicker;

public class TimePickerPreference extends DialogPreference {

    private static final String DEFAULT_TIME = "00:00";

    private TimePicker mTimePicker;

    public TimePickerPreference(Context context, AttributeSet attrs, int defStyle){
        super(context, attrs, defStyle);
        setPositiveButtonText(R.string.general_ok);
        setNegativeButtonText(R.string.general_cancel);
    }

    public TimePickerPreference(Context context, AttributeSet attrs){
        this(context, attrs, 0);
    }

    public TimePickerPreference(Context context){
        this(context, null);
    }

    @Override
    protected View onCreateDialogView(){
        mTimePicker = new TimePicker(getContext());
        mTimePicker.setEnabled(true);
        return mTimePicker;
    }

    @Override
    protected void onBindDialogView(View view) {
        super.onBindDialogView(view);
        TimePicker timePicker = mTimePicker;
        int[] hourAndMinutes = getHourAndTime(getPersistedString(DEFAULT_TIME));
        timePicker.setCurrentHour(hourAndMinutes[0]);
        timePicker.setCurrentMinute(hourAndMinutes[1]);
    }

    @Override
    protected Object onGetDefaultValue(TypedArray a, int index) {
        return a.getString(index);
    }

    @Override
    protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
        persistString(restoreValue ? getPersistedString(getCurrentTime())
                : (String) defaultValue);
    }

    protected void onDialogClosed(boolean positiveResult){
        if (positiveResult){
            if (mTimePicker != null){
                persistString(getCurrentTime());
            }
        }
    }

    /**
     *
     *
     *
     * @return string in format HH:MM
     */

    private String getCurrentTime(){
        if (mTimePicker != null) {
            return mTimePicker.getCurrentHour() + ":"+ mTimePicker.getCurrentMinute();
        }
        return DEFAULT_TIME;
    }

    /**
     *
     *
     *
     * @param timeString
     *            string in format HH:MM
     *
     * @return array of size 2; first element - hours, second - minutes
     */

    public static int[] getHourAndTime(String timeString){
        if (!timeString.contains(":")) {
            throw new RuntimeException("Bad time string");
        }
        String[] values = timeString.split(":");
        return new int[] { Integer.parseInt(values[0]), Integer.parseInt(values[1]) };

    }

}


text:
package org.locationtech.geowave.format.landsat8;

import org.locationtech.geowave.core.cli.annotations.GeowaveOperation;
import org.locationtech.geowave.core.cli.api.DefaultOperation;
import org.locationtech.geowave.core.cli.operations.GeowaveTopLevelSection;
import com.beust.jcommander.Parameters;

@GeowaveOperation(name = "landsat", parentOperation = GeowaveTopLevelSection.class)
@Parameters(
    commandDescription = "Operations to analyze, download, and ingest Landsat 8 imagery publicly available on AWS")
public class Landsat8Section extends DefaultOperation {
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="definitions"
             xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:camunda="http://camunda.org/schema/1.0/bpmn"
             targetNamespace="Examples">

    <process id="nonInterruptingCycle" isExecutable="true">

        <startEvent id="theStart"/>
        <sequenceFlow id="flow1" sourceRef="theStart" targetRef="task"/>

        <receiveTask id="task"/>
        <sequenceFlow id="flow2" sourceRef="task" targetRef="end"/>

        <boundaryEvent id="timer" attachedToRef="task" cancelActivity="false">
            <timerEventDefinition>
                <timeCycle>${timeCycle}</timeCycle>
            </timerEventDefinition>
        </boundaryEvent>
        <sequenceFlow id="flow3" sourceRef="timer" targetRef="timerFiredTask"/>
        <userTask id="timerFiredTask" />
        <sequenceFlow id="flow4" sourceRef="timerFiredTask" targetRef="nonInterruptingEnd"/>
        <endEvent id="nonInterruptingEnd"/>

        <endEvent id="end"/>

    </process>
</definitions>


text:
=head1 LICENSE

  Copyright (c) 1999-2011 The European Bioinformatics Institute and
  Genome Research Limited.  All rights reserved.

  This software is distributed under a modified Apache license.
  For license details, please see

    http://www.ensembl.org/info/about/code_licence.html

=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <dev@ensembl.org>.

  Questions may also be sent to the Ensembl help desk at
  <helpdesk@ensembl.org>.

=cut

=head1 NAME

Bio::EnsEMBL::DBFile::FileAdaptor - Base Adaptor for direct file access

=head1 SYNOPSIS

=head1 DESCRIPTION

Basic wrapper class to provide access to file based data.

This is primarily aimed at indexed Collection(.col) files which are optimised for Slice
based queries. Collections store fixed width width/windowed data as BLOBS.  This makes
it possible to seek to the a required location given slice coordinate and read the only
the required amount of data covering the slice.

Currently only works as hybrid DBAdaptor e.g. ResultFeatureAdaptor which inherits both from
here and BaseFeatureAdaptor.

=head1 SEE ALSO

=cut

package Bio::EnsEMBL::DBFile::FileAdaptor;

use Bio::EnsEMBL::Utils::Exception qw(throw warning deprecate);
use strict;
use warnings;

=head2 get_filehandle

  Arg[1]     : string     - filepath
  Arg[2]     : HASHREF    - Optional params, see open_file
  Example    : my $fh     = $self->get_filehandle($filepath, 1);
  Description: Gets and caches a simple file handle.
  Returntype : GLOB/undef - filehandle
  Exceptions : warns if cache entry exists but is not defined
  Caller     : general
  Status     : at risk

=cut

sub get_filehandle{
  my ($self, $filepath, $params_hash) = @_;

  my $file_op = '<';

  if(exists $params_hash->{-file_operator}){
	$file_op = $params_hash->{-file_operator};
  }else{
	$params_hash->{-file_operator} = $file_op;
  }

  if(! exists $self->{file_cache}{$filepath}{filehandle}){
	my $fh = $self->Bio::EnsEMBL::DBFile::FileAdaptor::open_file($filepath, $params_hash);

	if(defined $fh){
	  $self->{file_cache}{$filepath}{filehandle} = $fh;
	  #$self->initialise_filehandle($filepath) if $self->can('initialise_filehandle');
	  $self->initialise_filehandle($filepath) if($file_op eq '<');
	}
  }
  elsif(! defined $self->{file_cache}{$filepath}{filehandle}){
	#This maybe one of several read/seek errors which will have already been warned
	warn "Encountered and error with file handle for $filepath\n";
  }
  #else
  # check against cache file op
  # to make sure we aren't trying to open an already open fh with a different operator

  return $self->{file_cache}{$filepath}{filehandle};
}

=head2 open_file

  Arg[1]     : string     - filepath
  Arg[2]     : HASHREF    - Optional params:
                                 -binmode       => 0|1,   # Boolean i.e. treat file as binary
                                 -file_operator => '>'    # Default is '<'
                                #-perms_octal   =>  # Requires FileHandle
  Example    : my $fh     = $self->open_file($filepath, {-binmode = > 1, -file_operator => '>'});
  Description: Opens a file for reading or writing.
  Returntype : GLOB/undef - filehandle
  Exceptions : warns if file open fails
               warns if file operator unsupported
               warns if failed to set binmode
  Caller     : general
  Status     : at risk

=cut

sub open_file{
  my ($self, $filepath, $params_hash) = @_;

  #Validate params_hash?
  #rearrange? Will not warn/throw for invalid keys?
  #perms octal, requires FileHandle? See EFGUtils::open_file

  my $file_op = $params_hash->{-file_operator} || '<';

  if(($file_op ne '<') &&
	 ($file_op ne '>') &&
	 ($file_op ne '>>')){
	#thow rather than warn as this is a code bug
	throw("Cannot perform open with unsupported operator:\t${file_op}${filepath}");
  }

  my $fh;
  my $success = open($fh, "${file_op}${filepath}");
  #$fh will be still be GLOB on fail

  if(! $success){
	undef $fh;
	warn "Failed to open:\t$filepath\n$!\n";
  }
  elsif($params_hash->{-binmode}){
	$success = binmode $fh;

	if(! $success){
	  warn "Failed to set binmode:\t$filepath\n$!";
	  undef $fh;
	}
  }

  return $fh;
}

=head2 validate_file_length

  Arg[1]     : string  - filepath
  Arg[2]     : int     - expected length in bytes
  Example    : $self->validate_file_length($filepath, $expected_length);
  Description: Utility method which can be used during file creation
  Returntype : None
  Exceptions : warns if file open fails
               throws if file is not expected length
  Caller     : general
  Status     : at risk - change to seek to accounts for 'logical characters'

=cut

sub validate_file_length{
  my ($self, $filepath, $expected_length, $binmode) = @_;

  #Currently not using cache as we rarely want to
  #use the file handle afterwards

  #THIS WAS USING EFGUtils::open_file imported in the Collector::ResultFeature!!!!
  #which is just a sub not a class method, and is in a parallel inheritance path
  #No warnings about redefining method :(
  #Force use of FileAdaptor::open_file

  my $fh = $self->Bio::EnsEMBL::DBFile::FileAdaptor::open_file($filepath, {-binmode => $binmode});

  #sysseek always returns length in bytes, change to seek which
  #uses logical characters i.e. actual encoding?
  #Does seek use bytes in binmode and chars in non-binmode?

  my $seeked_bytes = sysseek($fh, 0, 2);# 2 is SEEK_END
  #There is no systell function. Use sysseek(FH, 0, 1) for that.

  if($seeked_bytes < $expected_length){
	throw("File is shorter($seeked_bytes) than expected($expected_length):\t$filepath\n");
  }
  elsif($seeked_bytes > $expected_length){
	throw("File is longer($seeked_bytes) than expected($expected_length):\t$filepath\n");
  }

  return;
}

### STUBB/TEMPLATE METHODS ###
#
#   If required hese should be over-ridden in the
#   descendant FileAdaptor e.g. CollectionAdaptor
#   Listed here rather for visibility (rather than
#   using 'can')

sub initialise_filehandle{
  return;
}

1;


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>ngInit in Nested ngRepeats</title>

Toy Index: {{$index}}, Box Index: {{boxIndex}}, Object Index: {{homeIndex}}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Camarosporium cytisi Berl. & Bres.

### Remarks
null


text:
require 'stringio'

# Enumerable EachSQL object.
class EachSQL
  include Enumerable

  # @param[Symbol] type RDBMS type: :default|:mysql|:oracle|:postgres
  # @param[String] delimiter Script delimiter.
  def initialize type, delimiter = ';'
    @type   = type
    @data   = ''
    @sqls   = []

    self.delimiter = delimiter
  end

  # @param[String] delim SQL delimiter
  # @return[EachSQL]
  def delimiter= delim
    @delim = delim
    @parser = EachSQL::Parser.parser_for @type, delim
    self
  end

  # @return[String] Current delimiter.
  def delimiter
    @delim
  end

  # Appends the given String to the buffer.
  # @param[String] input String to append
  def << input
    if input
      @data << input.sub(/\A#{[65279].pack('U*')}/, '') # BOM (FIXME)
    end
    self
  end

  # Clears the buffer
  # @return [EachSQL]
  def clear
    @data = ''
    self
  end

  # Parses current buffer and returns the result in Hash.
  # :sqls is an Array of processed executable SQL blocks,
  # :leftover is the unparsed trailing data
  # @return [Hash]
  def shift
    result   = @parser.parse @data
    @data    = result.captures[:leftover].join
    leftover = strip_sql(@data)
    {
      :sqls =>
        result.captures[:execution_block].map { |b| strip_sql b },
      :leftover => leftover.empty? ? nil : leftover
    }
  end

  # Return is the buffer is empty
  # @return [Boolean]
  def empty?
    @data.gsub(/\s/, '').empty?
  end

  # Parses the buffer and enumerates through the executable blocks.
  # @yield [String]
  # @return [NilClass]
  def each
    return enum_for(:each) unless block_given?

    result = shift
    sqls   = (result[:sqls] + result[:leftover]).
              map { |sql| strip_sql(sql) }.
              reject(&:empty?)
    sqls.each do |sql|
      yield sql
    end
  end

  private
  def strip_sql sql
    # Preprocess
    case @type
    when :oracle
      sql = sql.sub(/\A[\s\/]+/, '').sub(/[\s\/]+\Z/, '')
    end

    # FIXME: Infinite loop?
    # sql = sql.gsub(
    #         /
    #          (?:
    #            (?:\A(?:#{Regexp.escape @delim}|[\s]+)+)
    #            |
    #            (?:(?:#{Regexp.escape @delim}|[\s]+)+\Z)
    #          )+
    #         /x, '')
    prev_sql = nil
    delim = Regexp.escape @delim
    while prev_sql != sql
      prev_sql = sql
      sql = sql.strip.sub(/\A(?:#{delim})+/, '').sub(/(?:#{delim})+\Z/, '')
    end

    # Postprocess
    case @type
    when :oracle
      if sql =~ /\bend(\s+\S+)?\Z/i
        sql = sql + ';'
      end
    end

    sql
  end

end#EachSQL


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Operaciones - Claro</title>

    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

    <link rel="stylesheet" href="<?php echo base_url()?>bootstrap/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

    <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">

    <link rel="stylesheet" href="<?php echo base_url()?>dist/css/AdminLTE.min.css">

    <link rel="stylesheet" href="<?php echo base_url()?>dist/css/skins/_all-skins.min.css">

    <link rel="stylesheet" href="<?php echo base_url(); ?>plugins/datatables/dataTables.bootstrap.css">

          SIAD

          SIAD - Claro

            Minimizar Menu

                  <img src="<?php echo base_url()?>siad_img/Claro.png" class="user-image" alt="User Image">
                  <?php echo $this->session->userdata('NOMBRE').' '.$this->session->userdata('APELLIDOS'); ?>

                    <img src="<?php echo base_url()?>siad_img/Claro.png" class="img-circle" alt="User Image">

                      <?php echo $this->session->userdata('NOMBRE').' '.$this->session->userdata('APELLIDOS'); ?>
                      <?php echo $this->session->userdata('EMPUSUARIO') ?>

                      Recordar Password

                      Cambiar Password

                      <a href="<?php echo base_url()?>login/CerrarSesion" class="btn btn-default btn-flat">Cerra Sesion

MENU

            <?php

              $contador  = 0;
              $LineaTemp = 0;
              $IdMenu    = 0;

              if(!isset($_SESSION))
              {
                session_start();
              }

              $ArrayMenu = $_SESSION['Menu'];

              foreach ($ArrayMenu as $value) {
                # code...
                $linea    = $value->parent;
                $url      = $value->url;
                $IdMenu   = $value->id;

                if($linea == 0){
                  $LineaTemp = $IdMenu;
                  echo '
';
                  echo ''.$value->label.'';
                  echo '
';
                }

                foreach ($ArrayMenu as $child) {
                  # code...
                  if($child->parent == $LineaTemp){
                    echo '
url.'">'.$child->label.'';//

                    //_______
                    echo '
';
                    foreach ($ArrayMenu as $subchild) {
                      # code...
                      if($subchild->parent == $child->id){
                        echo '
url.'">'.$subchild->label.'
';
                      }
                    }
                    echo '

';
                    //_______
                  }
                }

                echo '

';
              }

            ?>


text:
PostgreSQL, often simply "Postgres", is an object-relational database management system (ORDBMS) with an emphasis on extensibility and standards-compliance. As a database server, its primary function is to store data, securely and supporting best practices, and retrieve it later, as requested by other software applications, be it those on the same computer or those running on another computer across a network (including the Internet). It can handle workloads ranging from small single-machine applications to large Internet-facing applications with many concurrent users. Recent versions also provide replication of the database itself for security and scalability.

PostgreSQL implements the majority of the SQL:2011 standard, is ACID-compliant and transactional (including most DDL statements) avoiding locking issues using multiversion concurrency control (MVCC), provides immunity to dirty reads and full serializability; handles complex SQL queries using many indexing methods that are not available in other databases; has updateable views and materialized views, triggers, foreign keys; supports functions and stored procedures, and other expandability, and has a large number of extensions written by third parties. In addition to the possibility of working with the major proprietary and open source databases, PostgreSQL supports migration from them, by its extensive standard SQL support and available migration tools. And if proprietary extensions had been used, by its extensibility that can emulate many through some built-in and third-party open source compatibility extensions, such as for Oracle.

> [wikipedia.org/wiki/PostgreSQL](https://en.wikipedia.org/wiki/PostgreSQL)

%%LOGO%%

# How to use this image

## start a postgres instance

```console
$ docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d %%IMAGE%%
```

The default `postgres` user and database are created in the entrypoint with `initdb`.

> The postgres database is a default database meant for use by users, utilities and third party applications.
>
> [postgresql.org/docs](http://www.postgresql.org/docs/9.5/interactive/app-initdb.html)

## ... or via `psql`

```console
$ docker run -it --rm --network some-network %%IMAGE%% psql -h some-postgres -U postgres
psql (9.5.0)
Type "help" for help.

postgres=# SELECT 1;
 ?column?
----------
        1
(1 row)

```

## %%STACK%%

Run `docker stack deploy -c stack.yml %%REPO%%` (or `docker-compose -f stack.yml up`), wait for it to initialize completely, and visit `http://swarm-ip:8080`, `http://localhost:8080`, or `http://host-ip:8080` (as appropriate).

# How to extend this image

There are many ways to extend the `%%REPO%%` image. Without trying to support every possible use case, here are just a few that we have found useful.

## Environment Variables

The PostgreSQL image uses several environment variables which are easy to miss. While none of the variables are required, they may significantly aid you in using the image.

**Warning**: the Docker specific variables will only have an effect if you start the container with a data directory that is empty; any pre-existing database will be left untouched on container startup.

### `POSTGRES_PASSWORD`

This environment variable is required for you to use the PostgreSQL image. It must not be empty or undefined. This environment variable sets the superuser password for PostgreSQL. The default superuser is defined by the `POSTGRES_USER` environment variable.

**Note 1:** The PostgreSQL image sets up `trust` authentication locally so you may notice a password is not required when connecting from `localhost` (inside the same container). However, a password will be required if connecting from a different host/container.

**Note 2:** This variable defines the superuser password in the PostgreSQL instance, as set by the `initdb` script during initial container startup. It has no effect on the `PGPASSWORD` environment variable that may be used by the `psql` client at runtime, as described at [https://www.postgresql.org/docs/10/static/libpq-envars.html](https://www.postgresql.org/docs/10/static/libpq-envars.html). `PGPASSWORD`, if used, will be specified as a separate environment variable.

### `POSTGRES_USER`

This optional environment variable is used in conjunction with `POSTGRES_PASSWORD` to set a user and its password. This variable will create the specified user with superuser power and a database with the same name. If it is not specified, then the default user of `postgres` will be used.

Be aware that if this parameter is specified, PostgreSQL will still show `The files belonging to this database system will be owned by user "postgres"` during initialization. This refers to the Linux system user (from `/etc/passwd` in the image) that the `postgres` daemon runs as, and as such is unrelated to the `POSTGRES_USER` option. See the section titled "Arbitrary `--user` Notes" for more details.

### `POSTGRES_DB`

This optional environment variable can be used to define a different name for the default database that is created when the image is first started. If it is not specified, then the value of `POSTGRES_USER` will be used.

### `POSTGRES_INITDB_ARGS`

This optional environment variable can be used to send arguments to `postgres initdb`. The value is a space separated string of arguments as `postgres initdb` would expect them. This is useful for adding functionality like data page checksums: `-e POSTGRES_INITDB_ARGS="--data-checksums"`.

### `POSTGRES_INITDB_WALDIR`

This optional environment variable can be used to define another location for the Postgres transaction log. By default the transaction log is stored in a subdirectory of the main Postgres data folder (`PGDATA`). Sometimes it can be desireable to store the transaction log in a different directory which may be backed by storage with different performance or reliability characteristics.

**Note:** on PostgreSQL 9.x, this variable is `POSTGRES_INITDB_XLOGDIR` (reflecting [the changed name of the `--xlogdir` flag to `--waldir` in PostgreSQL 10+](https://wiki.postgresql.org/wiki/New_in_postgres_10#Renaming_of_.22xlog.22_to_.22wal.22_Globally_.28and_location.2Flsn.29)).

### `POSTGRES_HOST_AUTH_METHOD`

This optional variable can be used to control the `auth-method` for `host` connections for `all` databases, `all` users, and `all` addresses. If unspecified then [`md5` password authentication](https://www.postgresql.org/docs/current/auth-password.html) is used. On an uninitialized database, this will populate `pg_hba.conf` via this approximate line:

```console
echo "host all all all $POSTGRES_HOST_AUTH_METHOD" >> pg_hba.conf
```

See the PostgreSQL documentation on [`pg_hba.conf`](https://www.postgresql.org/docs/current/auth-pg-hba-conf.html) for more information about possible values and their meanings.

**Note 1:** It is not recommended to use [`trust`](https://www.postgresql.org/docs/current/auth-trust.html) since it allows anyone to connect without a password, even if one is set (like via `POSTGRES_PASSWORD`). For more information see the PostgreSQL documentation on [*Trust Authentication*](https://www.postgresql.org/docs/current/auth-trust.html).

**Note 2:** If you set `POSTGRES_HOST_AUTH_METHOD` to `trust`, then `POSTGRES_PASSWORD` is not required.

### `PGDATA`

This optional variable can be used to define another location - like a subdirectory - for the database files. The default is `/var/lib/postgresql/data`. If the data volume you're using is a filesystem mountpoint (like with GCE persistent disks) or remote folder that cannot be chowned to the `postgres` user (like some NFS mounts), Postgres `initdb` recommends a subdirectory be created to contain the data.

For example:

```console
$ docker run -d \
	--name some-postgres \
	-e POSTGRES_PASSWORD=mysecretpassword \
	-e PGDATA=/var/lib/postgresql/data/pgdata \
	-v /custom/mount:/var/lib/postgresql/data \
	%%IMAGE%%
```

This is an environment variable that is not Docker specific. Because the variable is used by the `postgres` server binary (see the [PostgreSQL docs](https://www.postgresql.org/docs/11/app-postgres.html#id-1.9.5.14.7)), the entrypoint script takes it into account.

## Docker Secrets

As an alternative to passing sensitive information via environment variables, `_FILE` may be appended to some of the previously listed environment variables, causing the initialization script to load the values for those variables from files present in the container. In particular, this can be used to load passwords from Docker secrets stored in `/run/secrets/<secret_name>` files. For example:

```console
$ docker run --name some-postgres -e POSTGRES_PASSWORD_FILE=/run/secrets/postgres-passwd -d %%IMAGE%%
```

Currently, this is only supported for `POSTGRES_INITDB_ARGS`, `POSTGRES_PASSWORD`, `POSTGRES_USER`, and `POSTGRES_DB`.

## Initialization scripts

If you would like to do additional initialization in an image derived from this one, add one or more `*.sql`, `*.sql.gz`, or `*.sh` scripts under `/docker-entrypoint-initdb.d` (creating the directory if necessary). After the entrypoint calls `initdb` to create the default `postgres` user and database, it will run any `*.sql` files, run any executable `*.sh` scripts, and source any non-executable `*.sh` scripts found in that directory to do further initialization before starting the service.

**Warning**: scripts in `/docker-entrypoint-initdb.d` are only run if you start the container with a data directory that is empty; any pre-existing database will be left untouched on container startup. One common problem is that if one of your `/docker-entrypoint-initdb.d` scripts fails (which will cause the entrypoint script to exit) and your orchestrator restarts the container with the already initialized data directory, it will not continue on with your scripts.

For example, to add an additional user and database, add the following to `/docker-entrypoint-initdb.d/init-user-db.sh`:

```bash
#!/bin/bash
set -e

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
	CREATE USER docker;
	CREATE DATABASE docker;
	GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL
```

These initialization files will be executed in sorted name order as defined by the current locale, which defaults to `en_US.utf8`. Any `*.sql` files will be executed by `POSTGRES_USER`, which defaults to the `postgres` superuser. It is recommended that any `psql` commands that are run inside of a `*.sh` script be executed as `POSTGRES_USER` by using the `--username "$POSTGRES_USER"` flag. This user will be able to connect without a password due to the presence of `trust` authentication for Unix socket connections made inside the container.

Additionally, as of [docker-library/postgres#253](https://github.com/docker-library/postgres/pull/253), these initialization scripts are run as the `postgres` user (or as the "semi-arbitrary user" specified with the `--user` flag to `docker run`; see the section titled "Arbitrary `--user` Notes" for more details). Also, as of [docker-library/postgres#440](https://github.com/docker-library/postgres/pull/440), the temporary daemon started for these initialization scripts listens only on the Unix socket, so any `psql` usage should drop the hostname portion (see [docker-library/postgres#474 (comment)](https://github.com/docker-library/postgres/issues/474#issuecomment-416914741) for example).

## Database Configuration

There are many ways to set PostgreSQL server configuration. For information on what is available to configure, see the postgresql.org [docs](https://www.postgresql.org/docs/current/static/runtime-config.html) for the specific version of PostgreSQL that you are running. Here are a few options for setting configuration:

-	Use a custom config file. Create a config file and get it into the container. If you need a starting place for your config file you can use the sample provided by PostgreSQL which is available in the container at `/usr/share/postgresql/postgresql.conf.sample` (`/usr/local/share/postgresql/postgresql.conf.sample` in Alpine variants).

	-	**Important note:** you must set `listen_addresses = '*'`so that other containers will be able to access %%REPO%%.

	```console
	$ # get the default config
	$ docker run -i --rm postgres cat /usr/share/postgresql/postgresql.conf.sample > my-postgres.conf

	$ # customize the config

	$ # run postgres with custom config
	$ docker run -d --name some-postgres -v "$PWD/my-postgres.conf":/etc/postgresql/postgresql.conf -e POSTGRES_PASSWORD=mysecretpassword %%IMAGE%% -c 'config_file=/etc/postgresql/postgresql.conf'
	```

-	Set options directly on the run line. The entrypoint script is made so that any options passed to the docker command will be passed along to the `postgres` server daemon. From the [docs](https://www.postgresql.org/docs/current/static/app-postgres.html) we see that any option available in a `.conf` file can be set via `-c`.

	```console
	$ docker run -d --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword %%IMAGE%% -c shared_buffers=256MB -c max_connections=200
	```

## Locale Customization

You can extend the Debian-based images with a simple `Dockerfile` to set a different locale. The following example will set the default locale to `de_DE.utf8`:

```dockerfile
FROM %%IMAGE%%:9.4
RUN localedef -i de_DE -c -f UTF-8 -A /usr/share/locale/locale.alias de_DE.UTF-8
ENV LANG de_DE.utf8
```

Since database initialization only happens on container startup, this allows us to set the language before it is created.

Also of note, Alpine-based variants do *not* support locales; see ["Character sets and locale" in the musl documentation](https://wiki.musl-libc.org/functional-differences-from-glibc.html#Character-sets-and-locale) for more details.

## Additional Extensions

When using the default (Debian-based) variants, installing additional extensions (such as PostGIS) should be as simple as installing the relevant packages (see [github.com/postgis/docker-postgis](https://github.com/postgis/docker-postgis/blob/4eb614133d6aa87bfc5c952d24b7eb1f499e5c7c/12-3.0/Dockerfile) for a concrete example).

When using the Alpine variants, any postgres extension not listed in [postgres-contrib](https://www.postgresql.org/docs/10/static/contrib.html) will need to be compiled in your own image (again, see [github.com/postgis/docker-postgis](https://github.com/postgis/docker-postgis/blob/4eb614133d6aa87bfc5c952d24b7eb1f499e5c7c/12-3.0/alpine/Dockerfile) for a concrete example).

# Arbitrary `--user` Notes

As of [docker-library/postgres#253](https://github.com/docker-library/postgres/pull/253), this image supports running as a (mostly) arbitrary user via `--user` on `docker run`.

The main caveat to note is that `postgres` doesn't care what UID it runs as (as long as the owner of `/var/lib/postgresql/data` matches), but `initdb` *does* care (and needs the user to exist in `/etc/passwd`):

```console
$ docker run -it --rm --user www-data -e POSTGRES_PASSWORD=mysecretpassword %%IMAGE%%
The files belonging to this database system will be owned by user "www-data".
...

$ docker run -it --rm --user 1000:1000 -e POSTGRES_PASSWORD=mysecretpassword %%IMAGE%%
initdb: could not look up effective user ID 1000: user does not exist
```

The three easiest ways to get around this:

1.	use the Debian variants (not the Alpine variants) and thus allow the image to use [the `nss_wrapper` library](https://cwrap.org/nss_wrapper.html) to "fake" `/etc/passwd` contents for you (see [docker-library/postgres#448](https://github.com/docker-library/postgres/pull/448) for more details)

2.	bind-mount `/etc/passwd` read-only from the host (if the UID you desire is a valid user on your host):

	```console
	$ docker run -it --rm --user "$(id -u):$(id -g)" -v /etc/passwd:/etc/passwd:ro -e POSTGRES_PASSWORD=mysecretpassword %%IMAGE%%
	The files belonging to this database system will be owned by user "jsmith".
	...
	```

3.	initialize the target directory separately from the final runtime (with a `chown` in between):

	```console
	$ docker volume create pgdata
	$ docker run -it --rm -v pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=mysecretpassword %%IMAGE%%
	The files belonging to this database system will be owned by user "postgres".
	...
	( once it's finished initializing successfully and is waiting for connections, stop it )
	$ docker run -it --rm -v pgdata:/var/lib/postgresql/data bash chown -R 1000:1000 /var/lib/postgresql/data
	$ docker run -it --rm --user 1000:1000 -v pgdata:/var/lib/postgresql/data %%IMAGE%%
	LOG:  database system was shut down at 2017-01-20 00:03:23 UTC
	LOG:  MultiXact member wraparound protections are now enabled
	LOG:  autovacuum launcher started
	LOG:  database system is ready to accept connections
	```

# Caveats

If there is no database when `postgres` starts in a container, then `postgres` will create the default database for you. While this is the expected behavior of `postgres`, this means that it will not accept incoming connections during that time. This may cause issues when using automation tools, such as `docker-compose`, that start several containers simultaneously.

Also note that the default `/dev/shm` size for containers is 64MB. If the shared memory is exhausted you will encounter `ERROR:  could not resize shared memory segment . . . : No space left on device`. You will want to pass [`--shm-size=256MB`](https://docs.docker.com/engine/reference/run/#runtime-constraints-on-resources) for example to `docker run`, or alternatively in [`docker-compose`](https://docs.docker.com/compose/compose-file/#domainname-hostname-ipc-mac_address-privileged-read_only-shm_size-stdin_open-tty-user-working_dir)

See ["IPVS connection timeout issue" in the Docker Success Center](https://success.docker.com/article/ipvs-connection-timeout-issue) for details about IPVS connection timeouts which will affect long-running idle connections to PostgreSQL in Swarm Mode using overlay networks.

## Where to Store Data

**Important note:** There are several ways to store data used by applications that run in Docker containers. We encourage users of the `%%IMAGE%%` images to familiarize themselves with the options available, including:

-	Let Docker manage the storage of your database data [by writing the database files to disk on the host system using its own internal volume management](https://docs.docker.com/engine/tutorials/dockervolumes/#adding-a-data-volume). This is the default and is easy and fairly transparent to the user. The downside is that the files may be hard to locate for tools and applications that run directly on the host system, i.e. outside containers.
-	Create a data directory on the host system (outside the container) and [mount this to a directory visible from inside the container](https://docs.docker.com/engine/tutorials/dockervolumes/#mount-a-host-directory-as-a-data-volume). This places the database files in a known location on the host system, and makes it easy for tools and applications on the host system to access the files. The downside is that the user needs to make sure that the directory exists, and that e.g. directory permissions and other security mechanisms on the host system are set up correctly.

The Docker documentation is a good starting point for understanding the different storage options and variations, and there are multiple blogs and forum postings that discuss and give advice in this area. We will simply show the basic procedure here for the latter option above:

1.	Create a data directory on a suitable volume on your host system, e.g. `/my/own/datadir`.
2.	Start your `%%IMAGE%%` container like this:

	```console
	$ docker run --name some-%%REPO%% -v /my/own/datadir:/var/lib/postgresql/data -e POSTGRES_PASSWORD=mysecretpassword -d %%IMAGE%%:tag
	```

The `-v /my/own/datadir:/var/lib/postgresql/data` part of the command mounts the `/my/own/datadir` directory from the underlying host system as `/var/lib/postgresql/data` inside the container, where PostgreSQL by default will write its data files.


text:
layout: feature
title: 'Aspect'
shortdef: 'aspect'
udver: '2'
---

  Values:
  Hab
  Imp
  Iter
  Perf
  Prog
  Prosp
  Frus

Aspect is typically a feature of [verbs](u-pos/VERB).
It may also occur with other parts of speech
([nouns](u-pos/NOUN), [adjectives](u-pos/ADJ), [adverbs](u-pos/ADV)),
depending on whether borderline word forms such as gerunds and participles
are classified as verbs or as the other category.

Aspect is a feature that specifies duration of the action in time,
whether the action has been completed etc. In some languages
(e.g. English), some [tenses](Tense) are actually combinations of
tense and aspect. In other languages (e.g. Czech), aspect and tense
are separate, although not completely independent of each other.

In Czech and other Slavic languages, aspect is a lexical feature.
Pairs of imperfective and perfective verbs exist and are often
morphologically related but the space is highly irregular and the
verbs are considered to belong to separate lemmas.

Since we proceed bottom-up, the current standard covers only a few
aspect values found in corpora.  See Wikipedia
(<http://en.wikipedia.org/wiki/Grammatical_aspect>) for a long list of
other possible aspects.

### `Imp`: imperfect aspect

The action took / takes / will take some time span and there is no
information whether and when it was / will be completed.

#### Examples

* [cs] _péci_ "to bake" (Imp); _pekl chleba_ "he baked / was
  baking a bread"

### `Perf`: perfect aspect

The action has been / will have been completed. Since there is
emphasis on one point on the time scale (the point of completion),
this aspect does not work well with the present tense. For example,
Czech morphology can create present forms of perfective verbs but
these actually have a future meaning.

#### Examples

* [cs] _upéci_ "to bake" (Perf); _upekl chleba_ "he baked / has
  baked a bread"

### `Prosp`: prospective aspect

In general, prospective aspect can be described as relative future:
the action is/was/will be expected to take place at a moment that
follows the reference point; the reference point itself can be
in past, present or future.
In the English sentence
_When I got home yesterday, John called and said he would arrive soon,_
the last clause _(he would arrive soon)_ is in prospective aspect.
Nevertheless, English does not have overt affixal morphemes dedicated
to the prospective aspect, and we do not need the label in English.
But other languages do; the _-ko_ suffix in Basque is an example.

Note that this value was called `Pro` in UD v1 and it has been renamed `Prosp`
in UD v2.

#### Examples

* [eu] _Liburua irakurriko behar du._ lit. _book-a read-Prosp must AUX_ "He must go to read a book."

### `Prog`: progressive aspect

English progressive tenses (_I am eating, I have been doing …_)
have this aspect. They are constructed analytically (auxiliary +
present participle) but the _-ing_ participle is so bound to
progressive meaning that it seems a good idea to annotate it with this
feature (we have to distinguish it from the past participle somehow;
we may use both the "Tense" and the "Aspect" features).

In languages other than English, the progressive meaning may be
expressed by morphemes bound to the main verb, which makes this value
even more justified. Example is Turkish with its two distinct progressive
morphemes, _-yor_ and _-mekte._

#### Examples

* [tr] _eve gidiyor_ "she is going home (now)"
* [tr] _eve gitmekte_ "she is going home (now)"
* [tr] _eve gidiyordu_ "she was going home (when I saw her)"
* [tr] _eve gimekteydi_ "she was going home (when I saw her)"

### `Hab`: habitual aspect

English simple present has this aspect.

#### Examples

* [en] _he attends classes of Japanese_

### `Iter`: iterative / frequentative aspect

Denotes repeated action. Attested e.g. in Hungarian.
Iteratives also exist in Czech with this name but their meaning is rather habitual.
They can be formed
only from imperfective verbs and they are usually not classified as a separate
aspect; they are just `Aspect=Imp.`

Note: This value is new in UD v2 but a similar value has been used in UD v1
as language-specific for Hungarian, though it was called _frequentative_ there
(`Freq`).

#### Examples

* [hu] _üt_ "hit", _ütöget_ "hit several times"

### `Frus`: frustative aspect

"Frustrative is a grammatical marker that expresses the non-realization of some expected outcome implied by the proposition expressed in the marked clause." (Overall 2017)

"The frustrative is a functional element found in a number of languages which expresses, in its typical use, that an action did not have its intended consequences [...]" (Salanova)

'The frustrative particle in Kimaragang marks unrealized expectations or intentions, counter-
factuals, etc." (Kroeger 2017)

#### References

Kroeger, Paul. 2017. Frustration, culmination, and inertia in Kimaragang grammar. *Glossa: a journal of general linguistics* 2(1): 56. 1–29, DOI: [https://doi.org/10.5334/gjgl.146](https://doi.org/10.5334/gjgl.146)

Overall, S. (2017). A Typology of Frustrative Marking in Amazonian Languages. In A. Aikhenvald & R. Dixon (Eds.), *The Cambridge Handbook of Linguistic Typology* (Cambridge Handbooks in Language and Linguistics, pp. 477-512). Cambridge: Cambridge University Press. doi:10.1017/9781316135716.015

Salanova, Andrés Pablo. *A semantics for frustratives.* [https://www.mcgill.ca/linguistics/files/linguistics/a_semantics_for_frustratives.pdf](https://www.mcgill.ca/linguistics/files/linguistics/a_semantics_for_frustratives.pdf)

#### Examples

Examples cited by Avila (2021) (our English translations):

* [yrl] _Indé rewewé yepé kutara [...] _  "You were flying fast in vain [...]" (Casasnovas, 93)
* [yrl] _Apurakí-putari yepé, ixé se maraari.  _  "I wanted to work, but I'm tired." (Magalhães, 96, adap.)


text:
package com.mitchtalmadge.shillorkill.web;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.mitchtalmadge.shillorkill.service.LogService;
import com.mitchtalmadge.shillorkill.service.SpringProfileService;
import com.mitchtalmadge.shillorkill.web.api.APIResponse;
import com.mitchtalmadge.shillorkill.web.api.validators.APIRequestValidator;
import org.apache.catalina.connector.ClientAbortException;
import org.hibernate.MappingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class WebExceptionHandler extends ResponseEntityExceptionHandler {

    private final ResourceLoader resourceLoader;
    private final SpringProfileService springProfileService;
    private final LogService logService;

    @Autowired
    public WebExceptionHandler(ResourceLoader resourceLoader,
                               SpringProfileService springProfileService,
                               LogService logService) {
        this.resourceLoader = resourceLoader;
        this.springProfileService = springProfileService;
        this.logService = logService;
    }

    @Override
    protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        if (ex.getRequestURL().startsWith("/api"))
            // For API calls, send a not found error.
            return APIResponse.statusNotFound("The resource you have tried to access could not be found.");
        else {
            // Load the requested resource.
            Resource resource = this.resourceLoader.getResource("classpath:static" + ex.getRequestURL());

            // If it doesn't exist, load index.html
            if (!resource.exists() || ex.getRequestURL().equals("/")) {
                resource = this.resourceLoader.getResource("classpath:static/index.html");

                // If index.html doesn't exist, something is wrong internally.
                if (!resource.exists())
                    return APIResponse.statusInternalServerError();
            }

            // Send the resource.
            return new ResponseEntity<>(resource, HttpStatus.OK);
        }
    }

    @Override
    protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        if (ex.getCause() instanceof InvalidFormatException)
            return handleInvalidFormatException((InvalidFormatException) ex.getCause());

        logService.logException(getClass(), ex, "Could not parse HTTP message");
        return APIResponse.statusBadRequestNotParsable("The request could not be parsed.");
    }

    @ExceptionHandler(InvalidFormatException.class)
    protected APIResponse handleInvalidFormatException(InvalidFormatException ex) {
        return APIResponse.statusBadRequestNotParsable("Could not parse value: " + ex.getValue());
    }

    @ExceptionHandler(MappingException.class)
    protected APIResponse handleModelMappingException(MappingException ex) {
        logService.logException(getClass(), ex, "An error occurred while mapping an object to a DTO");
        return APIResponse.statusInternalServerError();
    }

    @ExceptionHandler(IllegalArgumentException.class)
    protected APIResponse handleIllegalArgumentException(IllegalArgumentException ex) {
        logService.logException(getClass(), ex, "An error occurred while processing an endpoint request");
        return APIResponse.statusInternalServerError();
    }

    @ExceptionHandler(APIRequestValidator.ValidationException.class)
    protected ResponseEntity<?> handleAPIRequestValidationException(APIRequestValidator.ValidationException ex) {
        return ex.getApiResponse();
    }

    @Override
    protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return APIResponse.statusUnsupportedMediaType(ex.getContentType());
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    protected APIResponse handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex) {
        return APIResponse.statusBadRequest("invalid_path_variable", "The passed in value for the '" + ex.getName() + "' path variable is not valid.");
    }

    @ExceptionHandler(ClientAbortException.class)
    protected void handleClientAbortException(ClientAbortException e) {
        logService.logError(getClass(), "A client connection was aborted: " + e.getMessage());
    }

    @Override
    protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return APIResponse.statusBadRequest("missing_parameter", "The request parameter '" + ex.getParameterName() + "' was not supplied.");
    }

    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        if (ex instanceof HttpRequestMethodNotSupportedException) {
            return APIResponse.statusMethodNotAllowed(((HttpRequestMethodNotSupportedException) ex).getMethod());
        }
        logService.logException(getClass(), ex, "An error occurred while processing an endpoint request");
        return APIResponse.statusInternalServerError();
    }
}


text:
id: 106
title: Vou para Natal-RN, II Natal Java Day
date: 2006-10-26T14:57:14+00:00
author: Claudio Miranda
layout: post
permalink: /2006/10/Vou-para-Natal-RN-II-Natal-Java-Day/
categories:
  - Java
---
[![II Natal Java Day](http://www.j2eebrasil.com.br/nataljavaday/images/logo_NJD.gif)](http://www.j2eebrasil.com.br/nataljavaday/)

Fui convidado pelo amigo Gleydson do JUG de Natal-RN a participar do [II Natal Java Day](http://www.j2eebrasil.com.br/nataljavaday/), [veja a programação](http://www.j2eebrasil.com.br/nataljavaday/programacao.jsp). Será no próximo sábado.

Para mim será uma ótima experiência, conhecer o trabalho e conversar com entusiastas da tecnologia Java.

Se você estiver por perto da Faculdade Natalense, passe pelo evento, pois acredito que será uma ótima oportunidade para a região.


text:
<?php

/*
Works out how which segments of the stream were viewed, and logs them as $start-$end, then works out session lengths
*/
class ViewSessions extends Parser {

	// The start and end time of each "viewing" session
	public $sessions = array();

	// The length of each viewing session
	public $sessionlength = array();

	public function log (&$record) {
		$file = $record['object'];

		$this->sessions[$file][] = $record['startMediaTime'] . '-' . $record['endMediaTime'];
		$this->sessionlength[$file][] = $record['endMediaTime'] - $record['startMediaTime'];

	}

	public function finish() {}

	public function toString() {}

	public function save($fileprefix) {

		// Make a list of session lengths
		foreach ($this->sessionlength as $game => $sessionlength) {

			$fp = fopen ($fileprefix . $game . '_views_sessions', 'w');

			foreach ($sessionlength as $length) {
				fwrite($fp, "$length\n");
			}

			fclose($fp);
		}

		// Make a list of actual session start and end times
		foreach ($this->sessions as $game => $sessions) {
			sort ($sessions, SORT_NUMERIC);

			$fp = fopen ($fileprefix . $game . '_views_start', 'w');

			foreach ($sessions as $time) {
				list ($start, $end) = explode('-', $time);
				fwrite($fp, "$start\t$end\t" . ($end - $start) . "\n");
			}

			fclose($fp);
		}
	}

}

?>


text:
package matgr.ai.neuralnet.feedforward;

import matgr.ai.neuralnet.Neuron;
import matgr.ai.neuralnet.NeuronFactory;
import matgr.ai.neuralnet.NeuronState;

import java.lang.reflect.Array;

public class ConvolutionDimensions {

    public final int inputWidth;
    public final int inputHeight;

    public final int kernelWidth;
    public final int kernelHeight;

    public final int strideX;
    public final int strideY;

    public final int outputWidth;
    public final int outputHeight;

    public final int paddingX;
    public final int paddingY;

    public ConvolutionDimensions(int inputWidth,
                                 int inputHeight,
                                 int kernelWidth,
                                 int kernelHeight) {

        this(inputWidth, inputHeight, kernelWidth, kernelHeight, 1, 1);
    }

    public ConvolutionDimensions(int inputWidth,
                                 int inputHeight,
                                 int kernelWidth,
                                 int kernelHeight,
                                 int strideX,
                                 int strideY) {

        this(inputWidth, inputHeight, kernelWidth, kernelHeight, strideX, strideY, 0, 0);
    }

    private ConvolutionDimensions(int inputWidth,
                                  int inputHeight,
                                  int kernelWidth,
                                  int kernelHeight,
                                  int strideX,
                                  int strideY,
                                  int paddingX,
                                  int paddingY) {

        // TODO: pretty sure larger strides don't make sense... (there will be gaps... if gaps end up being
        //       valid, the convolutions should center the kernels?)
        if (strideX > kernelWidth) {
            throw new IllegalArgumentException("Invalid horizontal stride");
        }
        if (strideY > kernelHeight) {
            throw new IllegalArgumentException("Invalid vertical stride");
        }

        this.kernelWidth = kernelWidth;
        this.kernelHeight = kernelHeight;

        this.inputWidth = inputWidth;
        this.inputHeight = inputHeight;

        this.strideX = strideX;
        this.strideY = strideY;

        // TODO: automatically pad where necessary?
        this.paddingX = paddingX;
        this.paddingY = paddingY;

        this.outputWidth = 1 + (this.inputWidth - this.kernelWidth + (2 * paddingX)) / strideX;
        this.outputHeight = 1 + (this.inputHeight - this.kernelHeight + (2 * paddingY)) / strideY;

        if (this.outputWidth < 0) {
            throw new IllegalArgumentException("Invalid kernel width");
        }
        if (this.outputHeight < 0) {
            throw new IllegalArgumentException("Invalid kernel height");
        }
    }

    public ConvolutionDimensions deepClone() {

        return new ConvolutionDimensions(
                inputWidth,
                inputHeight,
                kernelWidth,
                kernelHeight,
                strideX,
                strideY,
                paddingX,
                paddingY);
    }

    public int inputCount() {
        return inputWidth * inputHeight;
    }

    public int outputCount() {
        return outputWidth * outputHeight;
    }

    public static <NeuronT extends Neuron> NeuronState<NeuronT>[][] createHiddenNeuronArray(
            NeuronFactory<NeuronT> neuronFactory,
            int width,
            int height) {

        NeuronState<NeuronT>[][] neurons = createEmptyNeuronArray(width, height);

        for (int y = 0; y < height; y++) {

            NeuronState<NeuronT>[] row = neurons[y];

            for (int x = 0; x < width; x++) {

                NeuronT neuron = neuronFactory.createHidden();
                row[x] = new NeuronState<>(neuron);
            }
        }

        return neurons;
    }

    public static <NeuronT extends Neuron> NeuronState<NeuronT>[][] deepCloneNeuronArray(
            NeuronState<NeuronT>[][] neurons,
            int width,
            int height) {

        NeuronState<NeuronT>[][] neuronsClone = createEmptyNeuronArray(width, height);

        for (int y = 0; y < height; y++) {

            NeuronState<NeuronT>[] sourceRow = neurons[y];
            NeuronState<NeuronT>[] targetRow = neuronsClone[y];

            for (int x = 0; x < width; x++) {

                targetRow[x] = sourceRow[x].deepClone();
            }
        }

        return neurons;
    }

    public static <NeuronT extends Neuron> NeuronState<NeuronT>[][] createEmptyNeuronArray(int width, int height) {

        @SuppressWarnings("unchecked")
        NeuronState<NeuronT>[][] neurons = (NeuronState<NeuronT>[][]) Array.newInstance(
                NeuronState.class,
                height,
                width);

        return neurons;
    }
}


text:
layout: default
title: WebRTC Team @ IETF 81 Meeting in Québec, Canada
author: Serge Lachapelle
date: 2011-07-06 04:55:00
---

Members of the team (@juberti, @alvestrand, @jtlinden) will be attending
[IETF 81 in Québec, Canada, July 24th to July 30th][1]. We will also be
attending the [W3C F2F][2] on Saturday, July 23rd.

[1]: https://www.ietf.org/proceedings/81/index.html
[2]: http://www.w3.org/2011/04/webrtc/Overview.html#meeting


text:
namespace verible {
namespace lsp {
absl::Status MessageStreamSplitter::PullFrom(const ReadFun &read_fun) {
  if (!message_processor_) {
    return absl::FailedPreconditionError(
        "MessageStreamSplitter: Message processor not yet set, needed "
        "before PullFrom() called");
  }
  return ReadInput(read_fun);
}

// Return -1 if header is incomplete (not enough data yet).
// Return -2 if header complete, but does not contain a valid
//    Content-Length header (i.e. an actual problem)
// On success, returns the offset to the body and its size in "body_size"
static constexpr int kIncompleteHeader = -1;
static constexpr int kGarbledHeader = -2;
int MessageStreamSplitter::ParseHeaderGetBodyOffset(absl::string_view data,
                                                    int *body_size) {
  static constexpr absl::string_view kEndHeaderMarker = "\r\n\r\n";
  static constexpr absl::string_view kLenientEndHeaderMarker = "\n\n";
  static constexpr absl::string_view kContentLengthHeader = "Content-Length: ";

  int header_marker_len = kEndHeaderMarker.length();
  auto end_of_header = data.find(kEndHeaderMarker);
  if (end_of_header == absl::string_view::npos && lenient_lf_separation_) {
    end_of_header = data.find(kLenientEndHeaderMarker);
    header_marker_len = kLenientEndHeaderMarker.length();
  }
  if (end_of_header == absl::string_view::npos) return kIncompleteHeader;

  // Very dirty search for header - we don't check if starts with line.
  const absl::string_view header_content(data.data(), end_of_header);
  auto found_ContentLength_header = header_content.find(kContentLengthHeader);
  if (found_ContentLength_header == absl::string_view::npos) {
    return kGarbledHeader;
  }

  size_t end_key = found_ContentLength_header + kContentLengthHeader.size();
  if (!absl::SimpleAtoi(header_content.substr(end_key), body_size)) {
    return kGarbledHeader;
  }

  return end_of_header + header_marker_len;
}

// Read from data and process all fully available messages found in data.
// Updates "data" to return the remaining unprocessed data.
// Returns ok() status encountered a corrupted header.
absl::Status MessageStreamSplitter::ProcessContainedMessages(
    absl::string_view *data) {
  while (!data->empty()) {
    int body_size = 0;
    const int body_offset = ParseHeaderGetBodyOffset(*data, &body_size);
    if (body_offset == kGarbledHeader) {
      absl::string_view limited_view(
          data->data(), std::min(data->size(), static_cast<size_t>(256)));
      return absl::InvalidArgumentError(
          absl::StrCat("No `Content-Length:` header. '", limited_view, "...'"));
    }

    const int message_size = body_offset + body_size;
    if (body_offset == kIncompleteHeader ||
        message_size > static_cast<int>(data->size())) {
      return absl::OkStatus();  // Only insufficient partial buffer available.
    }

    absl::string_view header(data->data(), body_offset);
    absl::string_view body(data->data() + body_offset, body_size);
    message_processor_(header, body);

    stats_largest_body_ = std::max(stats_largest_body_, body.size());

    *data = {data->data() + message_size, data->size() - message_size};
  }
  return absl::OkStatus();
}

// Read from "read_fun", fill internal buffer and call all available
// complete messages in it.
absl::Status MessageStreamSplitter::ReadInput(const ReadFun &read_fun) {
  size_t write_offset = 0;

  // Move all we had left from last time to the beginning of the buffer.
  // This is in the same buffer, so we need to memmove()
  if (!pending_data_.empty()) {
    memmove(read_buffer_.data(), pending_data_.data(), pending_data_.size());
    write_offset = pending_data_.size();
  }

  if (write_offset == read_buffer_.size()) {
    read_buffer_.resize(2 * read_buffer_.size());
  }

  const int free_space = read_buffer_.size() - write_offset;
  int bytes_read = read_fun(read_buffer_.data() + write_offset, free_space);
  if (bytes_read <= 0) {
    // Got EOF.
    // If we still have data pending, regard this as data loss situation, as
    // we were never able to fully read the last message and send to process.
    // Otherwise, report 'Unavailable' to indicate EOF (meh, this should
    // be a better message).
    if (!pending_data_.empty()) {
      return absl::DataLossError(
          absl::StrCat("Got EOF, but still have incomplete message with ",
                       pending_data_.size(), " bytes read so far."));
    }
    return absl::UnavailableError(absl::StrCat("read() returned ", bytes_read));
  }
  stats_total_bytes_read_ += bytes_read;

  absl::string_view data(read_buffer_.data(), write_offset + bytes_read);
  if (auto status = ProcessContainedMessages(&data); !status.ok()) {
    return status;
  }

  pending_data_ = data;  // Remember for next round.

  return absl::OkStatus();
}
}  // namespace lsp
}  // namespace verible


text:
/*
 * File         : HYBDevice.java
 * Author       : Aamir Shafi, Mohsan Jameel, Ansar Javed, Bibrak Qamar
 * Created      : Mon Aug  5 12:22:15 PKT 2013
 * Revision     : $Revision: 1.28 $
 * Updated      : $Date: 2013/12/17 17:24:47 $
 *
 */

package xdev.hybdev;

import java.util.UUID;
import java.nio.*;
import mpjdev.*;
import xdev.*;

import mpjbuf.RawBuffer ;

public abstract class HYBRequest
    extends Request {

  HYBRequest nextCompleted, prevCompleted ;
  boolean inCompletedList ;

  HYBDevice device ;

  /* buffers for storing static/dynamic sections of the buffer */
  ByteBuffer dBuffer = null;
  RawBuffer eagerBuffer = null;
  byte[] dynamicBuffer = null;
  ByteBuffer staticBuffer;
  byte[] bytes = null;
  boolean alreadyCompleted = false ;

  boolean dSection = true, sSection = true;
  int context = -1, tag, commMode, rank_source = 0, sBufSize = 0, dBufSize = 0 ;
  int sendCounter, recvCounter, numEls = -1 ;

  UUID dstUUID, srcUUID;
  mpjdev.Status status = null;
  mpjbuf.Buffer buffer = null;
  mpjbuf.Type type = null;

  volatile boolean completed = false;

  public boolean cancel() {
    /* First start considering the sender side
     * a) Send. --> For eager-send, its not possible.
     *          --> For rendezvous, yeah, can be cancelled.
     *    Isend --> Eager-send, not possible.
     *          --> For rendezvous, not possible.
     * b) Same for Ready/Send
     * c) Bsend --> Not possible at all.
     * d) Ssend --> Possible.
     * e) Recv  --> Eager-send, not possible.
     *          --> Rendezvous-protocol.*/

    return false;
  }

  synchronized void setCompleted(boolean completed) {
    this.completed = completed;
  }

  synchronized boolean isCompleted() {
    return completed;
  }

  public static Status iwaitany(HYBRequest [] requests) {
    System.out.println(" HYBRequest.iwaitany( .. )") ;
    return null;
  }

  /**
   */
  public abstract Status iwait();

  /**
   * Method used by iwait() to actually wait for the communication to finish.
   */
  synchronized void waitMe() {
    while (!completed) {
      try {
        this.wait();
      }
      catch (Exception e) {
        e.printStackTrace() ;
      }
    }

    //device.completedList.remove(this);
    // .. remove from completedList ..
  }

  /**
   * Method used to notify that the communication operation has finished.
   */
  synchronized void notifyMe() {
    this.completed = true;

    try {
      this.notify();
    }
    catch (Exception e) {
      e.printStackTrace() ;
    }
  }

  /** this method returns Status object if the communication is completed,
   *  and if its not completed, it returns zero.
   */
  public Status itest() {
    if(alreadyCompleted) {
      return null;
    }
    synchronized (this) {
      if (this.isCompleted()) {
        return new mpjdev.Status(rank_source, tag, -1); //what is index ?
      }
      else {
        return null; //change this to something understand at higher levels ...
      }
    }
  }

  public void free() {
  }

  public boolean isnull() {
    return false;
  }
}


text:
//License

package com.ghgande.j2mod.modbus.procimg;

import com.ghgande.j2mod.modbus.util.Observable;

/**
 * Class implementing an observable register.
 *
 * @author Dieter Wimberger
 * @version 1.2rc1 (09/11/2004)
 */
public class ObservableRegister extends Observable implements Register {

	/**
	 * The word holding the content of this register.
	 */
	protected short m_Register;

	public int getValue() {
		return m_Register & 0xFFFF;
	}

	public final int toUnsignedShort() {
		return m_Register & 0xFFFF;
	}

	public final short toShort() {
		return m_Register;
	}

	public byte[] toBytes() {
		byte[] result = new byte[] { (byte) (m_Register >> 8),
									 (byte) (m_Register & 0xFF) };
		return result;
	}

	public final synchronized void setValue(int v) {
		m_Register = (short) v;
		notifyObservers("value");
	}

	public final synchronized void setValue(short s) {
		m_Register = s;
		notifyObservers("value");
	}

	public final synchronized void setValue(byte[] bytes) {
		if (bytes.length < 2) {
			throw new IllegalArgumentException();
		} else {
			m_Register = (short) (((short) ((bytes[0] << 8))) |
						 (((short) (bytes[1])) & 0xFF));
			notifyObservers("value");
		}
	}
}